##// END OF EJS Templates
fixing merge
Juan C. Espinoza -
r938:9e80eea2eb45 merge
parent child
Show More
@@ -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 import time
11 12 from multiprocessing import Process, Queue, cpu_count
12 13
13 14 import schainpy
14 15 import schainpy.admin
15 16
16 17 from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring
17 18 from xml.dom import minidom
18 19
19 20 from schainpy.model import *
20 21 from time import sleep
21 22
22 23 def prettify(elem):
23 24 """Return a pretty-printed XML string for the Element.
24 25 """
25 26 rough_string = tostring(elem, 'utf-8')
26 27 reparsed = minidom.parseString(rough_string)
27 28 return reparsed.toprettyxml(indent=" ")
28 29
29 30 def multiSchain(child, nProcess=cpu_count(), startDate=None, endDate=None, by_day=False):
30 31 skip = 0
31 32 cursor = 0
32 33 nFiles = None
33 34 processes = []
34 35 dt1 = datetime.datetime.strptime(startDate, '%Y/%m/%d')
35 36 dt2 = datetime.datetime.strptime(endDate, '%Y/%m/%d')
36 37 days = (dt2 - dt1).days
37 38
38 39 for day in range(days+1):
39 40 skip = 0
40 41 cursor = 0
41 42 q = Queue()
42 43 processes = []
43 44 dt = (dt1 + datetime.timedelta(day)).strftime('%Y/%m/%d')
44 45 firstProcess = Process(target=child, args=(cursor, skip, q, dt))
45 46 firstProcess.start()
46 47 if by_day:
47 48 continue
48 49 nFiles = q.get()
49 50 firstProcess.terminate()
50 51 skip = int(math.ceil(nFiles/nProcess))
51 52 while True:
52 53 processes.append(Process(target=child, args=(cursor, skip, q, dt)))
53 54 processes[cursor].start()
54 55 if nFiles < cursor*skip:
55 56 break
56 57 cursor += 1
57 58
58 59 def beforeExit(exctype, value, trace):
59 60 for process in processes:
60 61 process.terminate()
61 62 process.join()
62 63 print traceback.print_tb(trace)
63 64
64 65 sys.excepthook = beforeExit
65 66
66 67 for process in processes:
67 68 process.join()
68 69 process.terminate()
69 sys.exit()
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 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):
1317 1317
1318 1318 self.writeXml()
1319 1319 self.createObjects()
1320 1320 self.connectObjects()
1321 1321 self.run()
@@ -1,1228 +1,1228
1 1 '''
2 2
3 3 $Author: murco $
4 4 $Id: JROData.py 173 2012-11-20 15:06:21Z murco $
5 5 '''
6 6
7 7 import copy
8 8 import numpy
9 9 import datetime
10 10
11 11 from jroheaderIO import SystemHeader, RadarControllerHeader
12 12 from schainpy import cSchain
13 13
14 14
15 15 def getNumpyDtype(dataTypeCode):
16 16
17 17 if dataTypeCode == 0:
18 18 numpyDtype = numpy.dtype([('real','<i1'),('imag','<i1')])
19 19 elif dataTypeCode == 1:
20 20 numpyDtype = numpy.dtype([('real','<i2'),('imag','<i2')])
21 21 elif dataTypeCode == 2:
22 22 numpyDtype = numpy.dtype([('real','<i4'),('imag','<i4')])
23 23 elif dataTypeCode == 3:
24 24 numpyDtype = numpy.dtype([('real','<i8'),('imag','<i8')])
25 25 elif dataTypeCode == 4:
26 26 numpyDtype = numpy.dtype([('real','<f4'),('imag','<f4')])
27 27 elif dataTypeCode == 5:
28 28 numpyDtype = numpy.dtype([('real','<f8'),('imag','<f8')])
29 29 else:
30 30 raise ValueError, 'dataTypeCode was not defined'
31 31
32 32 return numpyDtype
33 33
34 34 def getDataTypeCode(numpyDtype):
35 35
36 36 if numpyDtype == numpy.dtype([('real','<i1'),('imag','<i1')]):
37 37 datatype = 0
38 38 elif numpyDtype == numpy.dtype([('real','<i2'),('imag','<i2')]):
39 39 datatype = 1
40 40 elif numpyDtype == numpy.dtype([('real','<i4'),('imag','<i4')]):
41 41 datatype = 2
42 42 elif numpyDtype == numpy.dtype([('real','<i8'),('imag','<i8')]):
43 43 datatype = 3
44 44 elif numpyDtype == numpy.dtype([('real','<f4'),('imag','<f4')]):
45 45 datatype = 4
46 46 elif numpyDtype == numpy.dtype([('real','<f8'),('imag','<f8')]):
47 47 datatype = 5
48 48 else:
49 49 datatype = None
50 50
51 51 return datatype
52 52
53 53 def hildebrand_sekhon(data, navg):
54 54 """
55 55 This method is for the objective determination of the noise level in Doppler spectra. This
56 56 implementation technique is based on the fact that the standard deviation of the spectral
57 57 densities is equal to the mean spectral density for white Gaussian noise
58 58
59 59 Inputs:
60 60 Data : heights
61 61 navg : numbers of averages
62 62
63 63 Return:
64 64 -1 : any error
65 65 anoise : noise's level
66 66 """
67 67
68 sortdata = numpy.sort(data,axis=None)
68 sortdata = numpy.sort(data, axis=None)
69 69 # lenOfData = len(sortdata)
70 70 # nums_min = lenOfData*0.2
71 71 #
72 72 # if nums_min <= 5:
73 73 # nums_min = 5
74 74 #
75 75 # sump = 0.
76 76 #
77 77 # sumq = 0.
78 78 #
79 79 # j = 0
80 80 #
81 81 # cont = 1
82 82 #
83 83 # while((cont==1)and(j<lenOfData)):
84 84 #
85 85 # sump += sortdata[j]
86 86 #
87 87 # sumq += sortdata[j]**2
88 88 #
89 89 # if j > nums_min:
90 90 # rtest = float(j)/(j-1) + 1.0/navg
91 91 # if ((sumq*j) > (rtest*sump**2)):
92 92 # j = j - 1
93 93 # sump = sump - sortdata[j]
94 94 # sumq = sumq - sortdata[j]**2
95 95 # cont = 0
96 96 #
97 97 # j += 1
98 98 #
99 99 # lnoise = sump /j
100 100 #
101 101 # return lnoise
102 102
103 103 return cSchain.hildebrand_sekhon(sortdata, navg)
104 104
105 105
106 106 class Beam:
107 107
108 108 def __init__(self):
109 109 self.codeList = []
110 110 self.azimuthList = []
111 111 self.zenithList = []
112 112
113 113 class GenericData(object):
114 114
115 115 flagNoData = True
116 116
117 117 def __init__(self):
118 118
119 119 raise NotImplementedError
120 120
121 121 def copy(self, inputObj=None):
122 122
123 123 if inputObj == None:
124 124 return copy.deepcopy(self)
125 125
126 126 for key in inputObj.__dict__.keys():
127 127
128 128 attribute = inputObj.__dict__[key]
129 129
130 130 #If this attribute is a tuple or list
131 131 if type(inputObj.__dict__[key]) in (tuple, list):
132 132 self.__dict__[key] = attribute[:]
133 133 continue
134 134
135 135 #If this attribute is another object or instance
136 136 if hasattr(attribute, '__dict__'):
137 137 self.__dict__[key] = attribute.copy()
138 138 continue
139 139
140 140 self.__dict__[key] = inputObj.__dict__[key]
141 141
142 142 def deepcopy(self):
143 143
144 144 return copy.deepcopy(self)
145 145
146 146 def isEmpty(self):
147 147
148 148 return self.flagNoData
149 149
150 150 class JROData(GenericData):
151 151
152 152 # m_BasicHeader = BasicHeader()
153 153 # m_ProcessingHeader = ProcessingHeader()
154 154
155 155 systemHeaderObj = SystemHeader()
156 156
157 157 radarControllerHeaderObj = RadarControllerHeader()
158 158
159 159 # data = None
160 160
161 161 type = None
162 162
163 163 datatype = None #dtype but in string
164 164
165 165 # dtype = None
166 166
167 167 # nChannels = None
168 168
169 169 # nHeights = None
170 170
171 171 nProfiles = None
172 172
173 173 heightList = None
174 174
175 175 channelList = None
176 176
177 177 flagDiscontinuousBlock = False
178 178
179 179 useLocalTime = False
180 180
181 181 utctime = None
182 182
183 183 timeZone = None
184 184
185 185 dstFlag = None
186 186
187 187 errorCount = None
188 188
189 189 blocksize = None
190 190
191 191 # nCode = None
192 192 #
193 193 # nBaud = None
194 194 #
195 195 # code = None
196 196
197 197 flagDecodeData = False #asumo q la data no esta decodificada
198 198
199 199 flagDeflipData = False #asumo q la data no esta sin flip
200 200
201 201 flagShiftFFT = False
202 202
203 203 # ippSeconds = None
204 204
205 205 # timeInterval = None
206 206
207 207 nCohInt = None
208 208
209 209 # noise = None
210 210
211 211 windowOfFilter = 1
212 212
213 213 #Speed of ligth
214 214 C = 3e8
215 215
216 216 frequency = 49.92e6
217 217
218 218 realtime = False
219 219
220 220 beacon_heiIndexList = None
221 221
222 222 last_block = None
223 223
224 224 blocknow = None
225 225
226 226 azimuth = None
227 227
228 228 zenith = None
229 229
230 230 beam = Beam()
231 231
232 232 profileIndex = None
233 233
234 234 def __init__(self):
235 235
236 236 raise NotImplementedError
237 237
238 238 def getNoise(self):
239 239
240 240 raise NotImplementedError
241 241
242 242 def getNChannels(self):
243 243
244 244 return len(self.channelList)
245 245
246 246 def getChannelIndexList(self):
247 247
248 248 return range(self.nChannels)
249 249
250 250 def getNHeights(self):
251 251
252 252 return len(self.heightList)
253 253
254 254 def getHeiRange(self, extrapoints=0):
255 255
256 256 heis = self.heightList
257 257 # deltah = self.heightList[1] - self.heightList[0]
258 258 #
259 259 # heis.append(self.heightList[-1])
260 260
261 261 return heis
262 262
263 263 def getDeltaH(self):
264 264
265 265 delta = self.heightList[1] - self.heightList[0]
266 266
267 267 return delta
268 268
269 269 def getltctime(self):
270 270
271 271 if self.useLocalTime:
272 272 return self.utctime - self.timeZone*60
273 273
274 274 return self.utctime
275 275
276 276 def getDatatime(self):
277 277
278 278 datatimeValue = datetime.datetime.utcfromtimestamp(self.ltctime)
279 279 return datatimeValue
280 280
281 281 def getTimeRange(self):
282 282
283 283 datatime = []
284 284
285 285 datatime.append(self.ltctime)
286 286 datatime.append(self.ltctime + self.timeInterval+1)
287 287
288 288 datatime = numpy.array(datatime)
289 289
290 290 return datatime
291 291
292 292 def getFmaxTimeResponse(self):
293 293
294 294 period = (10**-6)*self.getDeltaH()/(0.15)
295 295
296 296 PRF = 1./(period * self.nCohInt)
297 297
298 298 fmax = PRF
299 299
300 300 return fmax
301 301
302 302 def getFmax(self):
303 303
304 304 PRF = 1./(self.ippSeconds * self.nCohInt)
305 305
306 306 fmax = PRF
307 307
308 308 return fmax
309 309
310 310 def getVmax(self):
311 311
312 312 _lambda = self.C/self.frequency
313 313
314 314 vmax = self.getFmax() * _lambda/2
315 315
316 316 return vmax
317 317
318 318 def get_ippSeconds(self):
319 319 '''
320 320 '''
321 321 return self.radarControllerHeaderObj.ippSeconds
322 322
323 323 def set_ippSeconds(self, ippSeconds):
324 324 '''
325 325 '''
326 326
327 327 self.radarControllerHeaderObj.ippSeconds = ippSeconds
328 328
329 329 return
330 330
331 331 def get_dtype(self):
332 332 '''
333 333 '''
334 334 return getNumpyDtype(self.datatype)
335 335
336 336 def set_dtype(self, numpyDtype):
337 337 '''
338 338 '''
339 339
340 340 self.datatype = getDataTypeCode(numpyDtype)
341 341
342 342 def get_code(self):
343 343 '''
344 344 '''
345 345 return self.radarControllerHeaderObj.code
346 346
347 347 def set_code(self, code):
348 348 '''
349 349 '''
350 350 self.radarControllerHeaderObj.code = code
351 351
352 352 return
353 353
354 354 def get_ncode(self):
355 355 '''
356 356 '''
357 357 return self.radarControllerHeaderObj.nCode
358 358
359 359 def set_ncode(self, nCode):
360 360 '''
361 361 '''
362 362 self.radarControllerHeaderObj.nCode = nCode
363 363
364 364 return
365 365
366 366 def get_nbaud(self):
367 367 '''
368 368 '''
369 369 return self.radarControllerHeaderObj.nBaud
370 370
371 371 def set_nbaud(self, nBaud):
372 372 '''
373 373 '''
374 374 self.radarControllerHeaderObj.nBaud = nBaud
375 375
376 376 return
377 377
378 378 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
379 379 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
380 380 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
381 381 #noise = property(getNoise, "I'm the 'nHeights' property.")
382 382 datatime = property(getDatatime, "I'm the 'datatime' property")
383 383 ltctime = property(getltctime, "I'm the 'ltctime' property")
384 384 ippSeconds = property(get_ippSeconds, set_ippSeconds)
385 385 dtype = property(get_dtype, set_dtype)
386 386 # timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
387 387 code = property(get_code, set_code)
388 388 nCode = property(get_ncode, set_ncode)
389 389 nBaud = property(get_nbaud, set_nbaud)
390 390
391 391 class Voltage(JROData):
392 392
393 393 #data es un numpy array de 2 dmensiones (canales, alturas)
394 394 data = None
395 395
396 396 def __init__(self):
397 397 '''
398 398 Constructor
399 399 '''
400 400
401 401 self.useLocalTime = True
402 402
403 403 self.radarControllerHeaderObj = RadarControllerHeader()
404 404
405 405 self.systemHeaderObj = SystemHeader()
406 406
407 407 self.type = "Voltage"
408 408
409 409 self.data = None
410 410
411 411 # self.dtype = None
412 412
413 413 # self.nChannels = 0
414 414
415 415 # self.nHeights = 0
416 416
417 417 self.nProfiles = None
418 418
419 419 self.heightList = None
420 420
421 421 self.channelList = None
422 422
423 423 # self.channelIndexList = None
424 424
425 425 self.flagNoData = True
426 426
427 427 self.flagDiscontinuousBlock = False
428 428
429 429 self.utctime = None
430 430
431 431 self.timeZone = None
432 432
433 433 self.dstFlag = None
434 434
435 435 self.errorCount = None
436 436
437 437 self.nCohInt = None
438 438
439 439 self.blocksize = None
440 440
441 441 self.flagDecodeData = False #asumo q la data no esta decodificada
442 442
443 443 self.flagDeflipData = False #asumo q la data no esta sin flip
444 444
445 445 self.flagShiftFFT = False
446 446
447 447 self.flagDataAsBlock = False #Asumo que la data es leida perfil a perfil
448 448
449 449 self.profileIndex = 0
450 450
451 451 def getNoisebyHildebrand(self, channel = None):
452 452 """
453 453 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
454 454
455 455 Return:
456 456 noiselevel
457 457 """
458 458
459 459 if channel != None:
460 460 data = self.data[channel]
461 461 nChannels = 1
462 462 else:
463 463 data = self.data
464 464 nChannels = self.nChannels
465 465
466 466 noise = numpy.zeros(nChannels)
467 467 power = data * numpy.conjugate(data)
468 468
469 469 for thisChannel in range(nChannels):
470 470 if nChannels == 1:
471 471 daux = power[:].real
472 472 else:
473 473 daux = power[thisChannel,:].real
474 474 noise[thisChannel] = hildebrand_sekhon(daux, self.nCohInt)
475 475
476 476 return noise
477 477
478 478 def getNoise(self, type = 1, channel = None):
479 479
480 480 if type == 1:
481 481 noise = self.getNoisebyHildebrand(channel)
482 482
483 483 return noise
484 484
485 485 def getPower(self, channel = None):
486 486
487 487 if channel != None:
488 488 data = self.data[channel]
489 489 else:
490 490 data = self.data
491 491
492 492 power = data * numpy.conjugate(data)
493 493 powerdB = 10*numpy.log10(power.real)
494 494 powerdB = numpy.squeeze(powerdB)
495 495
496 496 return powerdB
497 497
498 498 def getTimeInterval(self):
499 499
500 500 timeInterval = self.ippSeconds * self.nCohInt
501 501
502 502 return timeInterval
503 503
504 504 noise = property(getNoise, "I'm the 'nHeights' property.")
505 505 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
506 506
507 507 class Spectra(JROData):
508 508
509 509 #data spc es un numpy array de 2 dmensiones (canales, perfiles, alturas)
510 510 data_spc = None
511 511
512 512 #data cspc es un numpy array de 2 dmensiones (canales, pares, alturas)
513 513 data_cspc = None
514 514
515 515 #data dc es un numpy array de 2 dmensiones (canales, alturas)
516 516 data_dc = None
517 517
518 518 #data power
519 519 data_pwr = None
520 520
521 521 nFFTPoints = None
522 522
523 523 # nPairs = None
524 524
525 525 pairsList = None
526 526
527 527 nIncohInt = None
528 528
529 529 wavelength = None #Necesario para cacular el rango de velocidad desde la frecuencia
530 530
531 531 nCohInt = None #se requiere para determinar el valor de timeInterval
532 532
533 533 ippFactor = None
534 534
535 535 profileIndex = 0
536 536
537 537 plotting = "spectra"
538 538
539 539 def __init__(self):
540 540 '''
541 541 Constructor
542 542 '''
543 543
544 544 self.useLocalTime = True
545 545
546 546 self.radarControllerHeaderObj = RadarControllerHeader()
547 547
548 548 self.systemHeaderObj = SystemHeader()
549 549
550 550 self.type = "Spectra"
551 551
552 552 # self.data = None
553 553
554 554 # self.dtype = None
555 555
556 556 # self.nChannels = 0
557 557
558 558 # self.nHeights = 0
559 559
560 560 self.nProfiles = None
561 561
562 562 self.heightList = None
563 563
564 564 self.channelList = None
565 565
566 566 # self.channelIndexList = None
567 567
568 568 self.pairsList = None
569 569
570 570 self.flagNoData = True
571 571
572 572 self.flagDiscontinuousBlock = False
573 573
574 574 self.utctime = None
575 575
576 576 self.nCohInt = None
577 577
578 578 self.nIncohInt = None
579 579
580 580 self.blocksize = None
581 581
582 582 self.nFFTPoints = None
583 583
584 584 self.wavelength = None
585 585
586 586 self.flagDecodeData = False #asumo q la data no esta decodificada
587 587
588 588 self.flagDeflipData = False #asumo q la data no esta sin flip
589 589
590 590 self.flagShiftFFT = False
591 591
592 592 self.ippFactor = 1
593 593
594 594 #self.noise = None
595 595
596 596 self.beacon_heiIndexList = []
597 597
598 598 self.noise_estimation = None
599 599
600 600
601 601 def getNoisebyHildebrand(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
602 602 """
603 603 Determino el nivel de ruido usando el metodo Hildebrand-Sekhon
604 604
605 605 Return:
606 606 noiselevel
607 607 """
608 608
609 609 noise = numpy.zeros(self.nChannels)
610 610
611 611 for channel in range(self.nChannels):
612 612 daux = self.data_spc[channel,xmin_index:xmax_index,ymin_index:ymax_index]
613 613 noise[channel] = hildebrand_sekhon(daux, self.nIncohInt)
614 614
615 615 return noise
616 616
617 617 def getNoise(self, xmin_index=None, xmax_index=None, ymin_index=None, ymax_index=None):
618 618
619 619 if self.noise_estimation is not None:
620 620 return self.noise_estimation #this was estimated by getNoise Operation defined in jroproc_spectra.py
621 621 else:
622 622 noise = self.getNoisebyHildebrand(xmin_index, xmax_index, ymin_index, ymax_index)
623 623 return noise
624 624
625 625 def getFreqRangeTimeResponse(self, extrapoints=0):
626 626
627 627 deltafreq = self.getFmaxTimeResponse() / (self.nFFTPoints*self.ippFactor)
628 628 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
629 629
630 630 return freqrange
631 631
632 632 def getAcfRange(self, extrapoints=0):
633 633
634 634 deltafreq = 10./(self.getFmax() / (self.nFFTPoints*self.ippFactor))
635 635 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
636 636
637 637 return freqrange
638 638
639 639 def getFreqRange(self, extrapoints=0):
640 640
641 641 deltafreq = self.getFmax() / (self.nFFTPoints*self.ippFactor)
642 642 freqrange = deltafreq*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) - deltafreq/2
643 643
644 644 return freqrange
645 645
646 646 def getVelRange(self, extrapoints=0):
647 647
648 648 deltav = self.getVmax() / (self.nFFTPoints*self.ippFactor)
649 649 velrange = deltav*(numpy.arange(self.nFFTPoints+extrapoints)-self.nFFTPoints/2.) #- deltav/2
650 650
651 651 return velrange
652 652
653 653 def getNPairs(self):
654 654
655 655 return len(self.pairsList)
656 656
657 657 def getPairsIndexList(self):
658 658
659 659 return range(self.nPairs)
660 660
661 661 def getNormFactor(self):
662 662
663 663 pwcode = 1
664 664
665 665 if self.flagDecodeData:
666 666 pwcode = numpy.sum(self.code[0]**2)
667 667 #normFactor = min(self.nFFTPoints,self.nProfiles)*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
668 668 normFactor = self.nProfiles*self.nIncohInt*self.nCohInt*pwcode*self.windowOfFilter
669 669
670 670 return normFactor
671 671
672 672 def getFlagCspc(self):
673 673
674 674 if self.data_cspc is None:
675 675 return True
676 676
677 677 return False
678 678
679 679 def getFlagDc(self):
680 680
681 681 if self.data_dc is None:
682 682 return True
683 683
684 684 return False
685 685
686 686 def getTimeInterval(self):
687 687
688 688 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt * self.nProfiles
689 689
690 690 return timeInterval
691 691
692 692 def getPower(self):
693 693
694 694 factor = self.normFactor
695 695 z = self.data_spc/factor
696 696 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
697 697 avg = numpy.average(z, axis=1)
698 698
699 699 return 10*numpy.log10(avg)
700 700
701 701 def getCoherence(self, pairsList=None, phase=False):
702 702
703 703 z = []
704 704 if pairsList is None:
705 705 pairsIndexList = self.pairsIndexList
706 706 else:
707 707 pairsIndexList = []
708 708 for pair in pairsList:
709 709 if pair not in self.pairsList:
710 710 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
711 711 pairsIndexList.append(self.pairsList.index(pair))
712 712 for i in range(len(pairsIndexList)):
713 713 pair = self.pairsList[pairsIndexList[i]]
714 714 ccf = numpy.average(self.data_cspc[pairsIndexList[i], :, :], axis=0)
715 715 powa = numpy.average(self.data_spc[pair[0], :, :], axis=0)
716 716 powb = numpy.average(self.data_spc[pair[1], :, :], axis=0)
717 717 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
718 718 if phase:
719 719 data = numpy.arctan2(avgcoherenceComplex.imag,
720 720 avgcoherenceComplex.real)*180/numpy.pi
721 721 else:
722 722 data = numpy.abs(avgcoherenceComplex)
723 723
724 724 z.append(data)
725 725
726 726 return numpy.array(z)
727 727
728 728 def setValue(self, value):
729 729
730 730 print "This property should not be initialized"
731 731
732 732 return
733 733
734 734 nPairs = property(getNPairs, setValue, "I'm the 'nPairs' property.")
735 735 pairsIndexList = property(getPairsIndexList, setValue, "I'm the 'pairsIndexList' property.")
736 736 normFactor = property(getNormFactor, setValue, "I'm the 'getNormFactor' property.")
737 737 flag_cspc = property(getFlagCspc, setValue)
738 738 flag_dc = property(getFlagDc, setValue)
739 739 noise = property(getNoise, setValue, "I'm the 'nHeights' property.")
740 740 timeInterval = property(getTimeInterval, setValue, "I'm the 'timeInterval' property")
741 741
742 742 class SpectraHeis(Spectra):
743 743
744 744 data_spc = None
745 745
746 746 data_cspc = None
747 747
748 748 data_dc = None
749 749
750 750 nFFTPoints = None
751 751
752 752 # nPairs = None
753 753
754 754 pairsList = None
755 755
756 756 nCohInt = None
757 757
758 758 nIncohInt = None
759 759
760 760 def __init__(self):
761 761
762 762 self.radarControllerHeaderObj = RadarControllerHeader()
763 763
764 764 self.systemHeaderObj = SystemHeader()
765 765
766 766 self.type = "SpectraHeis"
767 767
768 768 # self.dtype = None
769 769
770 770 # self.nChannels = 0
771 771
772 772 # self.nHeights = 0
773 773
774 774 self.nProfiles = None
775 775
776 776 self.heightList = None
777 777
778 778 self.channelList = None
779 779
780 780 # self.channelIndexList = None
781 781
782 782 self.flagNoData = True
783 783
784 784 self.flagDiscontinuousBlock = False
785 785
786 786 # self.nPairs = 0
787 787
788 788 self.utctime = None
789 789
790 790 self.blocksize = None
791 791
792 792 self.profileIndex = 0
793 793
794 794 self.nCohInt = 1
795 795
796 796 self.nIncohInt = 1
797 797
798 798 def getNormFactor(self):
799 799 pwcode = 1
800 800 if self.flagDecodeData:
801 801 pwcode = numpy.sum(self.code[0]**2)
802 802
803 803 normFactor = self.nIncohInt*self.nCohInt*pwcode
804 804
805 805 return normFactor
806 806
807 807 def getTimeInterval(self):
808 808
809 809 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
810 810
811 811 return timeInterval
812 812
813 813 normFactor = property(getNormFactor, "I'm the 'getNormFactor' property.")
814 814 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
815 815
816 816 class Fits(JROData):
817 817
818 818 heightList = None
819 819
820 820 channelList = None
821 821
822 822 flagNoData = True
823 823
824 824 flagDiscontinuousBlock = False
825 825
826 826 useLocalTime = False
827 827
828 828 utctime = None
829 829
830 830 timeZone = None
831 831
832 832 # ippSeconds = None
833 833
834 834 # timeInterval = None
835 835
836 836 nCohInt = None
837 837
838 838 nIncohInt = None
839 839
840 840 noise = None
841 841
842 842 windowOfFilter = 1
843 843
844 844 #Speed of ligth
845 845 C = 3e8
846 846
847 847 frequency = 49.92e6
848 848
849 849 realtime = False
850 850
851 851
852 852 def __init__(self):
853 853
854 854 self.type = "Fits"
855 855
856 856 self.nProfiles = None
857 857
858 858 self.heightList = None
859 859
860 860 self.channelList = None
861 861
862 862 # self.channelIndexList = None
863 863
864 864 self.flagNoData = True
865 865
866 866 self.utctime = None
867 867
868 868 self.nCohInt = 1
869 869
870 870 self.nIncohInt = 1
871 871
872 872 self.useLocalTime = True
873 873
874 874 self.profileIndex = 0
875 875
876 876 # self.utctime = None
877 877 # self.timeZone = None
878 878 # self.ltctime = None
879 879 # self.timeInterval = None
880 880 # self.header = None
881 881 # self.data_header = None
882 882 # self.data = None
883 883 # self.datatime = None
884 884 # self.flagNoData = False
885 885 # self.expName = ''
886 886 # self.nChannels = None
887 887 # self.nSamples = None
888 888 # self.dataBlocksPerFile = None
889 889 # self.comments = ''
890 890 #
891 891
892 892
893 893 def getltctime(self):
894 894
895 895 if self.useLocalTime:
896 896 return self.utctime - self.timeZone*60
897 897
898 898 return self.utctime
899 899
900 900 def getDatatime(self):
901 901
902 902 datatime = datetime.datetime.utcfromtimestamp(self.ltctime)
903 903 return datatime
904 904
905 905 def getTimeRange(self):
906 906
907 907 datatime = []
908 908
909 909 datatime.append(self.ltctime)
910 910 datatime.append(self.ltctime + self.timeInterval)
911 911
912 912 datatime = numpy.array(datatime)
913 913
914 914 return datatime
915 915
916 916 def getHeiRange(self):
917 917
918 918 heis = self.heightList
919 919
920 920 return heis
921 921
922 922 def getNHeights(self):
923 923
924 924 return len(self.heightList)
925 925
926 926 def getNChannels(self):
927 927
928 928 return len(self.channelList)
929 929
930 930 def getChannelIndexList(self):
931 931
932 932 return range(self.nChannels)
933 933
934 934 def getNoise(self, type = 1):
935 935
936 936 #noise = numpy.zeros(self.nChannels)
937 937
938 938 if type == 1:
939 939 noise = self.getNoisebyHildebrand()
940 940
941 941 if type == 2:
942 942 noise = self.getNoisebySort()
943 943
944 944 if type == 3:
945 945 noise = self.getNoisebyWindow()
946 946
947 947 return noise
948 948
949 949 def getTimeInterval(self):
950 950
951 951 timeInterval = self.ippSeconds * self.nCohInt * self.nIncohInt
952 952
953 953 return timeInterval
954 954
955 955 datatime = property(getDatatime, "I'm the 'datatime' property")
956 956 nHeights = property(getNHeights, "I'm the 'nHeights' property.")
957 957 nChannels = property(getNChannels, "I'm the 'nChannel' property.")
958 958 channelIndexList = property(getChannelIndexList, "I'm the 'channelIndexList' property.")
959 959 noise = property(getNoise, "I'm the 'nHeights' property.")
960 960
961 961 ltctime = property(getltctime, "I'm the 'ltctime' property")
962 962 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
963 963
964 964
965 965 class Correlation(JROData):
966 966
967 967 noise = None
968 968
969 969 SNR = None
970 970
971 971 #--------------------------------------------------
972 972
973 973 mode = None
974 974
975 975 split = False
976 976
977 977 data_cf = None
978 978
979 979 lags = None
980 980
981 981 lagRange = None
982 982
983 983 pairsList = None
984 984
985 985 normFactor = None
986 986
987 987 #--------------------------------------------------
988 988
989 989 # calculateVelocity = None
990 990
991 991 nLags = None
992 992
993 993 nPairs = None
994 994
995 995 nAvg = None
996 996
997 997
998 998 def __init__(self):
999 999 '''
1000 1000 Constructor
1001 1001 '''
1002 1002 self.radarControllerHeaderObj = RadarControllerHeader()
1003 1003
1004 1004 self.systemHeaderObj = SystemHeader()
1005 1005
1006 1006 self.type = "Correlation"
1007 1007
1008 1008 self.data = None
1009 1009
1010 1010 self.dtype = None
1011 1011
1012 1012 self.nProfiles = None
1013 1013
1014 1014 self.heightList = None
1015 1015
1016 1016 self.channelList = None
1017 1017
1018 1018 self.flagNoData = True
1019 1019
1020 1020 self.flagDiscontinuousBlock = False
1021 1021
1022 1022 self.utctime = None
1023 1023
1024 1024 self.timeZone = None
1025 1025
1026 1026 self.dstFlag = None
1027 1027
1028 1028 self.errorCount = None
1029 1029
1030 1030 self.blocksize = None
1031 1031
1032 1032 self.flagDecodeData = False #asumo q la data no esta decodificada
1033 1033
1034 1034 self.flagDeflipData = False #asumo q la data no esta sin flip
1035 1035
1036 1036 self.pairsList = None
1037 1037
1038 1038 self.nPoints = None
1039 1039
1040 1040 def getPairsList(self):
1041 1041
1042 1042 return self.pairsList
1043 1043
1044 1044 def getNoise(self, mode = 2):
1045 1045
1046 1046 indR = numpy.where(self.lagR == 0)[0][0]
1047 1047 indT = numpy.where(self.lagT == 0)[0][0]
1048 1048
1049 1049 jspectra0 = self.data_corr[:,:,indR,:]
1050 1050 jspectra = copy.copy(jspectra0)
1051 1051
1052 1052 num_chan = jspectra.shape[0]
1053 1053 num_hei = jspectra.shape[2]
1054 1054
1055 1055 freq_dc = jspectra.shape[1]/2
1056 1056 ind_vel = numpy.array([-2,-1,1,2]) + freq_dc
1057 1057
1058 1058 if ind_vel[0]<0:
1059 1059 ind_vel[range(0,1)] = ind_vel[range(0,1)] + self.num_prof
1060 1060
1061 1061 if mode == 1:
1062 1062 jspectra[:,freq_dc,:] = (jspectra[:,ind_vel[1],:] + jspectra[:,ind_vel[2],:])/2 #CORRECCION
1063 1063
1064 1064 if mode == 2:
1065 1065
1066 1066 vel = numpy.array([-2,-1,1,2])
1067 1067 xx = numpy.zeros([4,4])
1068 1068
1069 1069 for fil in range(4):
1070 1070 xx[fil,:] = vel[fil]**numpy.asarray(range(4))
1071 1071
1072 1072 xx_inv = numpy.linalg.inv(xx)
1073 1073 xx_aux = xx_inv[0,:]
1074 1074
1075 1075 for ich in range(num_chan):
1076 1076 yy = jspectra[ich,ind_vel,:]
1077 1077 jspectra[ich,freq_dc,:] = numpy.dot(xx_aux,yy)
1078 1078
1079 1079 junkid = jspectra[ich,freq_dc,:]<=0
1080 1080 cjunkid = sum(junkid)
1081 1081
1082 1082 if cjunkid.any():
1083 1083 jspectra[ich,freq_dc,junkid.nonzero()] = (jspectra[ich,ind_vel[1],junkid] + jspectra[ich,ind_vel[2],junkid])/2
1084 1084
1085 1085 noise = jspectra0[:,freq_dc,:] - jspectra[:,freq_dc,:]
1086 1086
1087 1087 return noise
1088 1088
1089 1089 def getTimeInterval(self):
1090 1090
1091 1091 timeInterval = self.ippSeconds * self.nCohInt * self.nProfiles
1092 1092
1093 1093 return timeInterval
1094 1094
1095 1095 def splitFunctions(self):
1096 1096
1097 1097 pairsList = self.pairsList
1098 1098 ccf_pairs = []
1099 1099 acf_pairs = []
1100 1100 ccf_ind = []
1101 1101 acf_ind = []
1102 1102 for l in range(len(pairsList)):
1103 1103 chan0 = pairsList[l][0]
1104 1104 chan1 = pairsList[l][1]
1105 1105
1106 1106 #Obteniendo pares de Autocorrelacion
1107 1107 if chan0 == chan1:
1108 1108 acf_pairs.append(chan0)
1109 1109 acf_ind.append(l)
1110 1110 else:
1111 1111 ccf_pairs.append(pairsList[l])
1112 1112 ccf_ind.append(l)
1113 1113
1114 1114 data_acf = self.data_cf[acf_ind]
1115 1115 data_ccf = self.data_cf[ccf_ind]
1116 1116
1117 1117 return acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf
1118 1118
1119 1119 def getNormFactor(self):
1120 1120 acf_ind, ccf_ind, acf_pairs, ccf_pairs, data_acf, data_ccf = self.splitFunctions()
1121 1121 acf_pairs = numpy.array(acf_pairs)
1122 1122 normFactor = numpy.zeros((self.nPairs,self.nHeights))
1123 1123
1124 1124 for p in range(self.nPairs):
1125 1125 pair = self.pairsList[p]
1126 1126
1127 1127 ch0 = pair[0]
1128 1128 ch1 = pair[1]
1129 1129
1130 1130 ch0_max = numpy.max(data_acf[acf_pairs==ch0,:,:], axis=1)
1131 1131 ch1_max = numpy.max(data_acf[acf_pairs==ch1,:,:], axis=1)
1132 1132 normFactor[p,:] = numpy.sqrt(ch0_max*ch1_max)
1133 1133
1134 1134 return normFactor
1135 1135
1136 1136 timeInterval = property(getTimeInterval, "I'm the 'timeInterval' property")
1137 1137 normFactor = property(getNormFactor, "I'm the 'normFactor property'")
1138 1138
1139 1139 class Parameters(Spectra):
1140 1140
1141 1141 experimentInfo = None #Information about the experiment
1142 1142
1143 1143 #Information from previous data
1144 1144
1145 1145 inputUnit = None #Type of data to be processed
1146 1146
1147 1147 operation = None #Type of operation to parametrize
1148 1148
1149 1149 #normFactor = None #Normalization Factor
1150 1150
1151 1151 groupList = None #List of Pairs, Groups, etc
1152 1152
1153 1153 #Parameters
1154 1154
1155 1155 data_param = None #Parameters obtained
1156 1156
1157 1157 data_pre = None #Data Pre Parametrization
1158 1158
1159 1159 data_SNR = None #Signal to Noise Ratio
1160 1160
1161 1161 # heightRange = None #Heights
1162 1162
1163 1163 abscissaList = None #Abscissa, can be velocities, lags or time
1164 1164
1165 1165 # noise = None #Noise Potency
1166 1166
1167 1167 utctimeInit = None #Initial UTC time
1168 1168
1169 1169 paramInterval = None #Time interval to calculate Parameters in seconds
1170 1170
1171 1171 useLocalTime = True
1172 1172
1173 1173 #Fitting
1174 1174
1175 1175 data_error = None #Error of the estimation
1176 1176
1177 1177 constants = None
1178 1178
1179 1179 library = None
1180 1180
1181 1181 #Output signal
1182 1182
1183 1183 outputInterval = None #Time interval to calculate output signal in seconds
1184 1184
1185 1185 data_output = None #Out signal
1186 1186
1187 1187 nAvg = None
1188 1188
1189 1189 noise_estimation = None
1190 1190
1191 1191
1192 1192 def __init__(self):
1193 1193 '''
1194 1194 Constructor
1195 1195 '''
1196 1196 self.radarControllerHeaderObj = RadarControllerHeader()
1197 1197
1198 1198 self.systemHeaderObj = SystemHeader()
1199 1199
1200 1200 self.type = "Parameters"
1201 1201
1202 1202 def getTimeRange1(self, interval):
1203 1203
1204 1204 datatime = []
1205 1205
1206 1206 if self.useLocalTime:
1207 1207 time1 = self.utctimeInit - self.timeZone*60
1208 1208 else:
1209 1209 time1 = self.utctimeInit
1210 1210
1211 1211 datatime.append(time1)
1212 1212 datatime.append(time1 + interval)
1213 1213 datatime = numpy.array(datatime)
1214 1214
1215 1215 return datatime
1216 1216
1217 1217 def getTimeInterval(self):
1218 1218
1219 1219 if hasattr(self, 'timeInterval1'):
1220 1220 return self.timeInterval1
1221 1221 else:
1222 1222 return self.paramInterval
1223 1223
1224 1224 def getNoise(self):
1225 1225
1226 1226 return self.spc_noise
1227 1227
1228 1228 timeInterval = property(getTimeInterval)
@@ -1,756 +1,773
1 1
2 2 import os
3 3 import zmq
4 4 import time
5 5 import numpy
6 6 import datetime
7 7 import numpy as np
8 8 import matplotlib
9 9 matplotlib.use('TkAgg')
10 10 import matplotlib.pyplot as plt
11 11 from mpl_toolkits.axes_grid1 import make_axes_locatable
12 12 from matplotlib.ticker import FuncFormatter, LinearLocator
13 13 from multiprocessing import Process
14 14
15 15 from schainpy.model.proc.jroproc_base import Operation
16 16
17 17 plt.ioff()
18 18
19 19 func = lambda x, pos: ('%s') %(datetime.datetime.fromtimestamp(x).strftime('%H:%M'))
20 20
21 21 d1970 = datetime.datetime(1970,1,1)
22 22
23 23 class PlotData(Operation, Process):
24 24
25 25 CODE = 'Figure'
26 26 colormap = 'jro'
27 CONFLATE = True
27 CONFLATE = False
28 28 __MAXNUMX = 80
29 __MAXNUMY = 80
30 29 __missing = 1E30
31 30
32 31 def __init__(self, **kwargs):
33 32
34 33 Operation.__init__(self, plot=True, **kwargs)
35 34 Process.__init__(self)
36 35 self.kwargs['code'] = self.CODE
37 36 self.mp = False
38 37 self.dataOut = None
39 38 self.isConfig = False
40 39 self.figure = None
41 40 self.axes = []
42 41 self.localtime = kwargs.pop('localtime', True)
43 42 self.show = kwargs.get('show', True)
44 43 self.save = kwargs.get('save', False)
45 44 self.colormap = kwargs.get('colormap', self.colormap)
46 45 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
47 46 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
48 47 self.showprofile = kwargs.get('showprofile', True)
49 48 self.title = kwargs.get('wintitle', '')
50 49 self.xaxis = kwargs.get('xaxis', 'frequency')
51 50 self.zmin = kwargs.get('zmin', None)
52 51 self.zmax = kwargs.get('zmax', None)
53 52 self.xmin = kwargs.get('xmin', None)
54 53 self.xmax = kwargs.get('xmax', None)
55 54 self.xrange = kwargs.get('xrange', 24)
56 55 self.ymin = kwargs.get('ymin', None)
57 56 self.ymax = kwargs.get('ymax', None)
57 self.__MAXNUMY = kwargs.get('decimation', 80)
58 58 self.throttle_value = 5
59 self.times = []
59 60
60 61 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
61 62
62 63 if x_buffer.shape[0] < 2:
63 64 return x_buffer, y_buffer, z_buffer
64 65
65 66 deltas = x_buffer[1:] - x_buffer[0:-1]
66 67 x_median = np.median(deltas)
67 68
68 69 index = np.where(deltas > 5*x_median)
69 70
70 71 if len(index[0]) != 0:
71 72 z_buffer[::, index[0], ::] = self.__missing
72 73 z_buffer = np.ma.masked_inside(z_buffer,
73 74 0.99*self.__missing,
74 75 1.01*self.__missing)
75 76
76 77 return x_buffer, y_buffer, z_buffer
77 78
78 79 def decimate(self):
79 80
80 81 # dx = int(len(self.x)/self.__MAXNUMX) + 1
81 82 dy = int(len(self.y)/self.__MAXNUMY) + 1
82 83
83 84 # x = self.x[::dx]
84 85 x = self.x
85 86 y = self.y[::dy]
86 87 z = self.z[::, ::, ::dy]
87 88
88 89 return x, y, z
89 90
90 91 def __plot(self):
91 92
92 93 print 'plotting...{}'.format(self.CODE)
93 94
94 95 if self.show:
95 96 self.figure.show()
96 97
97 98 self.plot()
98 99 plt.tight_layout()
99 100 self.figure.canvas.manager.set_window_title('{} {} - {}'.format(self.title, self.CODE.upper(),
100 101 datetime.datetime.fromtimestamp(self.max_time).strftime('%Y/%m/%d')))
101 102
102 103 if self.save:
103 104 figname = os.path.join(self.save, '{}_{}.png'.format(self.CODE,
104 105 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
105 106 print 'Saving figure: {}'.format(figname)
106 107 self.figure.savefig(figname)
107 108
108 109 self.figure.canvas.draw()
109 110
110 111 def plot(self):
111 112
112 113 print 'plotting...{}'.format(self.CODE.upper())
113 114 return
114 115
115 116 def run(self):
116 117
117 118 print '[Starting] {}'.format(self.name)
118 119
119 120 context = zmq.Context()
120 121 receiver = context.socket(zmq.SUB)
121 122 receiver.setsockopt(zmq.SUBSCRIBE, '')
122 123 receiver.setsockopt(zmq.CONFLATE, self.CONFLATE)
124
123 125 if 'server' in self.kwargs['parent']:
124 126 receiver.connect('ipc:///tmp/{}.plots'.format(self.kwargs['parent']['server']))
125 127 else:
126 128 receiver.connect("ipc:///tmp/zmq.plots")
127 129
130 seconds_passed = 0
131
128 132 while True:
129 133 try:
130 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)
134 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)#flags=zmq.NOBLOCK
135 self.started = self.data['STARTED']
131 136 self.dataOut = self.data['dataOut']
137
138 if (len(self.times) < len(self.data['times']) and not self.started and self.data['ENDED']):
139 continue
140
132 141 self.times = self.data['times']
133 142 self.times.sort()
134 143 self.throttle_value = self.data['throttle']
135 144 self.min_time = self.times[0]
136 145 self.max_time = self.times[-1]
137 146
138 147 if self.isConfig is False:
148 print 'setting up'
139 149 self.setup()
140 150 self.isConfig = True
141 self.__plot()
151 self.__plot()
142 152
143 153 if self.data['ENDED'] is True:
154 print '********GRAPHIC ENDED********'
155 self.ended = True
144 156 self.isConfig = False
157 self.__plot()
158 elif seconds_passed >= self.data['throttle']:
159 print 'passed', seconds_passed
160 self.__plot()
161 seconds_passed = 0
145 162
146 163 except zmq.Again as e:
147 164 print 'Waiting for data...'
148 plt.pause(self.throttle_value)
165 plt.pause(2)
166 seconds_passed += 2
149 167
150 168 def close(self):
151 169 if self.dataOut:
152 170 self.__plot()
153 171
154 172
155 173 class PlotSpectraData(PlotData):
156 174
157 175 CODE = 'spc'
158 176 colormap = 'jro'
159 177 CONFLATE = False
160 178
161 179 def setup(self):
162 180
163 181 ncolspan = 1
164 182 colspan = 1
165 183 self.ncols = int(numpy.sqrt(self.dataOut.nChannels)+0.9)
166 184 self.nrows = int(self.dataOut.nChannels*1./self.ncols + 0.9)
167 185 self.width = 3.6*self.ncols
168 186 self.height = 3.2*self.nrows
169 187 if self.showprofile:
170 188 ncolspan = 3
171 189 colspan = 2
172 190 self.width += 1.2*self.ncols
173 191
174 192 self.ylabel = 'Range [Km]'
175 193 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
176 194
177 195 if self.figure is None:
178 196 self.figure = plt.figure(figsize=(self.width, self.height),
179 197 edgecolor='k',
180 198 facecolor='w')
181 199 else:
182 200 self.figure.clf()
183 201
184 202 n = 0
185 203 for y in range(self.nrows):
186 204 for x in range(self.ncols):
187 205 if n >= self.dataOut.nChannels:
188 206 break
189 207 ax = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan), 1, colspan)
190 208 if self.showprofile:
191 209 ax.ax_profile = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan+colspan), 1, 1)
192 210
193 211 ax.firsttime = True
194 212 self.axes.append(ax)
195 213 n += 1
196 214
197 215 def plot(self):
198 216
199 217 if self.xaxis == "frequency":
200 218 x = self.dataOut.getFreqRange(1)/1000.
201 219 xlabel = "Frequency (kHz)"
202 220 elif self.xaxis == "time":
203 221 x = self.dataOut.getAcfRange(1)
204 222 xlabel = "Time (ms)"
205 223 else:
206 224 x = self.dataOut.getVelRange(1)
207 225 xlabel = "Velocity (m/s)"
208 226
209 227 y = self.dataOut.getHeiRange()
210 228 z = self.data[self.CODE]
211 229
212 230 for n, ax in enumerate(self.axes):
213 231
214 232 if ax.firsttime:
215 233 self.xmax = self.xmax if self.xmax else np.nanmax(x)
216 234 self.xmin = self.xmin if self.xmin else -self.xmax
217 235 self.ymin = self.ymin if self.ymin else np.nanmin(y)
218 236 self.ymax = self.ymax if self.ymax else np.nanmax(y)
219 237 self.zmin = self.zmin if self.zmin else np.nanmin(z)
220 238 self.zmax = self.zmax if self.zmax else np.nanmax(z)
221 239 ax.plot = ax.pcolormesh(x, y, z[n].T,
222 240 vmin=self.zmin,
223 241 vmax=self.zmax,
224 242 cmap=plt.get_cmap(self.colormap)
225 243 )
226 244 divider = make_axes_locatable(ax)
227 245 cax = divider.new_horizontal(size='3%', pad=0.05)
228 246 self.figure.add_axes(cax)
229 247 plt.colorbar(ax.plot, cax)
230 248
231 249 ax.set_xlim(self.xmin, self.xmax)
232 250 ax.set_ylim(self.ymin, self.ymax)
233 251
234 252 ax.set_ylabel(self.ylabel)
235 253 ax.set_xlabel(xlabel)
236 254
237 255 ax.firsttime = False
238 256
239 257 if self.showprofile:
240 258 ax.plot_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
241 259 ax.ax_profile.set_xlim(self.zmin, self.zmax)
242 260 ax.ax_profile.set_ylim(self.ymin, self.ymax)
243 261 ax.ax_profile.set_xlabel('dB')
244 262 ax.ax_profile.grid(b=True, axis='x')
245 263 ax.plot_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
246 264 color="k", linestyle="dashed", lw=2)[0]
247 265 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
248 266 else:
249 267 ax.plot.set_array(z[n].T.ravel())
250 268 if self.showprofile:
251 269 ax.plot_profile.set_data(self.data['rti'][self.max_time][n], y)
252 270 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
253 271
254 272 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
255 273 size=8)
256 274 self.saveTime = self.max_time
257 275
258 276
259 277 class PlotCrossSpectraData(PlotData):
260 278
261 279 CODE = 'cspc'
262 280 zmin_coh = None
263 281 zmax_coh = None
264 282 zmin_phase = None
265 283 zmax_phase = None
266 284 CONFLATE = False
267 285
268 286 def setup(self):
269 287
270 288 ncolspan = 1
271 289 colspan = 1
272 290 self.ncols = 2
273 291 self.nrows = self.dataOut.nPairs
274 292 self.width = 3.6*self.ncols
275 293 self.height = 3.2*self.nrows
276 294
277 295 self.ylabel = 'Range [Km]'
278 296 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
279 297
280 298 if self.figure is None:
281 299 self.figure = plt.figure(figsize=(self.width, self.height),
282 300 edgecolor='k',
283 301 facecolor='w')
284 302 else:
285 303 self.figure.clf()
286 304
287 305 for y in range(self.nrows):
288 306 for x in range(self.ncols):
289 307 ax = plt.subplot2grid((self.nrows, self.ncols), (y, x), 1, 1)
290 308 ax.firsttime = True
291 309 self.axes.append(ax)
292 310
293 311 def plot(self):
294 312
295 313 if self.xaxis == "frequency":
296 314 x = self.dataOut.getFreqRange(1)/1000.
297 315 xlabel = "Frequency (kHz)"
298 316 elif self.xaxis == "time":
299 317 x = self.dataOut.getAcfRange(1)
300 318 xlabel = "Time (ms)"
301 319 else:
302 320 x = self.dataOut.getVelRange(1)
303 321 xlabel = "Velocity (m/s)"
304 322
305 323 y = self.dataOut.getHeiRange()
306 324 z_coh = self.data['cspc_coh']
307 325 z_phase = self.data['cspc_phase']
308 326
309 327 for n in range(self.nrows):
310 328 ax = self.axes[2*n]
311 329 ax1 = self.axes[2*n+1]
312 330 if ax.firsttime:
313 331 self.xmax = self.xmax if self.xmax else np.nanmax(x)
314 332 self.xmin = self.xmin if self.xmin else -self.xmax
315 333 self.ymin = self.ymin if self.ymin else np.nanmin(y)
316 334 self.ymax = self.ymax if self.ymax else np.nanmax(y)
317 335 self.zmin_coh = self.zmin_coh if self.zmin_coh else 0.0
318 336 self.zmax_coh = self.zmax_coh if self.zmax_coh else 1.0
319 337 self.zmin_phase = self.zmin_phase if self.zmin_phase else -180
320 338 self.zmax_phase = self.zmax_phase if self.zmax_phase else 180
321 339
322 340 ax.plot = ax.pcolormesh(x, y, z_coh[n].T,
323 341 vmin=self.zmin_coh,
324 342 vmax=self.zmax_coh,
325 343 cmap=plt.get_cmap(self.colormap_coh)
326 344 )
327 345 divider = make_axes_locatable(ax)
328 346 cax = divider.new_horizontal(size='3%', pad=0.05)
329 347 self.figure.add_axes(cax)
330 348 plt.colorbar(ax.plot, cax)
331 349
332 350 ax.set_xlim(self.xmin, self.xmax)
333 351 ax.set_ylim(self.ymin, self.ymax)
334 352
335 353 ax.set_ylabel(self.ylabel)
336 354 ax.set_xlabel(xlabel)
337 355 ax.firsttime = False
338 356
339 357 ax1.plot = ax1.pcolormesh(x, y, z_phase[n].T,
340 358 vmin=self.zmin_phase,
341 359 vmax=self.zmax_phase,
342 360 cmap=plt.get_cmap(self.colormap_phase)
343 361 )
344 362 divider = make_axes_locatable(ax1)
345 363 cax = divider.new_horizontal(size='3%', pad=0.05)
346 364 self.figure.add_axes(cax)
347 365 plt.colorbar(ax1.plot, cax)
348 366
349 367 ax1.set_xlim(self.xmin, self.xmax)
350 368 ax1.set_ylim(self.ymin, self.ymax)
351 369
352 370 ax1.set_ylabel(self.ylabel)
353 371 ax1.set_xlabel(xlabel)
354 372 ax1.firsttime = False
355 373 else:
356 374 ax.plot.set_array(z_coh[n].T.ravel())
357 375 ax1.plot.set_array(z_phase[n].T.ravel())
358 376
359 377 ax.set_title('Coherence Ch{} * Ch{}'.format(self.dataOut.pairsList[n][0], self.dataOut.pairsList[n][1]), size=8)
360 378 ax1.set_title('Phase Ch{} * Ch{}'.format(self.dataOut.pairsList[n][0], self.dataOut.pairsList[n][1]), size=8)
361 379 self.saveTime = self.max_time
362 380
363 381
364 382 class PlotSpectraMeanData(PlotSpectraData):
365 383
366 384 CODE = 'spc_mean'
367 385 colormap = 'jet'
368 386
369 387 def plot(self):
370 388
371 389 if self.xaxis == "frequency":
372 390 x = self.dataOut.getFreqRange(1)/1000.
373 391 xlabel = "Frequency (kHz)"
374 392 elif self.xaxis == "time":
375 393 x = self.dataOut.getAcfRange(1)
376 394 xlabel = "Time (ms)"
377 395 else:
378 396 x = self.dataOut.getVelRange(1)
379 397 xlabel = "Velocity (m/s)"
380 398
381 399 y = self.dataOut.getHeiRange()
382 400 z = self.data['spc']
383 401 mean = self.data['mean'][self.max_time]
384 402
385 403 for n, ax in enumerate(self.axes):
386 404
387 405 if ax.firsttime:
388 406 self.xmax = self.xmax if self.xmax else np.nanmax(x)
389 407 self.xmin = self.xmin if self.xmin else -self.xmax
390 408 self.ymin = self.ymin if self.ymin else np.nanmin(y)
391 409 self.ymax = self.ymax if self.ymax else np.nanmax(y)
392 410 self.zmin = self.zmin if self.zmin else np.nanmin(z)
393 411 self.zmax = self.zmax if self.zmax else np.nanmax(z)
394 412 ax.plt = ax.pcolormesh(x, y, z[n].T,
395 413 vmin=self.zmin,
396 414 vmax=self.zmax,
397 415 cmap=plt.get_cmap(self.colormap)
398 416 )
399 417 ax.plt_dop = ax.plot(mean[n], y,
400 418 color='k')[0]
401 419
402 420 divider = make_axes_locatable(ax)
403 421 cax = divider.new_horizontal(size='3%', pad=0.05)
404 422 self.figure.add_axes(cax)
405 423 plt.colorbar(ax.plt, cax)
406 424
407 425 ax.set_xlim(self.xmin, self.xmax)
408 426 ax.set_ylim(self.ymin, self.ymax)
409 427
410 428 ax.set_ylabel(self.ylabel)
411 429 ax.set_xlabel(xlabel)
412 430
413 431 ax.firsttime = False
414 432
415 433 if self.showprofile:
416 434 ax.plt_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
417 435 ax.ax_profile.set_xlim(self.zmin, self.zmax)
418 436 ax.ax_profile.set_ylim(self.ymin, self.ymax)
419 437 ax.ax_profile.set_xlabel('dB')
420 438 ax.ax_profile.grid(b=True, axis='x')
421 439 ax.plt_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
422 440 color="k", linestyle="dashed", lw=2)[0]
423 441 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
424 442 else:
425 443 ax.plt.set_array(z[n].T.ravel())
426 444 ax.plt_dop.set_data(mean[n], y)
427 445 if self.showprofile:
428 446 ax.plt_profile.set_data(self.data['rti'][self.max_time][n], y)
429 447 ax.plt_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
430 448
431 449 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
432 450 size=8)
433 451 self.saveTime = self.max_time
434 452
435 453
436 454 class PlotRTIData(PlotData):
437 455
438 456 CODE = 'rti'
439 457 colormap = 'jro'
440 458
441 459 def setup(self):
442 460 self.ncols = 1
443 461 self.nrows = self.dataOut.nChannels
444 462 self.width = 10
445 463 self.height = 2.2*self.nrows if self.nrows<6 else 12
446 464 if self.nrows==1:
447 465 self.height += 1
448 466 self.ylabel = 'Range [Km]'
449 467 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
450 468
451 469 if self.figure is None:
452 470 self.figure = plt.figure(figsize=(self.width, self.height),
453 471 edgecolor='k',
454 472 facecolor='w')
455 473 else:
456 474 self.figure.clf()
457 475 self.axes = []
458 476
459 477 for n in range(self.nrows):
460 478 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
461 479 ax.firsttime = True
462 480 self.axes.append(ax)
463 481
464 482 def plot(self):
465 483
466 484 self.x = np.array(self.times)
467 485 self.y = self.dataOut.getHeiRange()
468 486 self.z = []
469 487
470 488 for ch in range(self.nrows):
471 489 self.z.append([self.data[self.CODE][t][ch] for t in self.times])
472 490
473 491 self.z = np.array(self.z)
474 492 for n, ax in enumerate(self.axes):
475
476 493 x, y, z = self.fill_gaps(*self.decimate())
477 494 xmin = self.min_time
478 495 xmax = xmin+self.xrange*60*60
496 self.zmin = self.zmin if self.zmin else np.min(self.z)
497 self.zmax = self.zmax if self.zmax else np.max(self.z)
479 498 if ax.firsttime:
480 499 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
481 500 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
482 self.zmin = self.zmin if self.zmin else np.nanmin(self.z)
483 self.zmax = self.zmax if self.zmax else np.nanmax(self.z)
484 501 plot = ax.pcolormesh(x, y, z[n].T,
485 502 vmin=self.zmin,
486 503 vmax=self.zmax,
487 504 cmap=plt.get_cmap(self.colormap)
488 505 )
489 506 divider = make_axes_locatable(ax)
490 507 cax = divider.new_horizontal(size='2%', pad=0.05)
491 508 self.figure.add_axes(cax)
492 509 plt.colorbar(plot, cax)
493 510 ax.set_ylim(self.ymin, self.ymax)
494 511
495 512 ax.xaxis.set_major_formatter(FuncFormatter(func))
496 513 ax.xaxis.set_major_locator(LinearLocator(6))
497 514
498 515 ax.set_ylabel(self.ylabel)
499 516
500 517 # if self.xmin is None:
501 518 # xmin = self.min_time
502 519 # else:
503 520 # xmin = (datetime.datetime.combine(self.dataOut.datatime.date(),
504 521 # datetime.time(self.xmin, 0, 0))-d1970).total_seconds()
505 522
506 523 ax.set_xlim(xmin, xmax)
507 524 ax.firsttime = False
508 525 else:
509 526 ax.collections.remove(ax.collections[0])
510 527 ax.set_xlim(xmin, xmax)
511 528 plot = ax.pcolormesh(x, y, z[n].T,
512 529 vmin=self.zmin,
513 530 vmax=self.zmax,
514 531 cmap=plt.get_cmap(self.colormap)
515 532 )
516 533 ax.set_title('{} {}'.format(self.titles[n],
517 534 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
518 535 size=8)
519 536
520 537 self.saveTime = self.min_time
521 538
522 539
523 540 class PlotCOHData(PlotRTIData):
524 541
525 542 CODE = 'coh'
526 543
527 544 def setup(self):
528 545
529 546 self.ncols = 1
530 547 self.nrows = self.dataOut.nPairs
531 548 self.width = 10
532 549 self.height = 2.2*self.nrows if self.nrows<6 else 12
533 550 if self.nrows==1:
534 551 self.height += 1
535 552 self.ylabel = 'Range [Km]'
536 553 self.titles = ['{} Ch{} * Ch{}'.format(self.CODE.upper(), x[0], x[1]) for x in self.dataOut.pairsList]
537 554
538 555 if self.figure is None:
539 556 self.figure = plt.figure(figsize=(self.width, self.height),
540 557 edgecolor='k',
541 558 facecolor='w')
542 559 else:
543 560 self.figure.clf()
544 561 self.axes = []
545 562
546 563 for n in range(self.nrows):
547 564 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
548 565 ax.firsttime = True
549 566 self.axes.append(ax)
550 567
551 568
552 569 class PlotNoiseData(PlotData):
553 570 CODE = 'noise'
554 571
555 572 def setup(self):
556 573
557 574 self.ncols = 1
558 575 self.nrows = 1
559 576 self.width = 10
560 577 self.height = 3.2
561 578 self.ylabel = 'Intensity [dB]'
562 579 self.titles = ['Noise']
563 580
564 581 if self.figure is None:
565 582 self.figure = plt.figure(figsize=(self.width, self.height),
566 583 edgecolor='k',
567 584 facecolor='w')
568 585 else:
569 586 self.figure.clf()
570 587 self.axes = []
571 588
572 589 self.ax = self.figure.add_subplot(self.nrows, self.ncols, 1)
573 590 self.ax.firsttime = True
574 591
575 592 def plot(self):
576 593
577 594 x = self.times
578 595 xmin = self.min_time
579 596 xmax = xmin+self.xrange*60*60
580 597 if self.ax.firsttime:
581 598 for ch in self.dataOut.channelList:
582 599 y = [self.data[self.CODE][t][ch] for t in self.times]
583 600 self.ax.plot(x, y, lw=1, label='Ch{}'.format(ch))
584 601 self.ax.firsttime = False
585 602 self.ax.xaxis.set_major_formatter(FuncFormatter(func))
586 603 self.ax.xaxis.set_major_locator(LinearLocator(6))
587 604 self.ax.set_ylabel(self.ylabel)
588 605 plt.legend()
589 606 else:
590 607 for ch in self.dataOut.channelList:
591 608 y = [self.data[self.CODE][t][ch] for t in self.times]
592 609 self.ax.lines[ch].set_data(x, y)
593 610
594 611 self.ax.set_xlim(xmin, xmax)
595 612 self.ax.set_ylim(min(y)-5, max(y)+5)
596 613 self.saveTime = self.min_time
597 614
598 615
599 616 class PlotWindProfilerData(PlotRTIData):
600 617
601 618 CODE = 'wind'
602 619 colormap = 'seismic'
603 620
604 621 def setup(self):
605 622 self.ncols = 1
606 623 self.nrows = self.dataOut.data_output.shape[0]
607 624 self.width = 10
608 625 self.height = 2.2*self.nrows
609 626 self.ylabel = 'Height [Km]'
610 627 self.titles = ['Zonal Wind' ,'Meridional Wind', 'Vertical Wind']
611 628 self.clabels = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
612 629 self.windFactor = [1, 1, 100]
613 630
614 631 if self.figure is None:
615 632 self.figure = plt.figure(figsize=(self.width, self.height),
616 633 edgecolor='k',
617 634 facecolor='w')
618 635 else:
619 636 self.figure.clf()
620 637 self.axes = []
621 638
622 639 for n in range(self.nrows):
623 640 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
624 641 ax.firsttime = True
625 642 self.axes.append(ax)
626 643
627 644 def plot(self):
628 645
629 646 self.x = np.array(self.times)
630 647 self.y = self.dataOut.heightList
631 648 self.z = []
632 649
633 650 for ch in range(self.nrows):
634 651 self.z.append([self.data['output'][t][ch] for t in self.times])
635 652
636 653 self.z = np.array(self.z)
637 654 self.z = numpy.ma.masked_invalid(self.z)
638 655
639 656 cmap=plt.get_cmap(self.colormap)
640 657 cmap.set_bad('black', 1.)
641 658
642 659 for n, ax in enumerate(self.axes):
643 660 x, y, z = self.fill_gaps(*self.decimate())
644 661 xmin = self.min_time
645 662 xmax = xmin+self.xrange*60*60
646 663 if ax.firsttime:
647 664 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
648 665 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
649 666 self.zmax = self.zmax if self.zmax else numpy.nanmax(abs(self.z[:-1, :]))
650 667 self.zmin = self.zmin if self.zmin else -self.zmax
651 668
652 669 plot = ax.pcolormesh(x, y, z[n].T*self.windFactor[n],
653 670 vmin=self.zmin,
654 671 vmax=self.zmax,
655 672 cmap=cmap
656 673 )
657 674 divider = make_axes_locatable(ax)
658 675 cax = divider.new_horizontal(size='2%', pad=0.05)
659 676 self.figure.add_axes(cax)
660 677 cb = plt.colorbar(plot, cax)
661 678 cb.set_label(self.clabels[n])
662 679 ax.set_ylim(self.ymin, self.ymax)
663 680
664 681 ax.xaxis.set_major_formatter(FuncFormatter(func))
665 682 ax.xaxis.set_major_locator(LinearLocator(6))
666 683
667 684 ax.set_ylabel(self.ylabel)
668 685
669 686 ax.set_xlim(xmin, xmax)
670 687 ax.firsttime = False
671 688 else:
672 689 ax.collections.remove(ax.collections[0])
673 690 ax.set_xlim(xmin, xmax)
674 691 plot = ax.pcolormesh(x, y, z[n].T*self.windFactor[n],
675 692 vmin=self.zmin,
676 693 vmax=self.zmax,
677 694 cmap=plt.get_cmap(self.colormap)
678 695 )
679 696 ax.set_title('{} {}'.format(self.titles[n],
680 697 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
681 698 size=8)
682 699
683 700 self.saveTime = self.min_time
684 701
685 702
686 703 class PlotSNRData(PlotRTIData):
687 704 CODE = 'snr'
688 705 colormap = 'jet'
689 706
690 707 class PlotDOPData(PlotRTIData):
691 708 CODE = 'dop'
692 709 colormap = 'jet'
693 710
694 711
695 712 class PlotPHASEData(PlotCOHData):
696 713 CODE = 'phase'
697 714 colormap = 'seismic'
698 715
699 716
700 717 class PlotSkyMapData(PlotData):
701 718
702 719 CODE = 'met'
703 720
704 721 def setup(self):
705 722
706 723 self.ncols = 1
707 724 self.nrows = 1
708 725 self.width = 7.2
709 726 self.height = 7.2
710 727
711 728 self.xlabel = 'Zonal Zenith Angle (deg)'
712 729 self.ylabel = 'Meridional Zenith Angle (deg)'
713 730
714 731 if self.figure is None:
715 732 self.figure = plt.figure(figsize=(self.width, self.height),
716 733 edgecolor='k',
717 734 facecolor='w')
718 735 else:
719 736 self.figure.clf()
720 737
721 738 self.ax = plt.subplot2grid((self.nrows, self.ncols), (0, 0), 1, 1, polar=True)
722 739 self.ax.firsttime = True
723 740
724 741
725 742 def plot(self):
726 743
727 744 arrayParameters = np.concatenate([self.data['param'][t] for t in self.times])
728 745 error = arrayParameters[:,-1]
729 746 indValid = numpy.where(error == 0)[0]
730 747 finalMeteor = arrayParameters[indValid,:]
731 748 finalAzimuth = finalMeteor[:,3]
732 749 finalZenith = finalMeteor[:,4]
733 750
734 751 x = finalAzimuth*numpy.pi/180
735 752 y = finalZenith
736 753
737 754 if self.ax.firsttime:
738 755 self.ax.plot = self.ax.plot(x, y, 'bo', markersize=5)[0]
739 756 self.ax.set_ylim(0,90)
740 757 self.ax.set_yticks(numpy.arange(0,90,20))
741 758 self.ax.set_xlabel(self.xlabel)
742 759 self.ax.set_ylabel(self.ylabel)
743 760 self.ax.yaxis.labelpad = 40
744 761 self.ax.firsttime = False
745 762 else:
746 763 self.ax.plot.set_data(x, y)
747 764
748 765
749 766 dt1 = datetime.datetime.fromtimestamp(self.min_time).strftime('%y/%m/%d %H:%M:%S')
750 767 dt2 = datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')
751 768 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
752 769 dt2,
753 770 len(x))
754 771 self.ax.set_title(title, size=8)
755 772
756 773 self.saveTime = self.max_time
@@ -1,1946 +1,1945
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 MomentsPlot(Figure):
10 10
11 11 isConfig = None
12 12 __nsubplots = None
13 13
14 14 WIDTHPROF = None
15 15 HEIGHTPROF = None
16 16 PREFIX = 'prm'
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 = 280
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 = MOMENTS_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 def getSubplots(self):
37 37
38 38 ncol = int(numpy.sqrt(self.nplots)+0.9)
39 39 nrow = int(self.nplots*1./ncol + 0.9)
40 40
41 41 return nrow, ncol
42 42
43 43 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
44 44
45 45 self.__showprofile = showprofile
46 46 self.nplots = nplots
47 47
48 48 ncolspan = 1
49 49 colspan = 1
50 50 if showprofile:
51 51 ncolspan = 3
52 52 colspan = 2
53 53 self.__nsubplots = 2
54 54
55 55 self.createFigure(id = id,
56 56 wintitle = wintitle,
57 57 widthplot = self.WIDTH + self.WIDTHPROF,
58 58 heightplot = self.HEIGHT + self.HEIGHTPROF,
59 59 show=show)
60 60
61 61 nrow, ncol = self.getSubplots()
62 62
63 63 counter = 0
64 64 for y in range(nrow):
65 65 for x in range(ncol):
66 66
67 67 if counter >= self.nplots:
68 68 break
69 69
70 70 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
71 71
72 72 if showprofile:
73 73 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
74 74
75 75 counter += 1
76 76
77 77 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
78 78 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
79 79 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
80 80 server=None, folder=None, username=None, password=None,
81 81 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
82 82
83 83 """
84 84
85 85 Input:
86 86 dataOut :
87 87 id :
88 88 wintitle :
89 89 channelList :
90 90 showProfile :
91 91 xmin : None,
92 92 xmax : None,
93 93 ymin : None,
94 94 ymax : None,
95 95 zmin : None,
96 96 zmax : None
97 97 """
98 98
99 99 if dataOut.flagNoData:
100 100 return 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"
114 114 channelIndexList.append(dataOut.channelList.index(channel))
115 115
116 116 factor = dataOut.normFactor
117 117 x = dataOut.abscissaList
118 118 y = dataOut.heightList
119 119
120 120 z = dataOut.data_pre[channelIndexList,:,:]/factor
121 121 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
122 122 avg = numpy.average(z, axis=1)
123 123 noise = dataOut.noise/factor
124 124
125 125 zdB = 10*numpy.log10(z)
126 126 avgdB = 10*numpy.log10(avg)
127 127 noisedB = 10*numpy.log10(noise)
128 128
129 129 #thisDatetime = dataOut.datatime
130 130 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
131 131 title = wintitle + " Parameters"
132 132 xlabel = "Velocity (m/s)"
133 133 ylabel = "Range (Km)"
134 134
135 135 update_figfile = False
136 136
137 137 if not self.isConfig:
138 138
139 139 nplots = len(channelIndexList)
140 140
141 141 self.setup(id=id,
142 142 nplots=nplots,
143 143 wintitle=wintitle,
144 144 showprofile=showprofile,
145 145 show=show)
146 146
147 147 if xmin == None: xmin = numpy.nanmin(x)
148 148 if xmax == None: xmax = numpy.nanmax(x)
149 149 if ymin == None: ymin = numpy.nanmin(y)
150 150 if ymax == None: ymax = numpy.nanmax(y)
151 151 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
152 152 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
153 153
154 154 self.FTP_WEI = ftp_wei
155 155 self.EXP_CODE = exp_code
156 156 self.SUB_EXP_CODE = sub_exp_code
157 157 self.PLOT_POS = plot_pos
158 158
159 159 self.isConfig = True
160 160 update_figfile = True
161 161
162 162 self.setWinTitle(title)
163 163
164 164 for i in range(self.nplots):
165 165 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
166 166 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i], noisedB[i], str_datetime)
167 167 axes = self.axesList[i*self.__nsubplots]
168 168 axes.pcolor(x, y, zdB[i,:,:],
169 169 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
170 170 xlabel=xlabel, ylabel=ylabel, title=title,
171 171 ticksize=9, cblabel='')
172 172 #Mean Line
173 173 mean = dataOut.data_param[i, 1, :]
174 174 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
175 175
176 176 if self.__showprofile:
177 177 axes = self.axesList[i*self.__nsubplots +1]
178 178 axes.pline(avgdB[i], y,
179 179 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
180 180 xlabel='dB', ylabel='', title='',
181 181 ytick_visible=False,
182 182 grid='x')
183 183
184 184 noiseline = numpy.repeat(noisedB[i], len(y))
185 185 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
186 186
187 187 self.draw()
188 188
189 189 self.save(figpath=figpath,
190 190 figfile=figfile,
191 191 save=save,
192 192 ftp=ftp,
193 193 wr_period=wr_period,
194 194 thisDatetime=thisDatetime)
195 195
196 196
197 197
198 198 class SkyMapPlot(Figure):
199 199
200 200 __isConfig = None
201 201 __nsubplots = None
202 202
203 203 WIDTHPROF = None
204 204 HEIGHTPROF = None
205 205 PREFIX = 'mmap'
206 206
207 207 def __init__(self, **kwargs):
208 208 Figure.__init__(self, **kwargs)
209 209 self.isConfig = False
210 210 self.__nsubplots = 1
211 211
212 212 # self.WIDTH = 280
213 213 # self.HEIGHT = 250
214 214 self.WIDTH = 600
215 215 self.HEIGHT = 600
216 216 self.WIDTHPROF = 120
217 217 self.HEIGHTPROF = 0
218 218 self.counter_imagwr = 0
219 219
220 220 self.PLOT_CODE = MSKYMAP_CODE
221 221
222 222 self.FTP_WEI = None
223 223 self.EXP_CODE = None
224 224 self.SUB_EXP_CODE = None
225 225 self.PLOT_POS = None
226 226
227 227 def getSubplots(self):
228 228
229 229 ncol = int(numpy.sqrt(self.nplots)+0.9)
230 230 nrow = int(self.nplots*1./ncol + 0.9)
231 231
232 232 return nrow, ncol
233 233
234 234 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
235 235
236 236 self.__showprofile = showprofile
237 237 self.nplots = nplots
238 238
239 239 ncolspan = 1
240 240 colspan = 1
241 241
242 242 self.createFigure(id = id,
243 243 wintitle = wintitle,
244 244 widthplot = self.WIDTH, #+ self.WIDTHPROF,
245 245 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
246 246 show=show)
247 247
248 248 nrow, ncol = 1,1
249 249 counter = 0
250 250 x = 0
251 251 y = 0
252 252 self.addAxes(1, 1, 0, 0, 1, 1, True)
253 253
254 254 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
255 255 tmin=0, tmax=24, timerange=None,
256 256 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
257 257 server=None, folder=None, username=None, password=None,
258 258 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
259 259
260 260 """
261 261
262 262 Input:
263 263 dataOut :
264 264 id :
265 265 wintitle :
266 266 channelList :
267 267 showProfile :
268 268 xmin : None,
269 269 xmax : None,
270 270 ymin : None,
271 271 ymax : None,
272 272 zmin : None,
273 273 zmax : None
274 274 """
275 275
276 276 arrayParameters = dataOut.data_param
277 277 error = arrayParameters[:,-1]
278 278 indValid = numpy.where(error == 0)[0]
279 279 finalMeteor = arrayParameters[indValid,:]
280 280 finalAzimuth = finalMeteor[:,3]
281 281 finalZenith = finalMeteor[:,4]
282 282
283 283 x = finalAzimuth*numpy.pi/180
284 284 y = finalZenith
285 285 x1 = [dataOut.ltctime, dataOut.ltctime]
286 286
287 287 #thisDatetime = dataOut.datatime
288 288 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
289 289 title = wintitle + " Parameters"
290 290 xlabel = "Zonal Zenith Angle (deg) "
291 291 ylabel = "Meridional Zenith Angle (deg)"
292 292 update_figfile = False
293 293
294 294 if not self.isConfig:
295 295
296 296 nplots = 1
297 297
298 298 self.setup(id=id,
299 299 nplots=nplots,
300 300 wintitle=wintitle,
301 301 showprofile=showprofile,
302 302 show=show)
303 303
304 304 if self.xmin is None and self.xmax is None:
305 305 self.xmin, self.xmax = self.getTimeLim(x1, tmin, tmax, timerange)
306 306
307 307 if timerange != None:
308 308 self.timerange = timerange
309 309 else:
310 310 self.timerange = self.xmax - self.xmin
311 311
312 312 self.FTP_WEI = ftp_wei
313 313 self.EXP_CODE = exp_code
314 314 self.SUB_EXP_CODE = sub_exp_code
315 315 self.PLOT_POS = plot_pos
316 316 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
317 317 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
318 318 self.isConfig = True
319 319 update_figfile = True
320 320
321 321 self.setWinTitle(title)
322 322
323 323 i = 0
324 324 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
325 325
326 326 axes = self.axesList[i*self.__nsubplots]
327 327 nevents = axes.x_buffer.shape[0] + x.shape[0]
328 328 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
329 329 axes.polar(x, y,
330 330 title=title, xlabel=xlabel, ylabel=ylabel,
331 331 ticksize=9, cblabel='')
332 332
333 333 self.draw()
334 334
335 335 self.save(figpath=figpath,
336 336 figfile=figfile,
337 337 save=save,
338 338 ftp=ftp,
339 339 wr_period=wr_period,
340 340 thisDatetime=thisDatetime,
341 341 update_figfile=update_figfile)
342 342
343 343 if dataOut.ltctime >= self.xmax:
344 344 self.isConfigmagwr = wr_period
345 345 self.isConfig = False
346 346 update_figfile = True
347 347 axes.__firsttime = True
348 348 self.xmin += self.timerange
349 349 self.xmax += self.timerange
350 350
351 351
352 352
353 353
354 354 class WindProfilerPlot(Figure):
355 355
356 356 __isConfig = None
357 357 __nsubplots = None
358 358
359 359 WIDTHPROF = None
360 360 HEIGHTPROF = None
361 361 PREFIX = 'wind'
362 362
363 363 def __init__(self, **kwargs):
364 364 Figure.__init__(self, **kwargs)
365 365 self.timerange = None
366 366 self.isConfig = False
367 367 self.__nsubplots = 1
368 368
369 369 self.WIDTH = 800
370 370 self.HEIGHT = 300
371 371 self.WIDTHPROF = 120
372 372 self.HEIGHTPROF = 0
373 373 self.counter_imagwr = 0
374 374
375 375 self.PLOT_CODE = WIND_CODE
376 376
377 377 self.FTP_WEI = None
378 378 self.EXP_CODE = None
379 379 self.SUB_EXP_CODE = None
380 380 self.PLOT_POS = None
381 381 self.tmin = None
382 382 self.tmax = None
383 383
384 384 self.xmin = None
385 385 self.xmax = None
386 386
387 387 self.figfile = None
388 388
389 389 def getSubplots(self):
390 390
391 391 ncol = 1
392 392 nrow = self.nplots
393 393
394 394 return nrow, ncol
395 395
396 396 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
397 397
398 398 self.__showprofile = showprofile
399 399 self.nplots = nplots
400 400
401 401 ncolspan = 1
402 402 colspan = 1
403 403
404 404 self.createFigure(id = id,
405 405 wintitle = wintitle,
406 406 widthplot = self.WIDTH + self.WIDTHPROF,
407 407 heightplot = self.HEIGHT + self.HEIGHTPROF,
408 408 show=show)
409 409
410 410 nrow, ncol = self.getSubplots()
411 411
412 412 counter = 0
413 413 for y in range(nrow):
414 414 if counter >= self.nplots:
415 415 break
416 416
417 417 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
418 418 counter += 1
419 419
420 420 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='False',
421 421 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
422 422 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
423 423 timerange=None, SNRthresh = None,
424 424 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
425 425 server=None, folder=None, username=None, password=None,
426 426 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
427 427 """
428 428
429 429 Input:
430 430 dataOut :
431 431 id :
432 432 wintitle :
433 433 channelList :
434 434 showProfile :
435 435 xmin : None,
436 436 xmax : None,
437 437 ymin : None,
438 438 ymax : None,
439 439 zmin : None,
440 440 zmax : None
441 441 """
442 442
443 443 # if timerange is not None:
444 444 # self.timerange = timerange
445 445 #
446 446 # tmin = None
447 447 # tmax = None
448 448
449 449
450 450 x = dataOut.getTimeRange1(dataOut.outputInterval)
451 451 y = dataOut.heightList
452 452 z = dataOut.data_output.copy()
453 453 nplots = z.shape[0] #Number of wind dimensions estimated
454 454 nplotsw = nplots
455 455
456 456
457 457 #If there is a SNR function defined
458 458 if dataOut.data_SNR is not None:
459 459 nplots += 1
460 460 SNR = dataOut.data_SNR
461 461 SNRavg = numpy.average(SNR, axis=0)
462 462
463 463 SNRdB = 10*numpy.log10(SNR)
464 464 SNRavgdB = 10*numpy.log10(SNRavg)
465 465
466 466 if SNRthresh == None: SNRthresh = -5.0
467 467 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
468 468
469 469 for i in range(nplotsw):
470 470 z[i,ind] = numpy.nan
471 471
472 472 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
473 473 #thisDatetime = datetime.datetime.now()
474 474 title = wintitle + "Wind"
475 475 xlabel = ""
476 476 ylabel = "Height (km)"
477 477 update_figfile = False
478 478
479 479 if not self.isConfig:
480 480
481 481 self.setup(id=id,
482 482 nplots=nplots,
483 483 wintitle=wintitle,
484 484 showprofile=showprofile,
485 485 show=show)
486 486
487 487 if timerange is not None:
488 488 self.timerange = timerange
489 489
490 490 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
491 491
492 492 if ymin == None: ymin = numpy.nanmin(y)
493 493 if ymax == None: ymax = numpy.nanmax(y)
494 494
495 495 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
496 496 #if numpy.isnan(zmax): zmax = 50
497 497 if zmin == None: zmin = -zmax
498 498
499 499 if nplotsw == 3:
500 500 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
501 501 if zmin_ver == None: zmin_ver = -zmax_ver
502 502
503 503 if dataOut.data_SNR is not None:
504 504 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
505 505 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
506 506
507 507
508 508 self.FTP_WEI = ftp_wei
509 509 self.EXP_CODE = exp_code
510 510 self.SUB_EXP_CODE = sub_exp_code
511 511 self.PLOT_POS = plot_pos
512 512
513 513 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
514 514 self.isConfig = True
515 515 self.figfile = figfile
516 516 update_figfile = True
517 517
518 518 self.setWinTitle(title)
519 519
520 520 if ((self.xmax - x[1]) < (x[1]-x[0])):
521 521 x[1] = self.xmax
522 522
523 523 strWind = ['Zonal', 'Meridional', 'Vertical']
524 524 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
525 525 zmaxVector = [zmax, zmax, zmax_ver]
526 526 zminVector = [zmin, zmin, zmin_ver]
527 527 windFactor = [1,1,100]
528 528
529 529 for i in range(nplotsw):
530 530
531 531 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
532 532 axes = self.axesList[i*self.__nsubplots]
533 533
534 534 z1 = z[i,:].reshape((1,-1))*windFactor[i]
535 535 #z1=numpy.ma.masked_where(z1==0.,z1)
536 536
537 537 axes.pcolorbuffer(x, y, z1,
538 538 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
539 539 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
540 540 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="seismic" )
541 541
542 542 if dataOut.data_SNR is not None:
543 543 i += 1
544 544 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
545 545 axes = self.axesList[i*self.__nsubplots]
546 546 SNRavgdB = SNRavgdB.reshape((1,-1))
547 547 axes.pcolorbuffer(x, y, SNRavgdB,
548 548 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
549 549 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
550 550 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
551 551
552 552 self.draw()
553 553
554 554 self.save(figpath=figpath,
555 555 figfile=figfile,
556 556 save=save,
557 557 ftp=ftp,
558 558 wr_period=wr_period,
559 559 thisDatetime=thisDatetime,
560 560 update_figfile=update_figfile)
561 561
562 562 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
563 563 self.counter_imagwr = wr_period
564 564 self.isConfig = False
565 565 update_figfile = True
566 566
567 567
568 568 class ParametersPlot(Figure):
569 569
570 570 __isConfig = None
571 571 __nsubplots = None
572 572
573 573 WIDTHPROF = None
574 574 HEIGHTPROF = None
575 575 PREFIX = 'param'
576 576
577 577 nplots = None
578 578 nchan = None
579 579
580 580 def __init__(self, **kwargs):
581 581 Figure.__init__(self, **kwargs)
582 582 self.timerange = None
583 583 self.isConfig = False
584 584 self.__nsubplots = 1
585 585
586 586 self.WIDTH = 800
587 587 self.HEIGHT = 180
588 588 self.WIDTHPROF = 120
589 589 self.HEIGHTPROF = 0
590 590 self.counter_imagwr = 0
591 591
592 592 self.PLOT_CODE = RTI_CODE
593 593
594 594 self.FTP_WEI = None
595 595 self.EXP_CODE = None
596 596 self.SUB_EXP_CODE = None
597 597 self.PLOT_POS = None
598 598 self.tmin = None
599 599 self.tmax = None
600 600
601 601 self.xmin = None
602 602 self.xmax = None
603 603
604 604 self.figfile = None
605 605
606 606 def getSubplots(self):
607 607
608 608 ncol = 1
609 609 nrow = self.nplots
610 610
611 611 return nrow, ncol
612 612
613 613 def setup(self, id, nplots, wintitle, show=True):
614 614
615 615 self.nplots = nplots
616 616
617 617 ncolspan = 1
618 618 colspan = 1
619 619
620 620 self.createFigure(id = id,
621 621 wintitle = wintitle,
622 622 widthplot = self.WIDTH + self.WIDTHPROF,
623 623 heightplot = self.HEIGHT + self.HEIGHTPROF,
624 624 show=show)
625 625
626 626 nrow, ncol = self.getSubplots()
627 627
628 628 counter = 0
629 629 for y in range(nrow):
630 630 for x in range(ncol):
631 631
632 632 if counter >= self.nplots:
633 633 break
634 634
635 635 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
636 636
637 637 counter += 1
638 638
639 639 def run(self, dataOut, id, wintitle="", channelList=None, paramIndex = 0, colormap=True,
640 640 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, timerange=None,
641 641 showSNR=False, SNRthresh = -numpy.inf, SNRmin=None, SNRmax=None,
642 642 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
643 643 server=None, folder=None, username=None, password=None,
644 644 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
645
646 645 """
647 646
648 647 Input:
649 648 dataOut :
650 649 id :
651 650 wintitle :
652 651 channelList :
653 652 showProfile :
654 653 xmin : None,
655 654 xmax : None,
656 655 ymin : None,
657 656 ymax : None,
658 657 zmin : None,
659 658 zmax : None
660 659 """
661 660
662 661 if colormap:
663 662 colormap="jet"
664 663 else:
665 664 colormap="RdBu_r"
666 665
667 666 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
668 667 return
669 668
670 669 if channelList == None:
671 670 channelIndexList = range(dataOut.data_param.shape[0])
672 671 else:
673 672 channelIndexList = []
674 673 for channel in channelList:
675 674 if channel not in dataOut.channelList:
676 675 raise ValueError, "Channel %d is not in dataOut.channelList"
677 676 channelIndexList.append(dataOut.channelList.index(channel))
678 677
679 678 x = dataOut.getTimeRange1(dataOut.paramInterval)
680 679 y = dataOut.getHeiRange()
681 680
682 681 if dataOut.data_param.ndim == 3:
683 682 z = dataOut.data_param[channelIndexList,paramIndex,:]
684 683 else:
685 684 z = dataOut.data_param[channelIndexList,:]
686 685
687 686 if showSNR:
688 687 #SNR data
689 688 SNRarray = dataOut.data_SNR[channelIndexList,:]
690 689 SNRdB = 10*numpy.log10(SNRarray)
691 690 ind = numpy.where(SNRdB < SNRthresh)
692 691 z[ind] = numpy.nan
693 692
694 693 thisDatetime = dataOut.datatime
695 694 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
696 695 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
697 696 xlabel = ""
698 697 ylabel = "Range (Km)"
699 698
700 699 update_figfile = False
701 700
702 701 if not self.isConfig:
703 702
704 703 nchan = len(channelIndexList)
705 704 self.nchan = nchan
706 705 self.plotFact = 1
707 706 nplots = nchan
708 707
709 708 if showSNR:
710 709 nplots = nchan*2
711 710 self.plotFact = 2
712 711 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
713 712 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
714 713
715 714 self.setup(id=id,
716 715 nplots=nplots,
717 716 wintitle=wintitle,
718 717 show=show)
719 718
720 719 if timerange != None:
721 720 self.timerange = timerange
722 721
723 722 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
724 723
725 724 if ymin == None: ymin = numpy.nanmin(y)
726 725 if ymax == None: ymax = numpy.nanmax(y)
727 726 if zmin == None: zmin = numpy.nanmin(z)
728 727 if zmax == None: zmax = numpy.nanmax(z)
729 728
730 729 self.FTP_WEI = ftp_wei
731 730 self.EXP_CODE = exp_code
732 731 self.SUB_EXP_CODE = sub_exp_code
733 732 self.PLOT_POS = plot_pos
734 733
735 734 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
736 735 self.isConfig = True
737 736 self.figfile = figfile
738 737 update_figfile = True
739 738
740 739 self.setWinTitle(title)
741 740
742 741 for i in range(self.nchan):
743 742 index = channelIndexList[i]
744 743 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
745 744 axes = self.axesList[i*self.plotFact]
746 745 z1 = z[i,:].reshape((1,-1))
747 746 axes.pcolorbuffer(x, y, z1,
748 747 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
749 748 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
750 749 ticksize=9, cblabel='', cbsize="1%",colormap=colormap)
751 750
752 751 if showSNR:
753 752 title = "Channel %d SNR: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
754 753 axes = self.axesList[i*self.plotFact + 1]
755 754 SNRdB1 = SNRdB[i,:].reshape((1,-1))
756 755 axes.pcolorbuffer(x, y, SNRdB1,
757 756 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
758 757 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
759 758 ticksize=9, cblabel='', cbsize="1%",colormap='jet')
760 759
761 760
762 761 self.draw()
763 762
764 763 if dataOut.ltctime >= self.xmax:
765 764 self.counter_imagwr = wr_period
766 765 self.isConfig = False
767 766 update_figfile = True
768 767
769 768 self.save(figpath=figpath,
770 769 figfile=figfile,
771 770 save=save,
772 771 ftp=ftp,
773 772 wr_period=wr_period,
774 773 thisDatetime=thisDatetime,
775 774 update_figfile=update_figfile)
776 775
777 776
778 777
779 778 class Parameters1Plot(Figure):
780 779
781 780 __isConfig = None
782 781 __nsubplots = None
783 782
784 783 WIDTHPROF = None
785 784 HEIGHTPROF = None
786 785 PREFIX = 'prm'
787 786
788 787 def __init__(self, **kwargs):
789 788 Figure.__init__(self, **kwargs)
790 789 self.timerange = 2*60*60
791 790 self.isConfig = False
792 791 self.__nsubplots = 1
793 792
794 793 self.WIDTH = 800
795 self.HEIGHT = 150
794 self.HEIGHT = 180
796 795 self.WIDTHPROF = 120
797 796 self.HEIGHTPROF = 0
798 797 self.counter_imagwr = 0
799 798
800 799 self.PLOT_CODE = PARMS_CODE
801 800
802 801 self.FTP_WEI = None
803 802 self.EXP_CODE = None
804 803 self.SUB_EXP_CODE = None
805 804 self.PLOT_POS = None
806 805 self.tmin = None
807 806 self.tmax = None
808 807
809 808 self.xmin = None
810 809 self.xmax = None
811 810
812 811 self.figfile = None
813 812
814 813 def getSubplots(self):
815 814
816 815 ncol = 1
817 816 nrow = self.nplots
818 817
819 818 return nrow, ncol
820 819
821 820 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
822 821
823 822 self.__showprofile = showprofile
824 823 self.nplots = nplots
825 824
826 825 ncolspan = 1
827 826 colspan = 1
828 827
829 828 self.createFigure(id = id,
830 829 wintitle = wintitle,
831 830 widthplot = self.WIDTH + self.WIDTHPROF,
832 831 heightplot = self.HEIGHT + self.HEIGHTPROF,
833 832 show=show)
834 833
835 834 nrow, ncol = self.getSubplots()
836 835
837 836 counter = 0
838 837 for y in range(nrow):
839 838 for x in range(ncol):
840 839
841 840 if counter >= self.nplots:
842 841 break
843 842
844 843 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
845 844
846 845 if showprofile:
847 846 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
848 847
849 848 counter += 1
850 849
851 850 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
852 851 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
853 852 parameterIndex = None, onlyPositive = False,
854 853 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None, onlySNR = False,
855 854 DOP = True,
856 855 zlabel = "", parameterName = "", parameterObject = "data_param",
857 856 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
858 857 server=None, folder=None, username=None, password=None,
859 858 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
860
859 #print inspect.getargspec(self.run).args
861 860 """
862 861
863 862 Input:
864 863 dataOut :
865 864 id :
866 865 wintitle :
867 866 channelList :
868 867 showProfile :
869 868 xmin : None,
870 869 xmax : None,
871 870 ymin : None,
872 871 ymax : None,
873 872 zmin : None,
874 873 zmax : None
875 874 """
876 875
877 876 data_param = getattr(dataOut, parameterObject)
878 877
879 878 if channelList == None:
880 879 channelIndexList = numpy.arange(data_param.shape[0])
881 880 else:
882 881 channelIndexList = numpy.array(channelList)
883 882
884 883 nchan = len(channelIndexList) #Number of channels being plotted
885 884
886 885 if nchan < 1:
887 886 return
888 887
889 888 nGraphsByChannel = 0
890 889
891 890 if SNR:
892 891 nGraphsByChannel += 1
893 892 if DOP:
894 893 nGraphsByChannel += 1
895 894
896 895 if nGraphsByChannel < 1:
897 896 return
898 897
899 898 nplots = nGraphsByChannel*nchan
900 899
901 900 if timerange is not None:
902 901 self.timerange = timerange
903 902
904 903 #tmin = None
905 904 #tmax = None
906 905 if parameterIndex == None:
907 906 parameterIndex = 1
908 907
909 908 x = dataOut.getTimeRange1(dataOut.paramInterval)
910 909 y = dataOut.heightList
911 910 z = data_param[channelIndexList,parameterIndex,:].copy()
912 911
913 912 zRange = dataOut.abscissaList
914 913 # nChannels = z.shape[0] #Number of wind dimensions estimated
915 914 # thisDatetime = dataOut.datatime
916 915
917 916 if dataOut.data_SNR is not None:
918 917 SNRarray = dataOut.data_SNR[channelIndexList,:]
919 918 SNRdB = 10*numpy.log10(SNRarray)
920 919 # SNRavgdB = 10*numpy.log10(SNRavg)
921 920 ind = numpy.where(SNRdB < 10**(SNRthresh/10))
922 921 z[ind] = numpy.nan
923 922
924 923 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
925 924 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
926 925 xlabel = ""
927 926 ylabel = "Range (Km)"
928 927
929 928 if (SNR and not onlySNR): nplots = 2*nplots
930 929
931 930 if onlyPositive:
932 931 colormap = "jet"
933 932 zmin = 0
934 933 else: colormap = "RdBu_r"
935 934
936 935 if not self.isConfig:
937 936
938 937 self.setup(id=id,
939 938 nplots=nplots,
940 939 wintitle=wintitle,
941 940 showprofile=showprofile,
942 941 show=show)
943 942
944 943 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
945 944
946 945 if ymin == None: ymin = numpy.nanmin(y)
947 946 if ymax == None: ymax = numpy.nanmax(y)
948 947 if zmin == None: zmin = numpy.nanmin(zRange)
949 948 if zmax == None: zmax = numpy.nanmax(zRange)
950 949
951 950 if SNR:
952 951 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
953 952 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
954 953
955 954 self.FTP_WEI = ftp_wei
956 955 self.EXP_CODE = exp_code
957 956 self.SUB_EXP_CODE = sub_exp_code
958 957 self.PLOT_POS = plot_pos
959 958
960 959 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
961 960 self.isConfig = True
962 961 self.figfile = figfile
963 962
964 963 self.setWinTitle(title)
965 964
966 965 if ((self.xmax - x[1]) < (x[1]-x[0])):
967 966 x[1] = self.xmax
968 967
969 968 for i in range(nchan):
970 969
971 970 if (SNR and not onlySNR): j = 2*i
972 971 else: j = i
973 972
974 973 j = nGraphsByChannel*i
975 974
976 975 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
977 976 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
978 977
979 978 if not onlySNR:
980 979 axes = self.axesList[j*self.__nsubplots]
981 980 z1 = z[i,:].reshape((1,-1))
982 981 axes.pcolorbuffer(x, y, z1,
983 982 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
984 983 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
985 984 ticksize=9, cblabel=zlabel, cbsize="1%")
986 985
987 986 if DOP:
988 987 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
989 988
990 989 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
991 990 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
992 991 axes = self.axesList[j]
993 992 z1 = z[i,:].reshape((1,-1))
994 993 axes.pcolorbuffer(x, y, z1,
995 994 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
996 995 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
997 996 ticksize=9, cblabel=zlabel, cbsize="1%")
998 997
999 998 if SNR:
1000 999 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1001 1000 axes = self.axesList[(j)*self.__nsubplots]
1002 1001 if not onlySNR:
1003 1002 axes = self.axesList[(j + 1)*self.__nsubplots]
1004 1003
1005 1004 axes = self.axesList[(j + nGraphsByChannel-1)]
1006 1005
1007 1006 z1 = SNRdB[i,:].reshape((1,-1))
1008 1007 axes.pcolorbuffer(x, y, z1,
1009 1008 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1010 1009 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
1011 1010 ticksize=9, cblabel=zlabel, cbsize="1%")
1012 1011
1013 1012
1014 1013
1015 1014 self.draw()
1016 1015
1017 1016 if x[1] >= self.axesList[0].xmax:
1018 1017 self.counter_imagwr = wr_period
1019 1018 self.isConfig = False
1020 1019 self.figfile = None
1021 1020
1022 1021 self.save(figpath=figpath,
1023 1022 figfile=figfile,
1024 1023 save=save,
1025 1024 ftp=ftp,
1026 1025 wr_period=wr_period,
1027 1026 thisDatetime=thisDatetime,
1028 1027 update_figfile=False)
1029 1028
1030 1029 class SpectralFittingPlot(Figure):
1031 1030
1032 1031 __isConfig = None
1033 1032 __nsubplots = None
1034 1033
1035 1034 WIDTHPROF = None
1036 1035 HEIGHTPROF = None
1037 1036 PREFIX = 'prm'
1038 1037
1039 1038
1040 1039 N = None
1041 1040 ippSeconds = None
1042 1041
1043 1042 def __init__(self, **kwargs):
1044 1043 Figure.__init__(self, **kwargs)
1045 1044 self.isConfig = False
1046 1045 self.__nsubplots = 1
1047 1046
1048 1047 self.PLOT_CODE = SPECFIT_CODE
1049 1048
1050 1049 self.WIDTH = 450
1051 1050 self.HEIGHT = 250
1052 1051 self.WIDTHPROF = 0
1053 1052 self.HEIGHTPROF = 0
1054 1053
1055 1054 def getSubplots(self):
1056 1055
1057 1056 ncol = int(numpy.sqrt(self.nplots)+0.9)
1058 1057 nrow = int(self.nplots*1./ncol + 0.9)
1059 1058
1060 1059 return nrow, ncol
1061 1060
1062 1061 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
1063 1062
1064 1063 showprofile = False
1065 1064 self.__showprofile = showprofile
1066 1065 self.nplots = nplots
1067 1066
1068 1067 ncolspan = 5
1069 1068 colspan = 4
1070 1069 if showprofile:
1071 1070 ncolspan = 5
1072 1071 colspan = 4
1073 1072 self.__nsubplots = 2
1074 1073
1075 1074 self.createFigure(id = id,
1076 1075 wintitle = wintitle,
1077 1076 widthplot = self.WIDTH + self.WIDTHPROF,
1078 1077 heightplot = self.HEIGHT + self.HEIGHTPROF,
1079 1078 show=show)
1080 1079
1081 1080 nrow, ncol = self.getSubplots()
1082 1081
1083 1082 counter = 0
1084 1083 for y in range(nrow):
1085 1084 for x in range(ncol):
1086 1085
1087 1086 if counter >= self.nplots:
1088 1087 break
1089 1088
1090 1089 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1091 1090
1092 1091 if showprofile:
1093 1092 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1094 1093
1095 1094 counter += 1
1096 1095
1097 1096 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
1098 1097 xmin=None, xmax=None, ymin=None, ymax=None,
1099 1098 save=False, figpath='./', figfile=None, show=True):
1100 1099
1101 1100 """
1102 1101
1103 1102 Input:
1104 1103 dataOut :
1105 1104 id :
1106 1105 wintitle :
1107 1106 channelList :
1108 1107 showProfile :
1109 1108 xmin : None,
1110 1109 xmax : None,
1111 1110 zmin : None,
1112 1111 zmax : None
1113 1112 """
1114 1113
1115 1114 if cutHeight==None:
1116 1115 h=270
1117 1116 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
1118 1117 cutHeight = dataOut.heightList[heightindex]
1119 1118
1120 1119 factor = dataOut.normFactor
1121 1120 x = dataOut.abscissaList[:-1]
1122 1121 #y = dataOut.getHeiRange()
1123 1122
1124 1123 z = dataOut.data_pre[:,:,heightindex]/factor
1125 1124 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1126 1125 avg = numpy.average(z, axis=1)
1127 1126 listChannels = z.shape[0]
1128 1127
1129 1128 #Reconstruct Function
1130 1129 if fit==True:
1131 1130 groupArray = dataOut.groupList
1132 1131 listChannels = groupArray.reshape((groupArray.size))
1133 1132 listChannels.sort()
1134 1133 spcFitLine = numpy.zeros(z.shape)
1135 1134 constants = dataOut.constants
1136 1135
1137 1136 nGroups = groupArray.shape[0]
1138 1137 nChannels = groupArray.shape[1]
1139 1138 nProfiles = z.shape[1]
1140 1139
1141 1140 for f in range(nGroups):
1142 1141 groupChann = groupArray[f,:]
1143 1142 p = dataOut.data_param[f,:,heightindex]
1144 1143 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
1145 1144 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
1146 1145 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
1147 1146 spcFitLine[groupChann,:] = fitLineAux
1148 1147 # spcFitLine = spcFitLine/factor
1149 1148
1150 1149 z = z[listChannels,:]
1151 1150 spcFitLine = spcFitLine[listChannels,:]
1152 1151 spcFitLinedB = 10*numpy.log10(spcFitLine)
1153 1152
1154 1153 zdB = 10*numpy.log10(z)
1155 1154 #thisDatetime = dataOut.datatime
1156 1155 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1157 1156 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1158 1157 xlabel = "Velocity (m/s)"
1159 1158 ylabel = "Spectrum"
1160 1159
1161 1160 if not self.isConfig:
1162 1161
1163 1162 nplots = listChannels.size
1164 1163
1165 1164 self.setup(id=id,
1166 1165 nplots=nplots,
1167 1166 wintitle=wintitle,
1168 1167 showprofile=showprofile,
1169 1168 show=show)
1170 1169
1171 1170 if xmin == None: xmin = numpy.nanmin(x)
1172 1171 if xmax == None: xmax = numpy.nanmax(x)
1173 1172 if ymin == None: ymin = numpy.nanmin(zdB)
1174 1173 if ymax == None: ymax = numpy.nanmax(zdB)+2
1175 1174
1176 1175 self.isConfig = True
1177 1176
1178 1177 self.setWinTitle(title)
1179 1178 for i in range(self.nplots):
1180 1179 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
1181 1180 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i])
1182 1181 axes = self.axesList[i*self.__nsubplots]
1183 1182 if fit == False:
1184 1183 axes.pline(x, zdB[i,:],
1185 1184 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1186 1185 xlabel=xlabel, ylabel=ylabel, title=title
1187 1186 )
1188 1187 if fit == True:
1189 1188 fitline=spcFitLinedB[i,:]
1190 1189 y=numpy.vstack([zdB[i,:],fitline] )
1191 1190 legendlabels=['Data','Fitting']
1192 1191 axes.pmultilineyaxis(x, y,
1193 1192 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1194 1193 xlabel=xlabel, ylabel=ylabel, title=title,
1195 1194 legendlabels=legendlabels, marker=None,
1196 1195 linestyle='solid', grid='both')
1197 1196
1198 1197 self.draw()
1199 1198
1200 1199 self.save(figpath=figpath,
1201 1200 figfile=figfile,
1202 1201 save=save,
1203 1202 ftp=ftp,
1204 1203 wr_period=wr_period,
1205 1204 thisDatetime=thisDatetime)
1206 1205
1207 1206
1208 1207 class EWDriftsPlot(Figure):
1209 1208
1210 1209 __isConfig = None
1211 1210 __nsubplots = None
1212 1211
1213 1212 WIDTHPROF = None
1214 1213 HEIGHTPROF = None
1215 1214 PREFIX = 'drift'
1216 1215
1217 1216 def __init__(self, **kwargs):
1218 1217 Figure.__init__(self, **kwargs)
1219 1218 self.timerange = 2*60*60
1220 1219 self.isConfig = False
1221 1220 self.__nsubplots = 1
1222 1221
1223 1222 self.WIDTH = 800
1224 1223 self.HEIGHT = 150
1225 1224 self.WIDTHPROF = 120
1226 1225 self.HEIGHTPROF = 0
1227 1226 self.counter_imagwr = 0
1228 1227
1229 1228 self.PLOT_CODE = EWDRIFT_CODE
1230 1229
1231 1230 self.FTP_WEI = None
1232 1231 self.EXP_CODE = None
1233 1232 self.SUB_EXP_CODE = None
1234 1233 self.PLOT_POS = None
1235 1234 self.tmin = None
1236 1235 self.tmax = None
1237 1236
1238 1237 self.xmin = None
1239 1238 self.xmax = None
1240 1239
1241 1240 self.figfile = None
1242 1241
1243 1242 def getSubplots(self):
1244 1243
1245 1244 ncol = 1
1246 1245 nrow = self.nplots
1247 1246
1248 1247 return nrow, ncol
1249 1248
1250 1249 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1251 1250
1252 1251 self.__showprofile = showprofile
1253 1252 self.nplots = nplots
1254 1253
1255 1254 ncolspan = 1
1256 1255 colspan = 1
1257 1256
1258 1257 self.createFigure(id = id,
1259 1258 wintitle = wintitle,
1260 1259 widthplot = self.WIDTH + self.WIDTHPROF,
1261 1260 heightplot = self.HEIGHT + self.HEIGHTPROF,
1262 1261 show=show)
1263 1262
1264 1263 nrow, ncol = self.getSubplots()
1265 1264
1266 1265 counter = 0
1267 1266 for y in range(nrow):
1268 1267 if counter >= self.nplots:
1269 1268 break
1270 1269
1271 1270 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1272 1271 counter += 1
1273 1272
1274 1273 def run(self, dataOut, id, wintitle="", channelList=None,
1275 1274 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1276 1275 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1277 1276 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1278 1277 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1279 1278 server=None, folder=None, username=None, password=None,
1280 1279 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1281 1280 """
1282 1281
1283 1282 Input:
1284 1283 dataOut :
1285 1284 id :
1286 1285 wintitle :
1287 1286 channelList :
1288 1287 showProfile :
1289 1288 xmin : None,
1290 1289 xmax : None,
1291 1290 ymin : None,
1292 1291 ymax : None,
1293 1292 zmin : None,
1294 1293 zmax : None
1295 1294 """
1296 1295
1297 1296 if timerange is not None:
1298 1297 self.timerange = timerange
1299 1298
1300 1299 tmin = None
1301 1300 tmax = None
1302 1301
1303 1302 x = dataOut.getTimeRange1(dataOut.outputInterval)
1304 1303 # y = dataOut.heightList
1305 1304 y = dataOut.heightList
1306 1305
1307 1306 z = dataOut.data_output
1308 1307 nplots = z.shape[0] #Number of wind dimensions estimated
1309 1308 nplotsw = nplots
1310 1309
1311 1310 #If there is a SNR function defined
1312 1311 if dataOut.data_SNR is not None:
1313 1312 nplots += 1
1314 1313 SNR = dataOut.data_SNR
1315 1314
1316 1315 if SNR_1:
1317 1316 SNR += 1
1318 1317
1319 1318 SNRavg = numpy.average(SNR, axis=0)
1320 1319
1321 1320 SNRdB = 10*numpy.log10(SNR)
1322 1321 SNRavgdB = 10*numpy.log10(SNRavg)
1323 1322
1324 1323 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1325 1324
1326 1325 for i in range(nplotsw):
1327 1326 z[i,ind] = numpy.nan
1328 1327
1329 1328
1330 1329 showprofile = False
1331 1330 # thisDatetime = dataOut.datatime
1332 1331 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1333 1332 title = wintitle + " EW Drifts"
1334 1333 xlabel = ""
1335 1334 ylabel = "Height (Km)"
1336 1335
1337 1336 if not self.isConfig:
1338 1337
1339 1338 self.setup(id=id,
1340 1339 nplots=nplots,
1341 1340 wintitle=wintitle,
1342 1341 showprofile=showprofile,
1343 1342 show=show)
1344 1343
1345 1344 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1346 1345
1347 1346 if ymin == None: ymin = numpy.nanmin(y)
1348 1347 if ymax == None: ymax = numpy.nanmax(y)
1349 1348
1350 1349 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1351 1350 if zminZonal == None: zminZonal = -zmaxZonal
1352 1351 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1353 1352 if zminVertical == None: zminVertical = -zmaxVertical
1354 1353
1355 1354 if dataOut.data_SNR is not None:
1356 1355 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1357 1356 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1358 1357
1359 1358 self.FTP_WEI = ftp_wei
1360 1359 self.EXP_CODE = exp_code
1361 1360 self.SUB_EXP_CODE = sub_exp_code
1362 1361 self.PLOT_POS = plot_pos
1363 1362
1364 1363 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1365 1364 self.isConfig = True
1366 1365
1367 1366
1368 1367 self.setWinTitle(title)
1369 1368
1370 1369 if ((self.xmax - x[1]) < (x[1]-x[0])):
1371 1370 x[1] = self.xmax
1372 1371
1373 1372 strWind = ['Zonal','Vertical']
1374 1373 strCb = 'Velocity (m/s)'
1375 1374 zmaxVector = [zmaxZonal, zmaxVertical]
1376 1375 zminVector = [zminZonal, zminVertical]
1377 1376
1378 1377 for i in range(nplotsw):
1379 1378
1380 1379 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1381 1380 axes = self.axesList[i*self.__nsubplots]
1382 1381
1383 1382 z1 = z[i,:].reshape((1,-1))
1384 1383
1385 1384 axes.pcolorbuffer(x, y, z1,
1386 1385 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1387 1386 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1388 1387 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1389 1388
1390 1389 if dataOut.data_SNR is not None:
1391 1390 i += 1
1392 1391 if SNR_1:
1393 1392 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1394 1393 else:
1395 1394 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1396 1395 axes = self.axesList[i*self.__nsubplots]
1397 1396 SNRavgdB = SNRavgdB.reshape((1,-1))
1398 1397
1399 1398 axes.pcolorbuffer(x, y, SNRavgdB,
1400 1399 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1401 1400 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1402 1401 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1403 1402
1404 1403 self.draw()
1405 1404
1406 1405 if x[1] >= self.axesList[0].xmax:
1407 1406 self.counter_imagwr = wr_period
1408 1407 self.isConfig = False
1409 1408 self.figfile = None
1410 1409
1411 1410
1412 1411
1413 1412
1414 1413 class PhasePlot(Figure):
1415 1414
1416 1415 __isConfig = None
1417 1416 __nsubplots = None
1418 1417
1419 1418 PREFIX = 'mphase'
1420 1419
1421 1420 def __init__(self, **kwargs):
1422 1421 Figure.__init__(self, **kwargs)
1423 1422 self.timerange = 24*60*60
1424 1423 self.isConfig = False
1425 1424 self.__nsubplots = 1
1426 1425 self.counter_imagwr = 0
1427 1426 self.WIDTH = 600
1428 1427 self.HEIGHT = 300
1429 1428 self.WIDTHPROF = 120
1430 1429 self.HEIGHTPROF = 0
1431 1430 self.xdata = None
1432 1431 self.ydata = None
1433 1432
1434 1433 self.PLOT_CODE = MPHASE_CODE
1435 1434
1436 1435 self.FTP_WEI = None
1437 1436 self.EXP_CODE = None
1438 1437 self.SUB_EXP_CODE = None
1439 1438 self.PLOT_POS = None
1440 1439
1441 1440
1442 1441 self.filename_phase = None
1443 1442
1444 1443 self.figfile = None
1445 1444
1446 1445 def getSubplots(self):
1447 1446
1448 1447 ncol = 1
1449 1448 nrow = 1
1450 1449
1451 1450 return nrow, ncol
1452 1451
1453 1452 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1454 1453
1455 1454 self.__showprofile = showprofile
1456 1455 self.nplots = nplots
1457 1456
1458 1457 ncolspan = 7
1459 1458 colspan = 6
1460 1459 self.__nsubplots = 2
1461 1460
1462 1461 self.createFigure(id = id,
1463 1462 wintitle = wintitle,
1464 1463 widthplot = self.WIDTH+self.WIDTHPROF,
1465 1464 heightplot = self.HEIGHT+self.HEIGHTPROF,
1466 1465 show=show)
1467 1466
1468 1467 nrow, ncol = self.getSubplots()
1469 1468
1470 1469 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1471 1470
1472 1471
1473 1472 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1474 1473 xmin=None, xmax=None, ymin=None, ymax=None,
1475 1474 timerange=None,
1476 1475 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1477 1476 server=None, folder=None, username=None, password=None,
1478 1477 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1479 1478
1480 1479
1481 1480 tmin = None
1482 1481 tmax = None
1483 1482 x = dataOut.getTimeRange1(dataOut.outputInterval)
1484 1483 y = dataOut.getHeiRange()
1485 1484
1486 1485
1487 1486 #thisDatetime = dataOut.datatime
1488 1487 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1489 1488 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1490 1489 xlabel = "Local Time"
1491 1490 ylabel = "Phase"
1492 1491
1493 1492
1494 1493 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1495 1494 phase_beacon = dataOut.data_output
1496 1495 update_figfile = False
1497 1496
1498 1497 if not self.isConfig:
1499 1498
1500 1499 self.nplots = phase_beacon.size
1501 1500
1502 1501 self.setup(id=id,
1503 1502 nplots=self.nplots,
1504 1503 wintitle=wintitle,
1505 1504 showprofile=showprofile,
1506 1505 show=show)
1507 1506
1508 1507 if timerange is not None:
1509 1508 self.timerange = timerange
1510 1509
1511 1510 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1512 1511
1513 1512 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1514 1513 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1515 1514
1516 1515 self.FTP_WEI = ftp_wei
1517 1516 self.EXP_CODE = exp_code
1518 1517 self.SUB_EXP_CODE = sub_exp_code
1519 1518 self.PLOT_POS = plot_pos
1520 1519
1521 1520 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1522 1521 self.isConfig = True
1523 1522 self.figfile = figfile
1524 1523 self.xdata = numpy.array([])
1525 1524 self.ydata = numpy.array([])
1526 1525
1527 1526 #open file beacon phase
1528 1527 path = '%s%03d' %(self.PREFIX, self.id)
1529 1528 beacon_file = os.path.join(path,'%s.txt'%self.name)
1530 1529 self.filename_phase = os.path.join(figpath,beacon_file)
1531 1530 update_figfile = True
1532 1531
1533 1532
1534 1533 #store data beacon phase
1535 1534 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1536 1535
1537 1536 self.setWinTitle(title)
1538 1537
1539 1538
1540 1539 title = "Phase Offset %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1541 1540
1542 1541 legendlabels = ["phase %d"%(chan) for chan in numpy.arange(self.nplots)]
1543 1542
1544 1543 axes = self.axesList[0]
1545 1544
1546 1545 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1547 1546
1548 1547 if len(self.ydata)==0:
1549 1548 self.ydata = phase_beacon.reshape(-1,1)
1550 1549 else:
1551 1550 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1552 1551
1553 1552
1554 1553 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1555 1554 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1556 1555 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1557 1556 XAxisAsTime=True, grid='both'
1558 1557 )
1559 1558
1560 1559 self.draw()
1561 1560
1562 1561 self.save(figpath=figpath,
1563 1562 figfile=figfile,
1564 1563 save=save,
1565 1564 ftp=ftp,
1566 1565 wr_period=wr_period,
1567 1566 thisDatetime=thisDatetime,
1568 1567 update_figfile=update_figfile)
1569 1568
1570 1569 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
1571 1570 self.counter_imagwr = wr_period
1572 1571 self.isConfig = False
1573 1572 update_figfile = True
1574 1573
1575 1574
1576 1575
1577 1576 class NSMeteorDetection1Plot(Figure):
1578 1577
1579 1578 isConfig = None
1580 1579 __nsubplots = None
1581 1580
1582 1581 WIDTHPROF = None
1583 1582 HEIGHTPROF = None
1584 1583 PREFIX = 'nsm'
1585 1584
1586 1585 zminList = None
1587 1586 zmaxList = None
1588 1587 cmapList = None
1589 1588 titleList = None
1590 1589 nPairs = None
1591 1590 nChannels = None
1592 1591 nParam = None
1593 1592
1594 1593 def __init__(self, **kwargs):
1595 1594 Figure.__init__(self, **kwargs)
1596 1595 self.isConfig = False
1597 1596 self.__nsubplots = 1
1598 1597
1599 1598 self.WIDTH = 750
1600 1599 self.HEIGHT = 250
1601 1600 self.WIDTHPROF = 120
1602 1601 self.HEIGHTPROF = 0
1603 1602 self.counter_imagwr = 0
1604 1603
1605 1604 self.PLOT_CODE = SPEC_CODE
1606 1605
1607 1606 self.FTP_WEI = None
1608 1607 self.EXP_CODE = None
1609 1608 self.SUB_EXP_CODE = None
1610 1609 self.PLOT_POS = None
1611 1610
1612 1611 self.__xfilter_ena = False
1613 1612 self.__yfilter_ena = False
1614 1613
1615 1614 def getSubplots(self):
1616 1615
1617 1616 ncol = 3
1618 1617 nrow = int(numpy.ceil(self.nplots/3.0))
1619 1618
1620 1619 return nrow, ncol
1621 1620
1622 1621 def setup(self, id, nplots, wintitle, show=True):
1623 1622
1624 1623 self.nplots = nplots
1625 1624
1626 1625 ncolspan = 1
1627 1626 colspan = 1
1628 1627
1629 1628 self.createFigure(id = id,
1630 1629 wintitle = wintitle,
1631 1630 widthplot = self.WIDTH + self.WIDTHPROF,
1632 1631 heightplot = self.HEIGHT + self.HEIGHTPROF,
1633 1632 show=show)
1634 1633
1635 1634 nrow, ncol = self.getSubplots()
1636 1635
1637 1636 counter = 0
1638 1637 for y in range(nrow):
1639 1638 for x in range(ncol):
1640 1639
1641 1640 if counter >= self.nplots:
1642 1641 break
1643 1642
1644 1643 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1645 1644
1646 1645 counter += 1
1647 1646
1648 1647 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1649 1648 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1650 1649 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1651 1650 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1652 1651 server=None, folder=None, username=None, password=None,
1653 1652 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1654 1653 xaxis="frequency"):
1655 1654
1656 1655 """
1657 1656
1658 1657 Input:
1659 1658 dataOut :
1660 1659 id :
1661 1660 wintitle :
1662 1661 channelList :
1663 1662 showProfile :
1664 1663 xmin : None,
1665 1664 xmax : None,
1666 1665 ymin : None,
1667 1666 ymax : None,
1668 1667 zmin : None,
1669 1668 zmax : None
1670 1669 """
1671 1670 #SEPARAR EN DOS PLOTS
1672 1671 nParam = dataOut.data_param.shape[1] - 3
1673 1672
1674 1673 utctime = dataOut.data_param[0,0]
1675 1674 tmet = dataOut.data_param[:,1].astype(int)
1676 1675 hmet = dataOut.data_param[:,2].astype(int)
1677 1676
1678 1677 x = dataOut.abscissaList
1679 1678 y = dataOut.heightList
1680 1679
1681 1680 z = numpy.zeros((nParam, y.size, x.size - 1))
1682 1681 z[:,:] = numpy.nan
1683 1682 z[:,hmet,tmet] = dataOut.data_param[:,3:].T
1684 1683 z[0,:,:] = 10*numpy.log10(z[0,:,:])
1685 1684
1686 1685 xlabel = "Time (s)"
1687 1686 ylabel = "Range (km)"
1688 1687
1689 1688 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1690 1689
1691 1690 if not self.isConfig:
1692 1691
1693 1692 nplots = nParam
1694 1693
1695 1694 self.setup(id=id,
1696 1695 nplots=nplots,
1697 1696 wintitle=wintitle,
1698 1697 show=show)
1699 1698
1700 1699 if xmin is None: xmin = numpy.nanmin(x)
1701 1700 if xmax is None: xmax = numpy.nanmax(x)
1702 1701 if ymin is None: ymin = numpy.nanmin(y)
1703 1702 if ymax is None: ymax = numpy.nanmax(y)
1704 1703 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1705 1704 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1706 1705 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1707 1706 if vmin is None: vmin = -vmax
1708 1707 if wmin is None: wmin = 0
1709 1708 if wmax is None: wmax = 50
1710 1709
1711 1710 pairsList = dataOut.groupList
1712 1711 self.nPairs = len(dataOut.groupList)
1713 1712
1714 1713 zminList = [SNRmin, vmin, cmin] + [pmin]*self.nPairs
1715 1714 zmaxList = [SNRmax, vmax, cmax] + [pmax]*self.nPairs
1716 1715 titleList = ["SNR","Radial Velocity","Coherence"]
1717 1716 cmapList = ["jet","RdBu_r","jet"]
1718 1717
1719 1718 for i in range(self.nPairs):
1720 1719 strAux1 = "Phase Difference "+ str(pairsList[i][0]) + str(pairsList[i][1])
1721 1720 titleList = titleList + [strAux1]
1722 1721 cmapList = cmapList + ["RdBu_r"]
1723 1722
1724 1723 self.zminList = zminList
1725 1724 self.zmaxList = zmaxList
1726 1725 self.cmapList = cmapList
1727 1726 self.titleList = titleList
1728 1727
1729 1728 self.FTP_WEI = ftp_wei
1730 1729 self.EXP_CODE = exp_code
1731 1730 self.SUB_EXP_CODE = sub_exp_code
1732 1731 self.PLOT_POS = plot_pos
1733 1732
1734 1733 self.isConfig = True
1735 1734
1736 1735 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1737 1736
1738 1737 for i in range(nParam):
1739 1738 title = self.titleList[i] + ": " +str_datetime
1740 1739 axes = self.axesList[i]
1741 1740 axes.pcolor(x, y, z[i,:].T,
1742 1741 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1743 1742 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1744 1743 self.draw()
1745 1744
1746 1745 if figfile == None:
1747 1746 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1748 1747 name = str_datetime
1749 1748 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1750 1749 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1751 1750 figfile = self.getFilename(name)
1752 1751
1753 1752 self.save(figpath=figpath,
1754 1753 figfile=figfile,
1755 1754 save=save,
1756 1755 ftp=ftp,
1757 1756 wr_period=wr_period,
1758 1757 thisDatetime=thisDatetime)
1759 1758
1760 1759
1761 1760 class NSMeteorDetection2Plot(Figure):
1762 1761
1763 1762 isConfig = None
1764 1763 __nsubplots = None
1765 1764
1766 1765 WIDTHPROF = None
1767 1766 HEIGHTPROF = None
1768 1767 PREFIX = 'nsm'
1769 1768
1770 1769 zminList = None
1771 1770 zmaxList = None
1772 1771 cmapList = None
1773 1772 titleList = None
1774 1773 nPairs = None
1775 1774 nChannels = None
1776 1775 nParam = None
1777 1776
1778 1777 def __init__(self, **kwargs):
1779 1778 Figure.__init__(self, **kwargs)
1780 1779 self.isConfig = False
1781 1780 self.__nsubplots = 1
1782 1781
1783 1782 self.WIDTH = 750
1784 1783 self.HEIGHT = 250
1785 1784 self.WIDTHPROF = 120
1786 1785 self.HEIGHTPROF = 0
1787 1786 self.counter_imagwr = 0
1788 1787
1789 1788 self.PLOT_CODE = SPEC_CODE
1790 1789
1791 1790 self.FTP_WEI = None
1792 1791 self.EXP_CODE = None
1793 1792 self.SUB_EXP_CODE = None
1794 1793 self.PLOT_POS = None
1795 1794
1796 1795 self.__xfilter_ena = False
1797 1796 self.__yfilter_ena = False
1798 1797
1799 1798 def getSubplots(self):
1800 1799
1801 1800 ncol = 3
1802 1801 nrow = int(numpy.ceil(self.nplots/3.0))
1803 1802
1804 1803 return nrow, ncol
1805 1804
1806 1805 def setup(self, id, nplots, wintitle, show=True):
1807 1806
1808 1807 self.nplots = nplots
1809 1808
1810 1809 ncolspan = 1
1811 1810 colspan = 1
1812 1811
1813 1812 self.createFigure(id = id,
1814 1813 wintitle = wintitle,
1815 1814 widthplot = self.WIDTH + self.WIDTHPROF,
1816 1815 heightplot = self.HEIGHT + self.HEIGHTPROF,
1817 1816 show=show)
1818 1817
1819 1818 nrow, ncol = self.getSubplots()
1820 1819
1821 1820 counter = 0
1822 1821 for y in range(nrow):
1823 1822 for x in range(ncol):
1824 1823
1825 1824 if counter >= self.nplots:
1826 1825 break
1827 1826
1828 1827 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1829 1828
1830 1829 counter += 1
1831 1830
1832 1831 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1833 1832 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1834 1833 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1835 1834 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1836 1835 server=None, folder=None, username=None, password=None,
1837 1836 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1838 1837 xaxis="frequency"):
1839 1838
1840 1839 """
1841 1840
1842 1841 Input:
1843 1842 dataOut :
1844 1843 id :
1845 1844 wintitle :
1846 1845 channelList :
1847 1846 showProfile :
1848 1847 xmin : None,
1849 1848 xmax : None,
1850 1849 ymin : None,
1851 1850 ymax : None,
1852 1851 zmin : None,
1853 1852 zmax : None
1854 1853 """
1855 1854 #Rebuild matrix
1856 1855 utctime = dataOut.data_param[0,0]
1857 1856 cmet = dataOut.data_param[:,1].astype(int)
1858 1857 tmet = dataOut.data_param[:,2].astype(int)
1859 1858 hmet = dataOut.data_param[:,3].astype(int)
1860 1859
1861 1860 nParam = 3
1862 1861 nChan = len(dataOut.groupList)
1863 1862 x = dataOut.abscissaList
1864 1863 y = dataOut.heightList
1865 1864
1866 1865 z = numpy.full((nChan, nParam, y.size, x.size - 1),numpy.nan)
1867 1866 z[cmet,:,hmet,tmet] = dataOut.data_param[:,4:]
1868 1867 z[:,0,:,:] = 10*numpy.log10(z[:,0,:,:]) #logarithmic scale
1869 1868 z = numpy.reshape(z, (nChan*nParam, y.size, x.size-1))
1870 1869
1871 1870 xlabel = "Time (s)"
1872 1871 ylabel = "Range (km)"
1873 1872
1874 1873 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1875 1874
1876 1875 if not self.isConfig:
1877 1876
1878 1877 nplots = nParam*nChan
1879 1878
1880 1879 self.setup(id=id,
1881 1880 nplots=nplots,
1882 1881 wintitle=wintitle,
1883 1882 show=show)
1884 1883
1885 1884 if xmin is None: xmin = numpy.nanmin(x)
1886 1885 if xmax is None: xmax = numpy.nanmax(x)
1887 1886 if ymin is None: ymin = numpy.nanmin(y)
1888 1887 if ymax is None: ymax = numpy.nanmax(y)
1889 1888 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1890 1889 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1891 1890 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1892 1891 if vmin is None: vmin = -vmax
1893 1892 if wmin is None: wmin = 0
1894 1893 if wmax is None: wmax = 50
1895 1894
1896 1895 self.nChannels = nChan
1897 1896
1898 1897 zminList = []
1899 1898 zmaxList = []
1900 1899 titleList = []
1901 1900 cmapList = []
1902 1901 for i in range(self.nChannels):
1903 1902 strAux1 = "SNR Channel "+ str(i)
1904 1903 strAux2 = "Radial Velocity Channel "+ str(i)
1905 1904 strAux3 = "Spectral Width Channel "+ str(i)
1906 1905
1907 1906 titleList = titleList + [strAux1,strAux2,strAux3]
1908 1907 cmapList = cmapList + ["jet","RdBu_r","jet"]
1909 1908 zminList = zminList + [SNRmin,vmin,wmin]
1910 1909 zmaxList = zmaxList + [SNRmax,vmax,wmax]
1911 1910
1912 1911 self.zminList = zminList
1913 1912 self.zmaxList = zmaxList
1914 1913 self.cmapList = cmapList
1915 1914 self.titleList = titleList
1916 1915
1917 1916 self.FTP_WEI = ftp_wei
1918 1917 self.EXP_CODE = exp_code
1919 1918 self.SUB_EXP_CODE = sub_exp_code
1920 1919 self.PLOT_POS = plot_pos
1921 1920
1922 1921 self.isConfig = True
1923 1922
1924 1923 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1925 1924
1926 1925 for i in range(self.nplots):
1927 1926 title = self.titleList[i] + ": " +str_datetime
1928 1927 axes = self.axesList[i]
1929 1928 axes.pcolor(x, y, z[i,:].T,
1930 1929 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1931 1930 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1932 1931 self.draw()
1933 1932
1934 1933 if figfile == None:
1935 1934 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1936 1935 name = str_datetime
1937 1936 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1938 1937 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1939 1938 figfile = self.getFilename(name)
1940 1939
1941 1940 self.save(figpath=figpath,
1942 1941 figfile=figfile,
1943 1942 save=save,
1944 1943 ftp=ftp,
1945 1944 wr_period=wr_period,
1946 1945 thisDatetime=thisDatetime)
@@ -1,1743 +1,1750
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 time, datetime
13 13 #import h5py
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 class JRODataReader(JRODataIO):
540 540
541 541
542 542 online = 0
543 543
544 544 realtime = 0
545 545
546 546 nReadBlocks = 0
547 547
548 548 delay = 10 #number of seconds waiting a new file
549 549
550 550 nTries = 3 #quantity tries
551 551
552 552 nFiles = 3 #number of files for searching
553 553
554 554 path = None
555 555
556 556 foldercounter = 0
557 557
558 558 flagNoMoreFiles = 0
559 559
560 560 datetimeList = []
561 561
562 562 __isFirstTimeOnline = 1
563 563
564 564 __printInfo = True
565 565
566 566 profileIndex = None
567 567
568 568 nTxs = 1
569 569
570 570 txIndex = None
571 571
572 572 #Added--------------------
573 573
574 574 selBlocksize = None
575 575
576 576 selBlocktime = None
577 577
578 578
579 579 def __init__(self):
580 580
581 581 """
582 582 This class is used to find data files
583 583
584 584 Example:
585 585 reader = JRODataReader()
586 586 fileList = reader.findDataFiles()
587 587
588 588 """
589 589 pass
590 590
591 591
592 592 def createObjByDefault(self):
593 593 """
594 594
595 595 """
596 596 raise NotImplementedError
597 597
598 598 def getBlockDimension(self):
599 599
600 600 raise NotImplementedError
601 601
602 602 def __searchFilesOffLine(self,
603 603 path,
604 604 startDate=None,
605 605 endDate=None,
606 606 startTime=datetime.time(0,0,0),
607 607 endTime=datetime.time(23,59,59),
608 608 set=None,
609 609 expLabel='',
610 610 ext='.r',
611 611 queue=None,
612 612 cursor=None,
613 613 skip=None,
614 614 walk=True):
615 615
616 616 self.filenameList = []
617 617 self.datetimeList = []
618 618
619 619 pathList = []
620 620
621 621 dateList, pathList = self.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True)
622 622
623 623 if dateList == []:
624 624 # print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
625 625 return None, None
626 626
627 627 if len(dateList) > 1:
628 628 print "[Reading] Data found for date range [%s - %s]: total days = %d" %(startDate, endDate, len(dateList))
629 629 else:
630 630 print "[Reading] Data found for date range [%s - %s]: date = %s" %(startDate, endDate, dateList[0])
631 631
632 632 filenameList = []
633 633 datetimeList = []
634 634
635 635 for thisPath in pathList:
636 636 # thisPath = pathList[pathDict[file]]
637 637
638 638 fileList = glob.glob1(thisPath, "*%s" %ext)
639 639 fileList.sort()
640 640
641 641 skippedFileList = []
642 642
643 643 if cursor is not None and skip is not None:
644 644 # if cursor*skip > len(fileList):
645 645 if skip == 0:
646 646 if queue is not None:
647 647 queue.put(len(fileList))
648 648 skippedFileList = []
649 649 else:
650 650 skippedFileList = fileList[cursor*skip: cursor*skip + skip]
651 651
652 652 else:
653 653 skippedFileList = fileList
654 654
655 655 for file in skippedFileList:
656 656
657 657 filename = os.path.join(thisPath,file)
658 658
659 659 if not isFileInDateRange(filename, startDate, endDate):
660 660 continue
661 661
662 662 thisDatetime = isFileInTimeRange(filename, startDate, endDate, startTime, endTime)
663 663
664 664 if not(thisDatetime):
665 665 continue
666 666
667 667 filenameList.append(filename)
668 668 datetimeList.append(thisDatetime)
669 669
670 670 if not(filenameList):
671 671 print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" %(startTime, endTime, ext, path)
672 672 return None, None
673 673
674 674 print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime)
675 675 print
676 676
677 677 for i in range(len(filenameList)):
678 678 print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
679 679
680 680 self.filenameList = filenameList
681 681 self.datetimeList = datetimeList
682 682
683 683 return pathList, filenameList
684 684
685 685 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
686 686
687 687 """
688 688 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
689 689 devuelve el archivo encontrado ademas de otros datos.
690 690
691 691 Input:
692 692 path : carpeta donde estan contenidos los files que contiene data
693 693
694 694 expLabel : Nombre del subexperimento (subfolder)
695 695
696 696 ext : extension de los files
697 697
698 698 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
699 699
700 700 Return:
701 701 directory : eL directorio donde esta el file encontrado
702 702 filename : el ultimo file de una determinada carpeta
703 703 year : el anho
704 704 doy : el numero de dia del anho
705 705 set : el set del archivo
706 706
707 707
708 708 """
709 709 if not os.path.isdir(path):
710 710 return None, None, None, None, None, None
711 711
712 712 dirList = []
713 713
714 714 if not walk:
715 715 fullpath = path
716 716 foldercounter = 0
717 717 else:
718 718 #Filtra solo los directorios
719 719 for thisPath in os.listdir(path):
720 720 if not os.path.isdir(os.path.join(path,thisPath)):
721 721 continue
722 722 if not isRadarFolder(thisPath):
723 723 continue
724 724
725 725 dirList.append(thisPath)
726 726
727 727 if not(dirList):
728 728 return None, None, None, None, None, None
729 729
730 730 dirList = sorted( dirList, key=str.lower )
731 731
732 732 doypath = dirList[-1]
733 733 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
734 734 fullpath = os.path.join(path, doypath, expLabel)
735 735
736 736
737 737 print "[Reading] %s folder was found: " %(fullpath )
738 738
739 739 if set == None:
740 740 filename = getlastFileFromPath(fullpath, ext)
741 741 else:
742 742 filename = getFileFromSet(fullpath, ext, set)
743 743
744 744 if not(filename):
745 745 return None, None, None, None, None, None
746 746
747 747 print "[Reading] %s file was found" %(filename)
748 748
749 749 if not(self.__verifyFile(os.path.join(fullpath, filename))):
750 750 return None, None, None, None, None, None
751 751
752 752 year = int( filename[1:5] )
753 753 doy = int( filename[5:8] )
754 754 set = int( filename[8:11] )
755 755
756 756 return fullpath, foldercounter, filename, year, doy, set
757 757
758 758 def __setNextFileOffline(self):
759 759
760 760 idFile = self.fileIndex
761 761
762 762 while (True):
763 763 idFile += 1
764 764 if not(idFile < len(self.filenameList)):
765 765 self.flagNoMoreFiles = 1
766 766 # print "[Reading] No more Files"
767 767 return 0
768 768
769 769 filename = self.filenameList[idFile]
770 770
771 771 if not(self.__verifyFile(filename)):
772 772 continue
773 773
774 774 fileSize = os.path.getsize(filename)
775 775 fp = open(filename,'rb')
776 776 break
777 777
778 778 self.flagIsNewFile = 1
779 779 self.fileIndex = idFile
780 780 self.filename = filename
781 781 self.fileSize = fileSize
782 782 self.fp = fp
783 783
784 784 # print "[Reading] Setting the file: %s"%self.filename
785 785
786 786 return 1
787 787
788 788 def __setNextFileOnline(self):
789 789 """
790 790 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
791 791 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
792 792 siguientes.
793 793
794 794 Affected:
795 795 self.flagIsNewFile
796 796 self.filename
797 797 self.fileSize
798 798 self.fp
799 799 self.set
800 800 self.flagNoMoreFiles
801 801
802 802 Return:
803 803 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
804 804 1 : si el file fue abierto con exito y esta listo a ser leido
805 805
806 806 Excepciones:
807 807 Si un determinado file no puede ser abierto
808 808 """
809 809 nFiles = 0
810 810 fileOk_flag = False
811 811 firstTime_flag = True
812 812
813 813 self.set += 1
814 814
815 815 if self.set > 999:
816 816 self.set = 0
817 817 self.foldercounter += 1
818 818
819 819 #busca el 1er file disponible
820 820 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
821 821 if fullfilename:
822 822 if self.__verifyFile(fullfilename, False):
823 823 fileOk_flag = True
824 824
825 825 #si no encuentra un file entonces espera y vuelve a buscar
826 826 if not(fileOk_flag):
827 827 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
828 828
829 829 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
830 830 tries = self.nTries
831 831 else:
832 832 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
833 833
834 834 for nTries in range( tries ):
835 835 if firstTime_flag:
836 836 print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
837 837 sleep( self.delay )
838 838 else:
839 839 print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
840 840
841 841 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
842 842 if fullfilename:
843 843 if self.__verifyFile(fullfilename):
844 844 fileOk_flag = True
845 845 break
846 846
847 847 if fileOk_flag:
848 848 break
849 849
850 850 firstTime_flag = False
851 851
852 852 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
853 853 self.set += 1
854 854
855 855 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
856 856 self.set = 0
857 857 self.doy += 1
858 858 self.foldercounter = 0
859 859
860 860 if fileOk_flag:
861 861 self.fileSize = os.path.getsize( fullfilename )
862 862 self.filename = fullfilename
863 863 self.flagIsNewFile = 1
864 864 if self.fp != None: self.fp.close()
865 865 self.fp = open(fullfilename, 'rb')
866 866 self.flagNoMoreFiles = 0
867 867 # print '[Reading] Setting the file: %s' % fullfilename
868 868 else:
869 869 self.fileSize = 0
870 870 self.filename = None
871 871 self.flagIsNewFile = 0
872 872 self.fp = None
873 873 self.flagNoMoreFiles = 1
874 874 # print '[Reading] No more files to read'
875 875
876 876 return fileOk_flag
877 877
878 878 def setNextFile(self):
879 879 if self.fp != None:
880 880 self.fp.close()
881 881
882 882 if self.online:
883 883 newFile = self.__setNextFileOnline()
884 884 else:
885 885 newFile = self.__setNextFileOffline()
886 886
887 887 if not(newFile):
888 888 print '[Reading] No more files to read'
889 889 return 0
890 890
891 print '[Reading] Setting the file: %s' % self.filename
891 if self.verbose:
892 print '[Reading] Setting the file: %s' % self.filename
892 893
893 894 self.__readFirstHeader()
894 895 self.nReadBlocks = 0
895 896 return 1
896 897
897 898 def __waitNewBlock(self):
898 899 """
899 900 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
900 901
901 902 Si el modo de lectura es OffLine siempre retorn 0
902 903 """
903 904 if not self.online:
904 905 return 0
905 906
906 907 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
907 908 return 0
908 909
909 910 currentPointer = self.fp.tell()
910 911
911 912 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
912 913
913 914 for nTries in range( self.nTries ):
914 915
915 916 self.fp.close()
916 917 self.fp = open( self.filename, 'rb' )
917 918 self.fp.seek( currentPointer )
918 919
919 920 self.fileSize = os.path.getsize( self.filename )
920 921 currentSize = self.fileSize - currentPointer
921 922
922 923 if ( currentSize >= neededSize ):
923 924 self.basicHeaderObj.read(self.fp)
924 925 return 1
925 926
926 927 if self.fileSize == self.fileSizeByHeader:
927 928 # self.flagEoF = True
928 929 return 0
929 930
930 931 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
931 932 sleep( self.delay )
932 933
933 934
934 935 return 0
935 936
936 937 def waitDataBlock(self,pointer_location):
937 938
938 939 currentPointer = pointer_location
939 940
940 941 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
941 942
942 943 for nTries in range( self.nTries ):
943 944 self.fp.close()
944 945 self.fp = open( self.filename, 'rb' )
945 946 self.fp.seek( currentPointer )
946 947
947 948 self.fileSize = os.path.getsize( self.filename )
948 949 currentSize = self.fileSize - currentPointer
949 950
950 951 if ( currentSize >= neededSize ):
951 952 return 1
952 953
953 954 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
954 955 sleep( self.delay )
955 956
956 957 return 0
957 958
958 959 def __jumpToLastBlock(self):
959 960
960 961 if not(self.__isFirstTimeOnline):
961 962 return
962 963
963 964 csize = self.fileSize - self.fp.tell()
964 965 blocksize = self.processingHeaderObj.blockSize
965 966
966 967 #salta el primer bloque de datos
967 968 if csize > self.processingHeaderObj.blockSize:
968 969 self.fp.seek(self.fp.tell() + blocksize)
969 970 else:
970 971 return
971 972
972 973 csize = self.fileSize - self.fp.tell()
973 974 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
974 975 while True:
975 976
976 977 if self.fp.tell()<self.fileSize:
977 978 self.fp.seek(self.fp.tell() + neededsize)
978 979 else:
979 980 self.fp.seek(self.fp.tell() - neededsize)
980 981 break
981 982
982 983 # csize = self.fileSize - self.fp.tell()
983 984 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
984 985 # factor = int(csize/neededsize)
985 986 # if factor > 0:
986 987 # self.fp.seek(self.fp.tell() + factor*neededsize)
987 988
988 989 self.flagIsNewFile = 0
989 990 self.__isFirstTimeOnline = 0
990 991
991 992 def __setNewBlock(self):
992 993
993 994 if self.fp == None:
994 995 return 0
995 996
996 997 # if self.online:
997 998 # self.__jumpToLastBlock()
998 999
999 1000 if self.flagIsNewFile:
1000 1001 self.lastUTTime = self.basicHeaderObj.utc
1001 1002 return 1
1002 1003
1003 1004 if self.realtime:
1004 1005 self.flagDiscontinuousBlock = 1
1005 1006 if not(self.setNextFile()):
1006 1007 return 0
1007 1008 else:
1008 1009 return 1
1009 1010
1010 1011 currentSize = self.fileSize - self.fp.tell()
1011 1012 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1012 1013
1013 1014 if (currentSize >= neededSize):
1014 1015 self.basicHeaderObj.read(self.fp)
1015 1016 self.lastUTTime = self.basicHeaderObj.utc
1016 1017 return 1
1017 1018
1018 1019 if self.__waitNewBlock():
1019 1020 self.lastUTTime = self.basicHeaderObj.utc
1020 1021 return 1
1021 1022
1022 1023 if not(self.setNextFile()):
1023 1024 return 0
1024 1025
1025 1026 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
1026 1027 self.lastUTTime = self.basicHeaderObj.utc
1027 1028
1028 1029 self.flagDiscontinuousBlock = 0
1029 1030
1030 1031 if deltaTime > self.maxTimeStep:
1031 1032 self.flagDiscontinuousBlock = 1
1032 1033
1033 1034 return 1
1034 1035
1035 1036 def readNextBlock(self):
1036 1037
1037 1038 #Skip block out of startTime and endTime
1038 1039 while True:
1039 1040 if not(self.__setNewBlock()):
1040 1041 return 0
1041 1042
1042 1043 if not(self.readBlock()):
1043 1044 return 0
1044 1045
1045 1046 self.getBasicHeader()
1046 1047
1047 1048 if not isTimeInRange(self.dataOut.datatime.time(), self.startTime, self.endTime):
1048 1049
1049 1050 print "[Reading] Block No. %d/%d -> %s [Skipping]" %(self.nReadBlocks,
1050 1051 self.processingHeaderObj.dataBlocksPerFile,
1051 1052 self.dataOut.datatime.ctime())
1052 1053 continue
1053 1054
1054 1055 break
1055 1056
1056 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1057 self.processingHeaderObj.dataBlocksPerFile,
1058 self.dataOut.datatime.ctime())
1057 if self.verbose:
1058 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1059 self.processingHeaderObj.dataBlocksPerFile,
1060 self.dataOut.datatime.ctime())
1059 1061 return 1
1060 1062
1061 1063 def __readFirstHeader(self):
1062 1064
1063 1065 self.basicHeaderObj.read(self.fp)
1064 1066 self.systemHeaderObj.read(self.fp)
1065 1067 self.radarControllerHeaderObj.read(self.fp)
1066 1068 self.processingHeaderObj.read(self.fp)
1067 1069
1068 1070 self.firstHeaderSize = self.basicHeaderObj.size
1069 1071
1070 1072 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
1071 1073 if datatype == 0:
1072 1074 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
1073 1075 elif datatype == 1:
1074 1076 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
1075 1077 elif datatype == 2:
1076 1078 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
1077 1079 elif datatype == 3:
1078 1080 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
1079 1081 elif datatype == 4:
1080 1082 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
1081 1083 elif datatype == 5:
1082 1084 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
1083 1085 else:
1084 1086 raise ValueError, 'Data type was not defined'
1085 1087
1086 1088 self.dtype = datatype_str
1087 1089 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
1088 1090 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
1089 1091 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
1090 1092 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
1091 1093 self.getBlockDimension()
1092 1094
1093 1095 def __verifyFile(self, filename, msgFlag=True):
1094 1096
1095 1097 msg = None
1096 1098
1097 1099 try:
1098 1100 fp = open(filename, 'rb')
1099 1101 except IOError:
1100 1102
1101 1103 if msgFlag:
1102 1104 print "[Reading] File %s can't be opened" % (filename)
1103 1105
1104 1106 return False
1105 1107
1106 1108 currentPosition = fp.tell()
1107 1109 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
1108 1110
1109 1111 if neededSize == 0:
1110 1112 basicHeaderObj = BasicHeader(LOCALTIME)
1111 1113 systemHeaderObj = SystemHeader()
1112 1114 radarControllerHeaderObj = RadarControllerHeader()
1113 1115 processingHeaderObj = ProcessingHeader()
1114 1116
1115 1117 if not( basicHeaderObj.read(fp) ):
1116 1118 fp.close()
1117 1119 return False
1118 1120
1119 1121 if not( systemHeaderObj.read(fp) ):
1120 1122 fp.close()
1121 1123 return False
1122 1124
1123 1125 if not( radarControllerHeaderObj.read(fp) ):
1124 1126 fp.close()
1125 1127 return False
1126 1128
1127 1129 if not( processingHeaderObj.read(fp) ):
1128 1130 fp.close()
1129 1131 return False
1130 1132
1131 1133 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
1132 1134 else:
1133 1135 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
1134 1136
1135 1137 fp.close()
1136 1138
1137 1139 fileSize = os.path.getsize(filename)
1138 1140 currentSize = fileSize - currentPosition
1139 1141
1140 1142 if currentSize < neededSize:
1141 1143 if msgFlag and (msg != None):
1142 1144 print msg
1143 1145 return False
1144 1146
1145 1147 return True
1146 1148
1147 1149 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1148 1150
1149 1151 path_empty = True
1150 1152
1151 1153 dateList = []
1152 1154 pathList = []
1153 1155
1154 1156 multi_path = path.split(',')
1155 1157
1156 1158 if not walk:
1157 1159
1158 1160 for single_path in multi_path:
1159 1161
1160 1162 if not os.path.isdir(single_path):
1161 1163 continue
1162 1164
1163 1165 fileList = glob.glob1(single_path, "*"+ext)
1164 1166
1165 1167 if not fileList:
1166 1168 continue
1167 1169
1168 1170 path_empty = False
1169 1171
1170 1172 fileList.sort()
1171 1173
1172 1174 for thisFile in fileList:
1173 1175
1174 1176 if not os.path.isfile(os.path.join(single_path, thisFile)):
1175 1177 continue
1176 1178
1177 1179 if not isRadarFile(thisFile):
1178 1180 continue
1179 1181
1180 1182 if not isFileInDateRange(thisFile, startDate, endDate):
1181 1183 continue
1182 1184
1183 1185 thisDate = getDateFromRadarFile(thisFile)
1184 1186
1185 1187 if thisDate in dateList:
1186 1188 continue
1187 1189
1188 1190 dateList.append(thisDate)
1189 1191 pathList.append(single_path)
1190 1192
1191 1193 else:
1192 1194 for single_path in multi_path:
1193 1195
1194 1196 if not os.path.isdir(single_path):
1195 1197 continue
1196 1198
1197 1199 dirList = []
1198 1200
1199 1201 for thisPath in os.listdir(single_path):
1200 1202
1201 1203 if not os.path.isdir(os.path.join(single_path,thisPath)):
1202 1204 continue
1203 1205
1204 1206 if not isRadarFolder(thisPath):
1205 1207 continue
1206 1208
1207 1209 if not isFolderInDateRange(thisPath, startDate, endDate):
1208 1210 continue
1209 1211
1210 1212 dirList.append(thisPath)
1211 1213
1212 1214 if not dirList:
1213 1215 continue
1214 1216
1215 1217 dirList.sort()
1216 1218
1217 1219 for thisDir in dirList:
1218 1220
1219 1221 datapath = os.path.join(single_path, thisDir, expLabel)
1220 1222 fileList = glob.glob1(datapath, "*"+ext)
1221 1223
1222 1224 if not fileList:
1223 1225 continue
1224 1226
1225 1227 path_empty = False
1226 1228
1227 1229 thisDate = getDateFromRadarFolder(thisDir)
1228 1230
1229 1231 pathList.append(datapath)
1230 1232 dateList.append(thisDate)
1231 1233
1232 1234 dateList.sort()
1233 1235
1234 1236 if walk:
1235 1237 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1236 1238 else:
1237 1239 pattern_path = multi_path[0]
1238 1240
1239 1241 if path_empty:
1240 1242 print "[Reading] No *%s files in %s for %s to %s" %(ext, pattern_path, startDate, endDate)
1241 1243 else:
1242 1244 if not dateList:
1243 1245 print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path)
1244 1246
1245 1247 if include_path:
1246 1248 return dateList, pathList
1247 1249
1248 1250 return dateList
1249 1251
1250 1252 def setup(self,
1251 1253 path=None,
1252 1254 startDate=None,
1253 1255 endDate=None,
1254 1256 startTime=datetime.time(0,0,0),
1255 1257 endTime=datetime.time(23,59,59),
1256 1258 set=None,
1257 1259 expLabel = "",
1258 1260 ext = None,
1259 1261 online = False,
1260 1262 delay = 60,
1261 1263 walk = True,
1262 1264 getblock = False,
1263 1265 nTxs = 1,
1264 1266 realtime=False,
1265 1267 blocksize=None,
1266 1268 blocktime=None,
1267 1269 queue=None,
1268 1270 skip=None,
1269 cursor=None):
1271 cursor=None,
1272 warnings=True,
1273 verbose=True):
1270 1274
1271 1275 if path == None:
1272 1276 raise ValueError, "[Reading] The path is not valid"
1273 1277
1274 1278 if ext == None:
1275 1279 ext = self.ext
1276 1280
1277 1281 if online:
1278 1282 print "[Reading] Searching files in online mode..."
1279 1283
1280 1284 for nTries in range( self.nTries ):
1281 1285 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1282 1286
1283 1287 if fullpath:
1284 1288 break
1285 1289
1286 1290 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
1287 1291 sleep( self.delay )
1288 1292
1289 1293 if not(fullpath):
1290 1294 print "[Reading] There 'isn't any valid file in %s" % path
1291 1295 return
1292 1296
1293 1297 self.year = year
1294 1298 self.doy = doy
1295 1299 self.set = set - 1
1296 1300 self.path = path
1297 1301 self.foldercounter = foldercounter
1298 1302 last_set = None
1299 1303
1300 1304 else:
1301 1305 print "[Reading] Searching files in offline mode ..."
1302 1306 pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1303 1307 startTime=startTime, endTime=endTime,
1304 1308 set=set, expLabel=expLabel, ext=ext,
1305 1309 walk=walk, cursor=cursor,
1306 1310 skip=skip, queue=queue)
1307 1311
1308 1312 if not(pathList):
1309 1313 # print "[Reading] No *%s files in %s (%s - %s)"%(ext, path,
1310 1314 # datetime.datetime.combine(startDate,startTime).ctime(),
1311 1315 # datetime.datetime.combine(endDate,endTime).ctime())
1312 1316
1313 1317 # sys.exit(-1)
1314 1318
1315 1319 self.fileIndex = -1
1316 1320 self.pathList = []
1317 1321 self.filenameList = []
1318 1322 return
1319 1323
1320 1324 self.fileIndex = -1
1321 1325 self.pathList = pathList
1322 1326 self.filenameList = filenameList
1323 1327 file_name = os.path.basename(filenameList[-1])
1324 1328 basename, ext = os.path.splitext(file_name)
1325 1329 last_set = int(basename[-3:])
1326 1330
1327 1331 self.online = online
1328 1332 self.realtime = realtime
1329 1333 self.delay = delay
1330 1334 ext = ext.lower()
1331 1335 self.ext = ext
1332 1336 self.getByBlock = getblock
1333 1337 self.nTxs = nTxs
1334 1338 self.startTime = startTime
1335 1339 self.endTime = endTime
1336 1340
1337 1341 #Added-----------------
1338 1342 self.selBlocksize = blocksize
1339 1343 self.selBlocktime = blocktime
1340 1344
1345 # Verbose-----------
1346 self.verbose = verbose
1347 self.warnings = warnings
1341 1348
1342 1349 if not(self.setNextFile()):
1343 1350 if (startDate!=None) and (endDate!=None):
1344 1351 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1345 1352 elif startDate != None:
1346 1353 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1347 1354 else:
1348 1355 print "[Reading] No files"
1349 1356
1350 1357 self.fileIndex = -1
1351 1358 self.pathList = []
1352 1359 self.filenameList = []
1353 1360 return
1354 1361
1355 1362 # self.getBasicHeader()
1356 1363
1357 1364 if last_set != None:
1358 1365 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1359 1366 return
1360 1367
1361 1368 def getBasicHeader(self):
1362 1369
1363 1370 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1364 1371
1365 1372 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1366 1373
1367 1374 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1368 1375
1369 1376 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1370 1377
1371 1378 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1372 1379
1373 1380 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1374 1381
1375 1382 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1376 1383
1377 1384 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1378 1385
1379 1386
1380 1387 def getFirstHeader(self):
1381 1388
1382 1389 raise NotImplementedError
1383 1390
1384 1391 def getData(self):
1385 1392
1386 1393 raise NotImplementedError
1387 1394
1388 1395 def hasNotDataInBuffer(self):
1389 1396
1390 1397 raise NotImplementedError
1391 1398
1392 1399 def readBlock(self):
1393 1400
1394 1401 raise NotImplementedError
1395 1402
1396 1403 def isEndProcess(self):
1397 1404
1398 1405 return self.flagNoMoreFiles
1399 1406
1400 1407 def printReadBlocks(self):
1401 1408
1402 1409 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1403 1410
1404 1411 def printTotalBlocks(self):
1405 1412
1406 1413 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1407 1414
1408 1415 def printNumberOfBlock(self):
1409 1416
1410 1417 if self.flagIsNewBlock:
1411 1418 print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1412 1419 self.processingHeaderObj.dataBlocksPerFile,
1413 1420 self.dataOut.datatime.ctime())
1414 1421
1415 1422 def printInfo(self):
1416 1423
1417 1424 if self.__printInfo == False:
1418 1425 return
1419 1426
1420 1427 self.basicHeaderObj.printInfo()
1421 1428 self.systemHeaderObj.printInfo()
1422 1429 self.radarControllerHeaderObj.printInfo()
1423 1430 self.processingHeaderObj.printInfo()
1424 1431
1425 1432 self.__printInfo = False
1426 1433
1427 1434
1428 1435 def run(self, **kwargs):
1429 1436
1430 1437 if not(self.isConfig):
1431 1438
1432 1439 # self.dataOut = dataOut
1433 1440 self.setup(**kwargs)
1434 1441 self.isConfig = True
1435 1442
1436 1443 self.getData()
1437 1444
1438 1445 class JRODataWriter(JRODataIO):
1439 1446
1440 1447 """
1441 1448 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1442 1449 de los datos siempre se realiza por bloques.
1443 1450 """
1444 1451
1445 1452 blockIndex = 0
1446 1453
1447 1454 path = None
1448 1455
1449 1456 setFile = None
1450 1457
1451 1458 profilesPerBlock = None
1452 1459
1453 1460 blocksPerFile = None
1454 1461
1455 1462 nWriteBlocks = 0
1456 1463
1457 1464 fileDate = None
1458 1465
1459 1466 def __init__(self, dataOut=None):
1460 1467 raise NotImplementedError
1461 1468
1462 1469
1463 1470 def hasAllDataInBuffer(self):
1464 1471 raise NotImplementedError
1465 1472
1466 1473
1467 1474 def setBlockDimension(self):
1468 1475 raise NotImplementedError
1469 1476
1470 1477
1471 1478 def writeBlock(self):
1472 1479 raise NotImplementedError
1473 1480
1474 1481
1475 1482 def putData(self):
1476 1483 raise NotImplementedError
1477 1484
1478 1485
1479 1486 def getProcessFlags(self):
1480 1487
1481 1488 processFlags = 0
1482 1489
1483 1490 dtype_index = get_dtype_index(self.dtype)
1484 1491 procflag_dtype = get_procflag_dtype(dtype_index)
1485 1492
1486 1493 processFlags += procflag_dtype
1487 1494
1488 1495 if self.dataOut.flagDecodeData:
1489 1496 processFlags += PROCFLAG.DECODE_DATA
1490 1497
1491 1498 if self.dataOut.flagDeflipData:
1492 1499 processFlags += PROCFLAG.DEFLIP_DATA
1493 1500
1494 1501 if self.dataOut.code is not None:
1495 1502 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1496 1503
1497 1504 if self.dataOut.nCohInt > 1:
1498 1505 processFlags += PROCFLAG.COHERENT_INTEGRATION
1499 1506
1500 1507 if self.dataOut.type == "Spectra":
1501 1508 if self.dataOut.nIncohInt > 1:
1502 1509 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1503 1510
1504 1511 if self.dataOut.data_dc is not None:
1505 1512 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1506 1513
1507 1514 if self.dataOut.flagShiftFFT:
1508 1515 processFlags += PROCFLAG.SHIFT_FFT_DATA
1509 1516
1510 1517 return processFlags
1511 1518
1512 1519 def setBasicHeader(self):
1513 1520
1514 1521 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1515 1522 self.basicHeaderObj.version = self.versionFile
1516 1523 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1517 1524
1518 1525 utc = numpy.floor(self.dataOut.utctime)
1519 1526 milisecond = (self.dataOut.utctime - utc)* 1000.0
1520 1527
1521 1528 self.basicHeaderObj.utc = utc
1522 1529 self.basicHeaderObj.miliSecond = milisecond
1523 1530 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1524 1531 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1525 1532 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1526 1533
1527 1534 def setFirstHeader(self):
1528 1535 """
1529 1536 Obtiene una copia del First Header
1530 1537
1531 1538 Affected:
1532 1539
1533 1540 self.basicHeaderObj
1534 1541 self.systemHeaderObj
1535 1542 self.radarControllerHeaderObj
1536 1543 self.processingHeaderObj self.
1537 1544
1538 1545 Return:
1539 1546 None
1540 1547 """
1541 1548
1542 1549 raise NotImplementedError
1543 1550
1544 1551 def __writeFirstHeader(self):
1545 1552 """
1546 1553 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1547 1554
1548 1555 Affected:
1549 1556 __dataType
1550 1557
1551 1558 Return:
1552 1559 None
1553 1560 """
1554 1561
1555 1562 # CALCULAR PARAMETROS
1556 1563
1557 1564 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1558 1565 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1559 1566
1560 1567 self.basicHeaderObj.write(self.fp)
1561 1568 self.systemHeaderObj.write(self.fp)
1562 1569 self.radarControllerHeaderObj.write(self.fp)
1563 1570 self.processingHeaderObj.write(self.fp)
1564 1571
1565 1572 def __setNewBlock(self):
1566 1573 """
1567 1574 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1568 1575
1569 1576 Return:
1570 1577 0 : si no pudo escribir nada
1571 1578 1 : Si escribio el Basic el First Header
1572 1579 """
1573 1580 if self.fp == None:
1574 1581 self.setNextFile()
1575 1582
1576 1583 if self.flagIsNewFile:
1577 1584 return 1
1578 1585
1579 1586 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1580 1587 self.basicHeaderObj.write(self.fp)
1581 1588 return 1
1582 1589
1583 1590 if not( self.setNextFile() ):
1584 1591 return 0
1585 1592
1586 1593 return 1
1587 1594
1588 1595
1589 1596 def writeNextBlock(self):
1590 1597 """
1591 1598 Selecciona el bloque siguiente de datos y los escribe en un file
1592 1599
1593 1600 Return:
1594 1601 0 : Si no hizo pudo escribir el bloque de datos
1595 1602 1 : Si no pudo escribir el bloque de datos
1596 1603 """
1597 1604 if not( self.__setNewBlock() ):
1598 1605 return 0
1599 1606
1600 1607 self.writeBlock()
1601 1608
1602 1609 print "[Writing] Block No. %d/%d" %(self.blockIndex,
1603 1610 self.processingHeaderObj.dataBlocksPerFile)
1604 1611
1605 1612 return 1
1606 1613
1607 1614 def setNextFile(self):
1608 1615 """
1609 1616 Determina el siguiente file que sera escrito
1610 1617
1611 1618 Affected:
1612 1619 self.filename
1613 1620 self.subfolder
1614 1621 self.fp
1615 1622 self.setFile
1616 1623 self.flagIsNewFile
1617 1624
1618 1625 Return:
1619 1626 0 : Si el archivo no puede ser escrito
1620 1627 1 : Si el archivo esta listo para ser escrito
1621 1628 """
1622 1629 ext = self.ext
1623 1630 path = self.path
1624 1631
1625 1632 if self.fp != None:
1626 1633 self.fp.close()
1627 1634
1628 1635 timeTuple = time.localtime( self.dataOut.utctime)
1629 1636 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1630 1637
1631 1638 fullpath = os.path.join( path, subfolder )
1632 1639 setFile = self.setFile
1633 1640
1634 1641 if not( os.path.exists(fullpath) ):
1635 1642 os.mkdir(fullpath)
1636 1643 setFile = -1 #inicializo mi contador de seteo
1637 1644 else:
1638 1645 filesList = os.listdir( fullpath )
1639 1646 if len( filesList ) > 0:
1640 1647 filesList = sorted( filesList, key=str.lower )
1641 1648 filen = filesList[-1]
1642 1649 # el filename debera tener el siguiente formato
1643 1650 # 0 1234 567 89A BCDE (hex)
1644 1651 # x YYYY DDD SSS .ext
1645 1652 if isNumber( filen[8:11] ):
1646 1653 setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1647 1654 else:
1648 1655 setFile = -1
1649 1656 else:
1650 1657 setFile = -1 #inicializo mi contador de seteo
1651 1658
1652 1659 setFile += 1
1653 1660
1654 1661 #If this is a new day it resets some values
1655 1662 if self.dataOut.datatime.date() > self.fileDate:
1656 1663 setFile = 0
1657 1664 self.nTotalBlocks = 0
1658 1665
1659 1666 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext )
1660 1667
1661 1668 filename = os.path.join( path, subfolder, filen )
1662 1669
1663 1670 fp = open( filename,'wb' )
1664 1671
1665 1672 self.blockIndex = 0
1666 1673
1667 1674 #guardando atributos
1668 1675 self.filename = filename
1669 1676 self.subfolder = subfolder
1670 1677 self.fp = fp
1671 1678 self.setFile = setFile
1672 1679 self.flagIsNewFile = 1
1673 1680 self.fileDate = self.dataOut.datatime.date()
1674 1681
1675 1682 self.setFirstHeader()
1676 1683
1677 1684 print '[Writing] Opening file: %s'%self.filename
1678 1685
1679 1686 self.__writeFirstHeader()
1680 1687
1681 1688 return 1
1682 1689
1683 1690 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1684 1691 """
1685 1692 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1686 1693
1687 1694 Inputs:
1688 1695 path : directory where data will be saved
1689 1696 profilesPerBlock : number of profiles per block
1690 1697 set : initial file set
1691 1698 datatype : An integer number that defines data type:
1692 1699 0 : int8 (1 byte)
1693 1700 1 : int16 (2 bytes)
1694 1701 2 : int32 (4 bytes)
1695 1702 3 : int64 (8 bytes)
1696 1703 4 : float32 (4 bytes)
1697 1704 5 : double64 (8 bytes)
1698 1705
1699 1706 Return:
1700 1707 0 : Si no realizo un buen seteo
1701 1708 1 : Si realizo un buen seteo
1702 1709 """
1703 1710
1704 1711 if ext == None:
1705 1712 ext = self.ext
1706 1713
1707 1714 self.ext = ext.lower()
1708 1715
1709 1716 self.path = path
1710 1717
1711 1718 if set is None:
1712 1719 self.setFile = -1
1713 1720 else:
1714 1721 self.setFile = set - 1
1715 1722
1716 1723 self.blocksPerFile = blocksPerFile
1717 1724
1718 1725 self.profilesPerBlock = profilesPerBlock
1719 1726
1720 1727 self.dataOut = dataOut
1721 1728 self.fileDate = self.dataOut.datatime.date()
1722 1729 #By default
1723 1730 self.dtype = self.dataOut.dtype
1724 1731
1725 1732 if datatype is not None:
1726 1733 self.dtype = get_numpy_dtype(datatype)
1727 1734
1728 1735 if not(self.setNextFile()):
1729 1736 print "[Writing] There isn't a next file"
1730 1737 return 0
1731 1738
1732 1739 self.setBlockDimension()
1733 1740
1734 1741 return 1
1735 1742
1736 1743 def run(self, dataOut, **kwargs):
1737 1744
1738 1745 if not(self.isConfig):
1739 1746
1740 1747 self.setup(dataOut, **kwargs)
1741 1748 self.isConfig = True
1742 1749
1743 1750 self.putData()
@@ -1,318 +1,349
1 1 '''
2 2
3 3 $Author: murco $
4 4 $Id: jroproc_base.py 1 2012-11-12 18:56:07Z murco $
5 5 '''
6 import inspect
7 from fuzzywuzzy import process
8
9 def checkKwargs(method, kwargs):
10 currentKwargs = kwargs
11 choices = inspect.getargspec(method).args
12 try:
13 choices.remove('self')
14 except Exception as e:
15 pass
16
17 try:
18 choices.remove('dataOut')
19 except Exception as e:
20 pass
21
22 for kwarg in kwargs:
23 fuzz = process.extractOne(kwarg, choices)
24 if fuzz is None:
25 continue
26 if fuzz[1] < 100:
27 raise Exception('\x1b[0;32;40mDid you mean {} instead of {} in {}? \x1b[0m'.
28 format(fuzz[0], kwarg, method.__self__.__class__.__name__))
6 29
7 30 class ProcessingUnit(object):
8 31
9 32 """
10 33 Esta es la clase base para el procesamiento de datos.
11 34
12 35 Contiene el metodo "call" para llamar operaciones. Las operaciones pueden ser:
13 36 - Metodos internos (callMethod)
14 37 - Objetos del tipo Operation (callObject). Antes de ser llamados, estos objetos
15 38 tienen que ser agreagados con el metodo "add".
16 39
17 40 """
18 41 # objeto de datos de entrada (Voltage, Spectra o Correlation)
19 42 dataIn = None
20 43 dataInList = []
21 44
22 45 # objeto de datos de entrada (Voltage, Spectra o Correlation)
23 46 dataOut = None
24 47
25 48 operations2RunDict = None
26 49
27 50 isConfig = False
28 51
29 52
30 53 def __init__(self, *args, **kwargs):
31 54
32 55 self.dataIn = None
33 56 self.dataInList = []
34 57
35 58 self.dataOut = None
36 59
37 60 self.operations2RunDict = {}
38 61 self.operationKwargs = {}
39 62
40 63 self.isConfig = False
41 64
42 65 self.args = args
43 66 self.kwargs = kwargs
67 checkKwargs(self.run, kwargs)
68
69 def getAllowedArgs(self):
70 return inspect.getargspec(self.run).args
44 71
45 72 def addOperationKwargs(self, objId, **kwargs):
46 73 '''
47 74 '''
48
75
49 76 self.operationKwargs[objId] = kwargs
50
51
77
78
52 79 def addOperation(self, opObj, objId):
53 80
54 81 """
55 82 Agrega un objeto del tipo "Operation" (opObj) a la lista de objetos "self.objectList" y retorna el
56 83 identificador asociado a este objeto.
57 84
58 85 Input:
59 86
60 87 object : objeto de la clase "Operation"
61 88
62 89 Return:
63 90
64 91 objId : identificador del objeto, necesario para ejecutar la operacion
65 92 """
66 93
67 94 self.operations2RunDict[objId] = opObj
68 95
69 96 return objId
70 97
71 98 def getOperationObj(self, objId):
72 99
73 100 if objId not in self.operations2RunDict.keys():
74 101 return None
75 102
76 103 return self.operations2RunDict[objId]
77 104
78 105 def operation(self, **kwargs):
79 106
80 107 """
81 108 Operacion directa sobre la data (dataOut.data). Es necesario actualizar los valores de los
82 109 atributos del objeto dataOut
83 110
84 111 Input:
85 112
86 113 **kwargs : Diccionario de argumentos de la funcion a ejecutar
87 114 """
88 115
89 116 raise NotImplementedError
90 117
91 118 def callMethod(self, name, opId):
92 119
93 120 """
94 121 Ejecuta el metodo con el nombre "name" y con argumentos **kwargs de la propia clase.
95 122
96 123 Input:
97 124 name : nombre del metodo a ejecutar
98 125
99 126 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
100 127
101 128 """
102 129
103 130 #Checking the inputs
104 131 if name == 'run':
105 132
106 133 if not self.checkInputs():
107 134 self.dataOut.flagNoData = True
108 135 return False
109 136 else:
110 137 #Si no es un metodo RUN la entrada es la misma dataOut (interna)
111 138 if self.dataOut is not None and self.dataOut.isEmpty():
112 139 return False
113 140
114 141 #Getting the pointer to method
115 142 methodToCall = getattr(self, name)
116 143
117 144 #Executing the self method
118 145
119 146 if hasattr(self, 'mp'):
120 if name=='run':
121 if self.mp is False:
147 if name=='run':
148 if self.mp is False:
122 149 self.mp = True
123 150 self.start()
124 151 else:
125 152 self.operationKwargs[opId]['parent'] = self.kwargs
126 methodToCall(**self.operationKwargs[opId])
153 methodToCall(**self.operationKwargs[opId])
127 154 else:
128 if name=='run':
155 if name=='run':
129 156 methodToCall(**self.kwargs)
130 else:
157 else:
131 158 methodToCall(**self.operationKwargs[opId])
132 159
133 160 if self.dataOut is None:
134 161 return False
135 162
136 163 if self.dataOut.isEmpty():
137 164 return False
138 165
139 166 return True
140 167
141 168 def callObject(self, objId):
142 169
143 170 """
144 171 Ejecuta la operacion asociada al identificador del objeto "objId"
145 172
146 173 Input:
147 174
148 175 objId : identificador del objeto a ejecutar
149 176
150 177 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
151 178
152 179 Return:
153 180
154 181 None
155 182 """
156 183
157 184 if self.dataOut is not None and self.dataOut.isEmpty():
158 185 return False
159 186
160 187 externalProcObj = self.operations2RunDict[objId]
161 188
162 189 if hasattr(externalProcObj, 'mp'):
163 190 if externalProcObj.mp is False:
164 191 externalProcObj.kwargs['parent'] = self.kwargs
165 192 self.operationKwargs[objId] = externalProcObj.kwargs
166 193 externalProcObj.mp = True
167 194 externalProcObj.start()
168 195 else:
169 196 externalProcObj.run(self.dataOut, **externalProcObj.kwargs)
170 197 self.operationKwargs[objId] = externalProcObj.kwargs
171
198
172 199
173 200 return True
174 201
175 202 def call(self, opType, opName=None, opId=None):
176 203
177 204 """
178 205 Return True si ejecuta la operacion interna nombrada "opName" o la operacion externa
179 206 identificada con el id "opId"; con los argumentos "**kwargs".
180 207
181 208 False si la operacion no se ha ejecutado.
182 209
183 210 Input:
184 211
185 212 opType : Puede ser "self" o "external"
186 213
187 214 Depende del tipo de operacion para llamar a:callMethod or callObject:
188 215
189 216 1. If opType = "self": Llama a un metodo propio de esta clase:
190 217
191 218 name_method = getattr(self, name)
192 219 name_method(**kwargs)
193 220
194 221
195 222 2. If opType = "other" o"external": Llama al metodo "run()" de una instancia de la
196 223 clase "Operation" o de un derivado de ella:
197 224
198 225 instanceName = self.operationList[opId]
199 226 instanceName.run(**kwargs)
200 227
201 228 opName : Si la operacion es interna (opType = 'self'), entonces el "opName" sera
202 229 usada para llamar a un metodo interno de la clase Processing
203 230
204 231 opId : Si la operacion es externa (opType = 'other' o 'external), entonces el
205 232 "opId" sera usada para llamar al metodo "run" de la clase Operation
206 233 registrada anteriormente con ese Id
207 234
208 235 Exception:
209 236 Este objeto de tipo Operation debe de haber sido agregado antes con el metodo:
210 237 "addOperation" e identificado con el valor "opId" = el id de la operacion.
211 238 De lo contrario retornara un error del tipo ValueError
212 239
213 240 """
214 241
215 242 if opType == 'self':
216 243
217 244 if not opName:
218 245 raise ValueError, "opName parameter should be defined"
219 246
220 247 sts = self.callMethod(opName, opId)
221 248
222 249 elif opType == 'other' or opType == 'external' or opType == 'plotter':
223 250
224 251 if not opId:
225 252 raise ValueError, "opId parameter should be defined"
226 253
227 254 if opId not in self.operations2RunDict.keys():
228 255 raise ValueError, "Any operation with id=%s has been added" %str(opId)
229 256
230 257 sts = self.callObject(opId)
231 258
232 259 else:
233 260 raise ValueError, "opType should be 'self', 'external' or 'plotter'; and not '%s'" %opType
234 261
235 262 return sts
236 263
237 264 def setInput(self, dataIn):
238 265
239 266 self.dataIn = dataIn
240 267 self.dataInList.append(dataIn)
241 268
242 269 def getOutputObj(self):
243 270
244 271 return self.dataOut
245 272
246 273 def checkInputs(self):
247 274
248 275 for thisDataIn in self.dataInList:
249 276
250 277 if thisDataIn.isEmpty():
251 278 return False
252 279
253 280 return True
254 281
255 282 def setup(self):
256 283
257 284 raise NotImplementedError
258 285
259 286 def run(self):
260 287
261 288 raise NotImplementedError
262 289
263 290 def close(self):
264 291 #Close every thread, queue or any other object here is it is neccesary.
265 292 return
266 293
267 294 class Operation(object):
268 295
269 296 """
270 297 Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit
271 298 y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de
272 299 acumulacion dentro de esta clase
273 300
274 301 Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer)
275 302
276 303 """
277 304
278 305 __buffer = None
279 306 isConfig = False
280 307
281 308 def __init__(self, **kwargs):
282 309
283 310 self.__buffer = None
284 311 self.isConfig = False
285 312 self.kwargs = kwargs
313 checkKwargs(self.run, kwargs)
314
315 def getAllowedArgs(self):
316 return inspect.getargspec(self.run).args
286 317
287 318 def setup(self):
288 319
289 320 self.isConfig = True
290 321
291 322 raise NotImplementedError
292 323
293 324 def run(self, dataIn, **kwargs):
294 325
295 326 """
296 327 Realiza las operaciones necesarias sobre la dataIn.data y actualiza los
297 328 atributos del objeto dataIn.
298 329
299 330 Input:
300 331
301 332 dataIn : objeto del tipo JROData
302 333
303 334 Return:
304 335
305 336 None
306 337
307 338 Affected:
308 339 __buffer : buffer de recepcion de datos.
309 340
310 341 """
311 342 if not self.isConfig:
312 343 self.setup(**kwargs)
313 344
314 345 raise NotImplementedError
315 346
316 347 def close(self):
317 348
318 349 pass
@@ -1,450 +1,465
1 1 '''
2 2 @author: Juan C. Espinoza
3 3 '''
4 4
5 5 import time
6 6 import json
7 7 import numpy
8 8 import paho.mqtt.client as mqtt
9 9 import zmq
10 import cPickle as pickle
10 from profilehooks import profile
11 11 import datetime
12 12 from zmq.utils.monitor import recv_monitor_message
13 13 from functools import wraps
14 14 from threading import Thread
15 15 from multiprocessing import Process
16 16
17 17 from schainpy.model.proc.jroproc_base import Operation, ProcessingUnit
18 18
19 19 MAXNUMX = 100
20 20 MAXNUMY = 100
21 21
22 22 class PrettyFloat(float):
23 23 def __repr__(self):
24 24 return '%.2f' % self
25 25
26 26 def roundFloats(obj):
27 27 if isinstance(obj, list):
28 28 return map(roundFloats, obj)
29 29 elif isinstance(obj, float):
30 30 return round(obj, 2)
31 31
32 def decimate(z):
32 def decimate(z, MAXNUMY):
33 33 # dx = int(len(self.x)/self.__MAXNUMX) + 1
34 34
35 35 dy = int(len(z[0])/MAXNUMY) + 1
36 36
37 37 return z[::, ::dy]
38 38
39 39 class throttle(object):
40 40 """Decorator that prevents a function from being called more than once every
41 41 time period.
42 42 To create a function that cannot be called more than once a minute, but
43 43 will sleep until it can be called:
44 44 @throttle(minutes=1)
45 45 def foo():
46 46 pass
47 47
48 48 for i in range(10):
49 49 foo()
50 50 print "This function has run %s times." % i
51 51 """
52 52
53 53 def __init__(self, seconds=0, minutes=0, hours=0):
54 54 self.throttle_period = datetime.timedelta(
55 55 seconds=seconds, minutes=minutes, hours=hours
56 56 )
57 57
58 58 self.time_of_last_call = datetime.datetime.min
59 59
60 60 def __call__(self, fn):
61 61 @wraps(fn)
62 62 def wrapper(*args, **kwargs):
63 63 now = datetime.datetime.now()
64 64 time_since_last_call = now - self.time_of_last_call
65 65 time_left = self.throttle_period - time_since_last_call
66 66
67 67 if time_left > datetime.timedelta(seconds=0):
68 68 return
69 69
70 70 self.time_of_last_call = datetime.datetime.now()
71 71 return fn(*args, **kwargs)
72 72
73 73 return wrapper
74 74
75 75
76 76 class PublishData(Operation):
77 77 """Clase publish."""
78 78
79 79 def __init__(self, **kwargs):
80 80 """Inicio."""
81 81 Operation.__init__(self, **kwargs)
82 82 self.isConfig = False
83 83 self.client = None
84 84 self.zeromq = None
85 85 self.mqtt = None
86 86
87 87 def on_disconnect(self, client, userdata, rc):
88 88 if rc != 0:
89 89 print("Unexpected disconnection.")
90 90 self.connect()
91 91
92 92 def connect(self):
93 93 print 'trying to connect'
94 94 try:
95 95 self.client.connect(
96 96 host=self.host,
97 97 port=self.port,
98 98 keepalive=60*10,
99 99 bind_address='')
100 100 self.client.loop_start()
101 101 # self.client.publish(
102 102 # self.topic + 'SETUP',
103 103 # json.dumps(setup),
104 104 # retain=True
105 105 # )
106 106 except:
107 107 print "MQTT Conection error."
108 108 self.client = False
109 109
110 def setup(self, port=1883, username=None, password=None, clientId="user", zeromq=1, **kwargs):
110 def setup(self, port=1883, username=None, password=None, clientId="user", zeromq=1, verbose=True, **kwargs):
111 111 self.counter = 0
112 112 self.topic = kwargs.get('topic', 'schain')
113 113 self.delay = kwargs.get('delay', 0)
114 114 self.plottype = kwargs.get('plottype', 'spectra')
115 115 self.host = kwargs.get('host', "10.10.10.82")
116 116 self.port = kwargs.get('port', 3000)
117 117 self.clientId = clientId
118 118 self.cnt = 0
119 119 self.zeromq = zeromq
120 120 self.mqtt = kwargs.get('plottype', 0)
121 121 self.client = None
122 self.verbose = verbose
123 self.dataOut.firstdata = True
122 124 setup = []
123 125 if mqtt is 1:
124 126 self.client = mqtt.Client(
125 127 client_id=self.clientId + self.topic + 'SCHAIN',
126 128 clean_session=True)
127 129 self.client.on_disconnect = self.on_disconnect
128 130 self.connect()
129 131 for plot in self.plottype:
130 132 setup.append({
131 133 'plot': plot,
132 134 'topic': self.topic + plot,
133 135 'title': getattr(self, plot + '_' + 'title', False),
134 136 'xlabel': getattr(self, plot + '_' + 'xlabel', False),
135 137 'ylabel': getattr(self, plot + '_' + 'ylabel', False),
136 138 'xrange': getattr(self, plot + '_' + 'xrange', False),
137 139 'yrange': getattr(self, plot + '_' + 'yrange', False),
138 140 'zrange': getattr(self, plot + '_' + 'zrange', False),
139 141 })
140 142 if zeromq is 1:
141 143 context = zmq.Context()
142 144 self.zmq_socket = context.socket(zmq.PUSH)
143 145 server = kwargs.get('server', 'zmq.pipe')
144 146
145 147 if 'tcp://' in server:
146 148 address = server
147 149 else:
148 150 address = 'ipc:///tmp/%s' % server
149 151
150 152 self.zmq_socket.connect(address)
151 153 time.sleep(1)
152 154
155
153 156 def publish_data(self):
154 157 self.dataOut.finished = False
155 158 if self.mqtt is 1:
156 159 yData = self.dataOut.heightList[:2].tolist()
157 160 if self.plottype == 'spectra':
158 161 data = getattr(self.dataOut, 'data_spc')
159 162 z = data/self.dataOut.normFactor
160 163 zdB = 10*numpy.log10(z)
161 164 xlen, ylen = zdB[0].shape
162 165 dx = int(xlen/MAXNUMX) + 1
163 166 dy = int(ylen/MAXNUMY) + 1
164 167 Z = [0 for i in self.dataOut.channelList]
165 168 for i in self.dataOut.channelList:
166 169 Z[i] = zdB[i][::dx, ::dy].tolist()
167 170 payload = {
168 171 'timestamp': self.dataOut.utctime,
169 172 'data': roundFloats(Z),
170 173 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
171 174 'interval': self.dataOut.getTimeInterval(),
172 175 'type': self.plottype,
173 176 'yData': yData
174 177 }
175 178 # print payload
176 179
177 180 elif self.plottype in ('rti', 'power'):
178 181 data = getattr(self.dataOut, 'data_spc')
179 182 z = data/self.dataOut.normFactor
180 183 avg = numpy.average(z, axis=1)
181 184 avgdB = 10*numpy.log10(avg)
182 185 xlen, ylen = z[0].shape
183 186 dy = numpy.floor(ylen/self.__MAXNUMY) + 1
184 187 AVG = [0 for i in self.dataOut.channelList]
185 188 for i in self.dataOut.channelList:
186 189 AVG[i] = avgdB[i][::dy].tolist()
187 190 payload = {
188 191 'timestamp': self.dataOut.utctime,
189 192 'data': roundFloats(AVG),
190 193 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
191 194 'interval': self.dataOut.getTimeInterval(),
192 195 'type': self.plottype,
193 196 'yData': yData
194 197 }
195 198 elif self.plottype == 'noise':
196 199 noise = self.dataOut.getNoise()/self.dataOut.normFactor
197 200 noisedB = 10*numpy.log10(noise)
198 201 payload = {
199 202 'timestamp': self.dataOut.utctime,
200 203 'data': roundFloats(noisedB.reshape(-1, 1).tolist()),
201 204 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
202 205 'interval': self.dataOut.getTimeInterval(),
203 206 'type': self.plottype,
204 207 'yData': yData
205 208 }
206 209 elif self.plottype == 'snr':
207 210 data = getattr(self.dataOut, 'data_SNR')
208 211 avgdB = 10*numpy.log10(data)
209 212
210 213 ylen = data[0].size
211 214 dy = numpy.floor(ylen/self.__MAXNUMY) + 1
212 215 AVG = [0 for i in self.dataOut.channelList]
213 216 for i in self.dataOut.channelList:
214 217 AVG[i] = avgdB[i][::dy].tolist()
215 218 payload = {
216 219 'timestamp': self.dataOut.utctime,
217 220 'data': roundFloats(AVG),
218 221 'channels': ['Ch %s' % ch for ch in self.dataOut.channelList],
219 222 'type': self.plottype,
220 223 'yData': yData
221 224 }
222 225 else:
223 226 print "Tipo de grafico invalido"
224 227 payload = {
225 228 'data': 'None',
226 229 'timestamp': 'None',
227 230 'type': None
228 231 }
229 232 # print 'Publishing data to {}'.format(self.host)
230 233 self.client.publish(self.topic + self.plottype, json.dumps(payload), qos=0)
231 234
232 235 if self.zeromq is 1:
233 print '[Sending] {} - {}'.format(self.dataOut.type, self.dataOut.datatime)
236 if self.verbose:
237 print '[Sending] {} - {}'.format(self.dataOut.type, self.dataOut.datatime)
234 238 self.zmq_socket.send_pyobj(self.dataOut)
239 self.dataOut.firstdata = False
240
235 241
236 242 def run(self, dataOut, **kwargs):
237 243 self.dataOut = dataOut
238 244 if not self.isConfig:
239 245 self.setup(**kwargs)
240 246 self.isConfig = True
241 247
242 248 self.publish_data()
243 249 time.sleep(self.delay)
244 250
245 251 def close(self):
246 252 if self.zeromq is 1:
247 253 self.dataOut.finished = True
248 254 self.zmq_socket.send_pyobj(self.dataOut)
249
255 self.zmq_socket.close()
250 256 if self.client:
251 257 self.client.loop_stop()
252 258 self.client.disconnect()
253 259
254
255 260 class ReceiverData(ProcessingUnit, Process):
256 261
257 262 throttle_value = 5
258 263
259 264 def __init__(self, **kwargs):
260 265
261 266 ProcessingUnit.__init__(self, **kwargs)
262 267 Process.__init__(self)
263 268 self.mp = False
264 269 self.isConfig = False
265 270 self.isWebConfig = False
266 271 self.plottypes =[]
267 272 self.connections = 0
268 273 server = kwargs.get('server', 'zmq.pipe')
269 274 plot_server = kwargs.get('plot_server', 'zmq.web')
270 275 if 'tcp://' in server:
271 276 address = server
272 277 else:
273 278 address = 'ipc:///tmp/%s' % server
274 279
275 280 if 'tcp://' in plot_server:
276 281 plot_address = plot_server
277 282 else:
278 283 plot_address = 'ipc:///tmp/%s' % plot_server
279 284
280 285 self.address = address
281 286 self.plot_address = plot_address
282 287 self.plottypes = [s.strip() for s in kwargs.get('plottypes', 'rti').split(',')]
283 288 self.realtime = kwargs.get('realtime', False)
284 289 self.throttle_value = kwargs.get('throttle', 5)
285 290 self.sendData = self.initThrottle(self.throttle_value)
286 291 self.setup()
287 292
288 293 def setup(self):
289 294
290 295 self.data = {}
291 296 self.data['times'] = []
292 297 for plottype in self.plottypes:
293 298 self.data[plottype] = {}
294 299 self.data['noise'] = {}
295 300 self.data['throttle'] = self.throttle_value
296 301 self.data['ENDED'] = False
297 302 self.isConfig = True
298 303 self.data_web = {}
299 304
300 305 def event_monitor(self, monitor):
301 306
302 307 events = {}
303 308
304 309 for name in dir(zmq):
305 310 if name.startswith('EVENT_'):
306 311 value = getattr(zmq, name)
307 312 events[value] = name
308 313
309 314 while monitor.poll():
310 315 evt = recv_monitor_message(monitor)
311 316 if evt['event'] == 32:
312 317 self.connections += 1
313 318 if evt['event'] == 512:
314 319 pass
315 320 if self.connections == 0 and self.started is True:
316 321 self.ended = True
317 322
318 323 evt.update({'description': events[evt['event']]})
319 324
320 325 if evt['event'] == zmq.EVENT_MONITOR_STOPPED:
321 326 break
322 327 monitor.close()
323 328 print("event monitor thread done!")
324 329
325 330 def initThrottle(self, throttle_value):
326 331
327 332 @throttle(seconds=throttle_value)
328 333 def sendDataThrottled(fn_sender, data):
329 334 fn_sender(data)
330 335
331 336 return sendDataThrottled
332 337
338
333 339 def send(self, data):
334 340 # print '[sending] data=%s size=%s' % (data.keys(), len(data['times']))
335 341 self.sender.send_pyobj(data)
336 342
337 def update(self):
338 343
344 def update(self):
339 345 t = self.dataOut.utctime
340 346
341 347 if t in self.data['times']:
342 348 return
343 349
344 350 self.data['times'].append(t)
345 351 self.data['dataOut'] = self.dataOut
346 352
347 353 for plottype in self.plottypes:
348 354 if plottype == 'spc':
349 355 z = self.dataOut.data_spc/self.dataOut.normFactor
350 356 self.data[plottype] = 10*numpy.log10(z)
351 357 self.data['noise'][t] = 10*numpy.log10(self.dataOut.getNoise()/self.dataOut.normFactor)
352 358 if plottype == 'cspc':
353 359 jcoherence = self.dataOut.data_cspc/numpy.sqrt(self.dataOut.data_spc*self.dataOut.data_spc)
354 360 self.data['cspc_coh'] = numpy.abs(jcoherence)
355 361 self.data['cspc_phase'] = numpy.arctan2(jcoherence.imag, jcoherence.real)*180/numpy.pi
356 362 if plottype == 'rti':
357 363 self.data[plottype][t] = self.dataOut.getPower()
358 364 if plottype == 'snr':
359 365 self.data[plottype][t] = 10*numpy.log10(self.dataOut.data_SNR)
360 366 if plottype == 'dop':
361 367 self.data[plottype][t] = 10*numpy.log10(self.dataOut.data_DOP)
362 368 if plottype == 'mean':
363 369 self.data[plottype][t] = self.dataOut.data_MEAN
364 370 if plottype == 'std':
365 371 self.data[plottype][t] = self.dataOut.data_STD
366 372 if plottype == 'coh':
367 373 self.data[plottype][t] = self.dataOut.getCoherence()
368 374 if plottype == 'phase':
369 375 self.data[plottype][t] = self.dataOut.getCoherence(phase=True)
370 376 if plottype == 'output':
371 377 self.data[plottype][t] = self.dataOut.data_output
372 378 if plottype == 'param':
373 379 self.data[plottype][t] = self.dataOut.data_param
374 380 if self.realtime:
375 381 self.data_web['timestamp'] = t
376 382 if plottype == 'spc':
377 383 self.data_web[plottype] = roundFloats(decimate(self.data[plottype]).tolist())
378 384 elif plottype == 'cspc':
379 385 self.data_web['cspc_coh'] = roundFloats(decimate(self.data['cspc_coh']).tolist())
380 386 self.data_web['cspc_phase'] = roundFloats(decimate(self.data['cspc_phase']).tolist())
381 387 elif plottype == 'noise':
382 388 self.data_web['noise'] = roundFloats(self.data['noise'][t].tolist())
383 389 else:
384 390 self.data_web[plottype] = roundFloats(decimate(self.data[plottype][t]).tolist())
385 391 self.data_web['interval'] = self.dataOut.getTimeInterval()
386 392 self.data_web['type'] = plottype
387 393
388 394 def run(self):
389 395
390 396 print '[Starting] {} from {}'.format(self.name, self.address)
391 397
392 398 self.context = zmq.Context()
393 399 self.receiver = self.context.socket(zmq.PULL)
394 400 self.receiver.bind(self.address)
395 401 monitor = self.receiver.get_monitor_socket()
396 402 self.sender = self.context.socket(zmq.PUB)
397 403 if self.realtime:
398 404 self.sender_web = self.context.socket(zmq.PUB)
399 405 self.sender_web.connect(self.plot_address)
400 406 time.sleep(1)
407
401 408 if 'server' in self.kwargs:
402 409 self.sender.bind("ipc:///tmp/{}.plots".format(self.kwargs['server']))
403 410 else:
404 411 self.sender.bind("ipc:///tmp/zmq.plots")
405 412
413 time.sleep(3)
414
406 415 t = Thread(target=self.event_monitor, args=(monitor,))
407 416 t.start()
408 417
409 418 while True:
410 419 self.dataOut = self.receiver.recv_pyobj()
411 420 # print '[Receiving] {} - {}'.format(self.dataOut.type,
412 421 # self.dataOut.datatime.ctime())
413 422
414 423 self.update()
415 424
425 if self.dataOut.firstdata is True:
426 self.data['STARTED'] = True
427
428
416 429 if self.dataOut.finished is True:
417 430 self.send(self.data)
418 431 self.connections -= 1
419 432 if self.connections == 0 and self.started:
420 433 self.ended = True
421 434 self.data['ENDED'] = True
422 435 self.send(self.data)
423 436 self.setup()
437 self.started = False
424 438 else:
425 439 if self.realtime:
426 440 self.send(self.data)
427 441 self.sender_web.send_string(json.dumps(self.data_web))
428 442 else:
429 443 self.sendData(self.send, self.data)
430 444 self.started = True
431 445
446 self.data['STARTED'] = False
432 447 return
433 448
434 449 def sendToWeb(self):
435 450
436 451 if not self.isWebConfig:
437 452 context = zmq.Context()
438 453 sender_web_config = context.socket(zmq.PUB)
439 454 if 'tcp://' in self.plot_address:
440 455 dum, address, port = self.plot_address.split(':')
441 456 conf_address = '{}:{}:{}'.format(dum, address, int(port)+1)
442 457 else:
443 458 conf_address = self.plot_address + '.config'
444 459 sender_web_config.bind(conf_address)
445 460 time.sleep(1)
446 461 for kwargs in self.operationKwargs.values():
447 462 if 'plot' in kwargs:
448 463 print '[Sending] Config data to web for {}'.format(kwargs['code'].upper())
449 464 sender_web_config.send_string(json.dumps(kwargs))
450 465 self.isWebConfig = True
@@ -1,87 +1,97
1 1 import argparse
2 2
3 3 from schainpy.controller import Project, multiSchain
4 4
5 5 desc = "HF_EXAMPLE"
6 6
7 7 def fiber(cursor, skip, q, dt):
8 8
9 9 controllerObj = Project()
10 10
11 11 controllerObj.setup(id='191', name='test01', description=desc)
12 12
13 13 readUnitConfObj = controllerObj.addReadUnit(datatype='SpectraReader',
14 path='/home/nanosat/data/hysell_data20/pdata',
14 path='/home/nanosat/data/sp1_f0',
15 15 startDate=dt,
16 16 endDate=dt,
17 17 startTime="00:00:00",
18 18 endTime="23:59:59",
19 19 online=0,
20 20 #set=1426485881,
21 delay=10,
22 21 walk=1,
23 22 queue=q,
24 23 cursor=cursor,
25 24 skip=skip,
25 verbose=1
26 26 #timezone=-5*3600
27 27 )
28 28
29 29 # #opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
30 30 #
31 31 procUnitConfObj2 = controllerObj.addProcUnit(datatype='Spectra', inputId=readUnitConfObj.getId())
32 # opObj11 = procUnitConfObj2.addParameter(name='pairsList', value='(0,1)', format='pairslist')
33 #
32 # procUnitConfObj2.addParameter(name='nipp', value='5', format='int')
33
34 34 procUnitConfObj3 = controllerObj.addProcUnit(datatype='ParametersProc', inputId=readUnitConfObj.getId())
35 35 opObj11 = procUnitConfObj3.addOperation(name='SpectralMoments', optype='other')
36 36
37 37 #
38 38 # opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='other')
39 39 # opObj11.addParameter(name='id', value='1000', format='int')
40 40 # opObj11.addParameter(name='wintitle', value='HF_Jicamarca_Spc', format='str')
41 41 # opObj11.addParameter(name='channelList', value='0', format='intlist')
42 42 # opObj11.addParameter(name='zmin', value='-120', format='float')
43 43 # opObj11.addParameter(name='zmax', value='-70', format='float')
44 44 # opObj11.addParameter(name='save', value='1', format='int')
45 45 # opObj11.addParameter(name='figpath', value=figpath, format='str')
46 46
47 # opObj11 = procUnitConfObj2.addOperation(name='RTIPlot', optype='other')
47 # opObj11 = procUnitConfObj3.addOperation(name='Parameters1Plot', optype='other')
48 # opObj11.addParameter(name='channelList', value='0', format='intList')
49
48 50 # opObj11.addParameter(name='id', value='2000', format='int')
49 # opObj11.addParameter(name='wintitzmaxle', value='HF_Jicamarca', format='str')
50 # opObj11.addParameter(name='showprofile', value='0', format='int')
51 # # opObj11.addParameter(name='colormap', value='0', format='bool')
52 # opObj11.addParameter(name='onlySNR', value='1', format='bool')
53 # opObj11.addParameter(name='DOP', value='0', format='bool')
54 # # opObj11.addParameter(name='showSNR', value='1', format='bool')
55 # # opObj11.addParameter(name='SNRthresh', value='0', format='int')
56 # opObj11.addParameter(name='SNRmin', value='-10', format='int')
57 # opObj11.addParameter(name='SNRmax', value='30', format='int')
58
59 # opObj11.addParameter(name='showSNR', value='1', format='int')
51 60 # # opObj11.addParameter(name='channelList', value='0', format='intlist')
52 61 # # opObj11.addParameter(name='xmin', value='0', format='float')
53 62 # opObj11.addParameter(name='xmin', value='0', format='float')
54 63 # opObj11.addParameter(name='xmax', value='24', format='float')
55 64
56 65 # opObj11.addParameter(name='zmin', value='-110', format='float')
57 66 # opObj11.addParameter(name='zmax', value='-70', format='float')
58 67 # opObj11.addParameter(name='save', value='0', format='int')
59 68 # # opObj11.addParameter(name='figpath', value='/tmp/', format='str')
60 69 #
61 70 opObj12 = procUnitConfObj3.addOperation(name='PublishData', optype='other')
62 71 opObj12.addParameter(name='zeromq', value=1, format='int')
72 opObj12.addParameter(name='verbose', value=0, format='bool')
63 73
64 74
65 75 # opObj13 = procUnitConfObj3.addOperation(name='PublishData', optype='other')
66 76 # opObj13.addParameter(name='zeromq', value=1, format='int')
67 77 # opObj13.addParameter(name='server', value="juanca", format='str')
68 78
69 opObj12.addParameter(name='delay', value=1, format='int')
79 opObj12.addParameter(name='delay', value=0, format='int')
70 80
71 81
72 82 # print "Escribiendo el archivo XML"
73 83 # controllerObj.writeXml(filename)
74 84 # print "Leyendo el archivo XML"
75 85 # controllerObj.readXml(filename)
76 86
77 87
78 88 # timeit.timeit('controllerObj.run()', number=2)
79 89
80 90 controllerObj.start()
81 91
82 92
83 93 if __name__ == '__main__':
84 94 parser = argparse.ArgumentParser(description='Set number of parallel processes')
85 95 parser.add_argument('--nProcess', default=1, type=int)
86 96 args = parser.parse_args()
87 multiSchain(fiber, nProcess=args.nProcess, startDate='2015/09/26', endDate='2015/09/26')
97 multiSchain(fiber, nProcess=args.nProcess, startDate='2017/01/26', endDate='2017/01/28')
@@ -1,75 +1,97
1 #!/usr/bin/env python
2 '''
3 Created on Jul 7, 2014
1 import argparse
4 2
5 @author: roj-idl71
6 '''
7 import os, sys
8 from datetime import datetime, timedelta
9 import multiprocessing
10 from schainpy.controller import Project
3 from schainpy.controller import Project, multiSchain
11 4
12 def main(date):
5 desc = "HF_EXAMPLE"
13 6
14 controllerObj = Project()
15
16 controllerObj.setup(id='191', name='test01', description='')
17
18 readUnitConfObj = controllerObj.addReadUnit(datatype='Spectra',
19 path='/home/nanosat/data/zeus',
20 startDate=date,
21 endDate=date,
22 startTime='00:00:00',
23 endTime='23:59:59',
24 online=0,
25 walk=1,
26 expLabel='')
27
28 procUnitConfObj1 = controllerObj.addProcUnit(datatype='Spectra', inputId=readUnitConfObj.getId())
29 #opObj11 = procUnitConfObj1.addOperation(name='removeDC')
30 #opObj11.addParameter(name='mode', value='1', format='int')
31
32 #opObj11 = procUnitConfObj1.addOperation(name='removeInterference')
33
34
35 opObj11 = procUnitConfObj1.addOperation(name='RTIPlot', optype='other')
36 opObj11.addParameter(name='id', value='10', format='int')
37 opObj11.addParameter(name='wintitle', value='150Km', format='str')
38 opObj11.addParameter(name='colormap', value='jro', format='str')
39 opObj11.addParameter(name='xaxis', value='time', format='str')
40 opObj11.addParameter(name='xmin', value='0', format='int')
41 opObj11.addParameter(name='xmax', value='23', format='int')
42 #opObj11.addParameter(name='ymin', value='100', format='int')
43 #opObj11.addParameter(name='ymax', value='150', format='int')
44 opObj11.addParameter(name='zmin', value='10', format='int')
45 opObj11.addParameter(name='zmax', value='35', format='int')
7 def fiber(cursor, skip, q, dt):
46 8
9 controllerObj = Project()
47 10
48
49
50 opObject12 = procUnitConfObj1.addOperation(name='PlotRTIData', optype='other')
51 opObject12.addParameter(name='id', value='12', format='int')
52 opObject12.addParameter(name='wintitle', value='150Km', format='str')
53 opObject12.addParameter(name='colormap', value='jro', format='str')
54 opObject12.addParameter(name='xaxis', value='time', format='str')
55 opObject12.addParameter(name='xmin', value='0', format='int')
56 opObject12.addParameter(name='xmax', value='23', format='int')
57 #opObject12.addParameter(name='ymin', value='100', format='int')
58 #opObject12.addParameter(name='ymax', value='150', format='int')
59 opObject12.addParameter(name='zmin', value='10', format='int')
60 opObject12.addParameter(name='zmax', value='35', format='int')
61 #opObject12.addParameter(name='pause', value='1', format='bool')
62 opObject12.addParameter(name='show', value='0', format='bool')
63 opObject12.addParameter(name='save', value='/tmp', format='str')
64
11 controllerObj.setup(id='191', name='test01', description=desc)
12
13 readUnitConfObj = controllerObj.addReadUnit(datatype='SpectraReader',
14 path='/home/nanosat/data/julia',
15 startDate=dt,
16 endDate=dt,
17 startTime="00:00:00",
18 endTime="23:59:59",
19 online=0,
20 #set=1426485881,
21 delay=10,
22 walk=1,
23 queue=q,
24 cursor=cursor,
25 skip=skip,
26 #timezone=-5*3600
27 )
28
29 # #opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
30 #
31 procUnitConfObj2 = controllerObj.addProcUnit(datatype='Spectra', inputId=readUnitConfObj.getId())
32 # procUnitConfObj2.addParameter(name='nipp', value='5', format='int')
33
34 # procUnitConfObj3 = controllerObj.addProcUnit(datatype='ParametersProc', inputId=readUnitConfObj.getId())
35 # opObj11 = procUnitConfObj3.addOperation(name='SpectralMoments', optype='other')
36
37 #
38 # opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='other')
39 # opObj11.addParameter(name='id', value='1000', format='int')
40 # opObj11.addParameter(name='wintitle', value='HF_Jicamarca_Spc', format='str')
41 # opObj11.addParameter(name='channelList', value='0', format='intlist')
42 # opObj11.addParameter(name='zmin', value='-120', format='float')
43 # opObj11.addParameter(name='zmax', value='-70', format='float')
44 # opObj11.addParameter(name='save', value='1', format='int')
45 # opObj11.addParameter(name='figpath', value=figpath, format='str')
46
47 # opObj11 = procUnitConfObj3.addOperation(name='Parameters1Plot', optype='other')
48 # opObj11.addParameter(name='channelList', value='0', format='intList')
49 #
50 # opObj11.addParameter(name='id', value='2000', format='int')
51 # # opObj11.addParameter(name='colormap', value='0', format='bool')
52 # opObj11.addParameter(name='onlySNR', value='1', format='bool')
53 # opObj11.addParameter(name='DOP', value='0', format='bool')
54 # opObj11.addParameter(name='showSNR', value='1', format='bool')
55 # opObj11.addParameter(name='SNRthresh', value='0', format='int')
56 # opObj11.addParameter(name='SNRmin', value='-10', format='int')
57 # opObj11.addParameter(name='SNRmax', value='30', format='int')
58
59 # opObj11.addParameter(name='showSNR', value='1', format='int')
60 # # opObj11.addParameter(name='channelList', value='0', format='intlist')
61 # # opObj11.addParameter(name='xmin', value='0', format='float')
62 # opObj11.addParameter(name='xmin', value='0', format='float')
63 # opObj11.addParameter(name='xmax', value='24', format='float')
64
65 # opObj11.addParameter(name='zmin', value='-110', format='float')
66 # opObj11.addParameter(name='zmax', value='-70', format='float')
67 # opObj11.addParameter(name='save', value='0', format='int')
68 # # opObj11.addParameter(name='figpath', value='/tmp/', format='str')
69 #
70 opObj12 = procUnitConfObj2.addOperation(name='PublishData', optype='other')
71 opObj12.addParameter(name='zeromq', value=1, format='int')
72 # opObj12.addParameter(name='server', value='tcp://10.10.10.82:7000', format='str')
73
74
75 # opObj13 = procUnitConfObj3.addOperation(name='PublishData', optype='other')
76 # opObj13.addParameter(name='zeromq', value=1, format='int')
77 # opObj13.addParameter(name='server', value="juanca", format='str')
78
79 # opObj12.addParameter(name='delay', value=1, format='int')
80
81
82 # print "Escribiendo el archivo XML"
83 # controllerObj.writeXml(filename)
84 # print "Leyendo el archivo XML"
85 # controllerObj.readXml(filename)
86
87
88 # timeit.timeit('controllerObj.run()', number=2)
65 89
66 90 controllerObj.start()
67 91
68 if __name__=='__main__':
69
70 dt = datetime(2017, 1, 12)
71
72 dates = [(dt+timedelta(x)).strftime('%Y/%m/%d') for x in range(20)]
73 92
74 p = multiprocessing.Pool(4)
75 p.map(main, dates)
93 if __name__ == '__main__':
94 parser = argparse.ArgumentParser(description='Set number of parallel processes')
95 parser.add_argument('--nProcess', default=1, type=int)
96 args = parser.parse_args()
97 multiSchain(fiber, nProcess=args.nProcess, startDate='2016/08/19', endDate='2016/08/19')
@@ -1,58 +1,58
1 1 #!/usr/bin/env python
2 2 '''
3 3 Created on Jul 7, 2014
4 4
5 5 @author: roj-idl71
6 6 '''
7 7 import os, sys
8 8
9 9 from schainpy.controller import Project
10 10
11 11 if __name__ == '__main__':
12 12 desc = "Segundo Test"
13 13
14 14 controllerObj = Project()
15 15 controllerObj.setup(id='191', name='test01', description=desc)
16 16
17 17 proc1 = controllerObj.addProcUnit(name='ReceiverData')
18 18 proc1.addParameter(name='realtime', value='0', format='bool')
19 proc1.addParameter(name='plottypes', value='rti,coh,phase,snr,dop', format='str')
19 proc1.addParameter(name='plottypes', value='rti,coh,phase', format='str')
20 20 proc1.addParameter(name='throttle', value='10', format='int')
21 proc1.addParameter(name='plot_server', value='tcp://10.10.10.82:7000', format='str')
21 # proc1.addParameter(name='server', value='tcp://10.10.10.82:7000', format='str')
22 22 ## TODO Agregar direccion de server de publicacion a graficos como variable
23 23
24 24 op1 = proc1.addOperation(name='PlotRTIData', optype='other')
25 25 op1.addParameter(name='wintitle', value='Julia 150Km', format='str')
26 26 op1.addParameter(name='save', value='/home/nanosat/Pictures', format='str')
27 27 op1.addParameter(name='show', value='0', format='bool')
28 28 op1.addParameter(name='colormap', value='jet', format='str')
29 29 #
30 30 op2 = proc1.addOperation(name='PlotCOHData', optype='other')
31 31 op2.addParameter(name='wintitle', value='Julia 150Km', format='str')
32 32 op2.addParameter(name='save', value='/home/nanosat/Pictures', format='str')
33 33 op2.addParameter(name='colormap', value='jet', format='str')
34 34 op2.addParameter(name='show', value='0', format='bool')
35 # #
35 # # #
36 36 op6 = proc1.addOperation(name='PlotPHASEData', optype='other')
37 37 op6.addParameter(name='wintitle', value='Julia 150Km', format='str')
38 38 op6.addParameter(name='save', value='/home/nanosat/Pictures', format='str')
39 39 op6.addParameter(name='show', value='1', format='bool')
40 #
41 # proc2 = controllerObj.addProcUnit(name='ReceiverData')
42 # proc2.addParameter(name='server', value='juanca', format='str')
43 # proc2.addParameter(name='plottypes', value='snr,dop', format='str')
44 #
45 op3 = proc1.addOperation(name='PlotSNRData', optype='other')
46 op3.addParameter(name='wintitle', value='Julia 150Km', format='str')
47 op3.addParameter(name='save', value='/home/nanosat/Pictures', format='str')
48 op3.addParameter(name='show', value='0', format='bool')
49 #
50 op4 = proc1.addOperation(name='PlotDOPData', optype='other')
51 op4.addParameter(name='wintitle', value='Julia 150Km', format='str')
52 op4.addParameter(name='save', value='/home/nanosat/Pictures', format='str')
53 op4.addParameter(name='show', value='0', format='bool')
54 op4.addParameter(name='colormap', value='jet', format='str')
40 # #
41 # # proc2 = controllerObj.addProcUnit(name='ReceiverData')
42 # # proc2.addParameter(name='server', value='juanca', format='str')
43 # # proc2.addParameter(name='plottypes', value='snr,dop', format='str')
44 # #
45 # op3 = proc1.addOperation(name='PlotSNRData', optype='other')
46 # op3.addParameter(name='wintitle', value='Julia 150Km', format='str')
47 # op3.addParameter(name='save', value='/home/nanosat/Pictures', format='str')
48 # op3.addParameter(name='show', value='0', format='bool')
49 # #
50 # op4 = proc1.addOperation(name='PlotDOPData', optype='other')
51 # op4.addParameter(name='wintitle', value='Julia 150Km', format='str')
52 # op4.addParameter(name='save', value='/home/nanosat/Pictures', format='str')
53 # op4.addParameter(name='show', value='0', format='bool')
54 # op4.addParameter(name='colormap', value='jet', format='str')
55 55
56 56
57 57
58 58 controllerObj.start()
@@ -1,1 +1,1
1 <Project description="HF_EXAMPLE" id="191" name="test01"><ReadUnit datatype="SpectraReader" id="1911" inputId="0" name="SpectraReader"><Operation id="19111" name="run" priority="1" type="self"><Parameter format="str" id="191111" name="datatype" value="SpectraReader" /><Parameter format="str" id="191112" name="path" value="/home/nanosat/data/hysell_data20/pdata" /><Parameter format="date" id="191113" name="startDate" value="2015/09/26" /><Parameter format="date" id="191114" name="endDate" value="2015/09/26" /><Parameter format="time" id="191115" name="startTime" value="00:00:00" /><Parameter format="time" id="191116" name="endTime" value="23:59:59" /><Parameter format="int" id="191118" name="cursor" value="2" /><Parameter format="int" id="191119" name="skip" value="720" /><Parameter format="int" id="191120" name="delay" value="10" /><Parameter format="int" id="191121" name="walk" value="1" /><Parameter format="int" id="191122" name="online" value="0" /></Operation></ReadUnit><ProcUnit datatype="ParametersProc" id="1913" inputId="1911" name="ParametersProc"><Operation id="19131" name="run" priority="1" type="self" /><Operation id="19132" name="SpectralMoments" priority="2" type="other" /><Operation id="19133" name="PublishData" priority="3" type="other"><Parameter format="int" id="191331" name="zeromq" value="1" /><Parameter format="int" id="191332" name="delay" value="1" /></Operation></ProcUnit><ProcUnit datatype="Spectra" id="1912" inputId="1911" name="SpectraProc"><Operation id="19121" name="run" priority="1" type="self" /></ProcUnit></Project> No newline at end of file
1 <Project description="HF_EXAMPLE" id="191" name="test01"><ReadUnit datatype="SpectraReader" id="1911" inputId="0" name="SpectraReader"><Operation id="19111" name="run" priority="1" type="self"><Parameter format="str" id="191111" name="datatype" value="SpectraReader" /><Parameter format="str" id="191112" name="path" value="/home/nanosat/data/sp1_f0" /><Parameter format="date" id="191113" name="startDate" value="2017/01/28" /><Parameter format="date" id="191114" name="endDate" value="2017/01/28" /><Parameter format="time" id="191115" name="startTime" value="00:00:00" /><Parameter format="time" id="191116" name="endTime" value="23:59:59" /><Parameter format="int" id="191118" name="cursor" value="28" /><Parameter format="int" id="191119" name="skip" value="22" /><Parameter format="int" id="191120" name="walk" value="1" /><Parameter format="int" id="191121" name="verbose" value="1" /><Parameter format="int" id="191122" name="online" value="0" /></Operation></ReadUnit><ProcUnit datatype="ParametersProc" id="1913" inputId="1911" name="ParametersProc"><Operation id="19131" name="run" priority="1" type="self" /><Operation id="19132" name="SpectralMoments" priority="2" type="other" /><Operation id="19133" name="PublishData" priority="3" type="other"><Parameter format="int" id="191331" name="zeromq" value="1" /><Parameter format="bool" id="191332" name="verbose" value="0" /><Parameter format="int" id="191333" name="delay" value="0" /></Operation></ProcUnit><ProcUnit datatype="Spectra" id="1912" inputId="1911" name="SpectraProc"><Operation id="19121" name="run" priority="1" type="self" /></ProcUnit></Project> No newline at end of file
@@ -1,48 +1,49
1 1 '''
2 2 Created on Jul 16, 2014
3 3
4 4 @author: Miguel Urco
5 5 '''
6 6
7 7 from schainpy import __version__
8 8 from setuptools import setup, Extension
9 9
10 10 setup(name="schainpy",
11 11 version=__version__,
12 12 description="Python tools to read, write and process Jicamarca data",
13 13 author="Miguel Urco",
14 14 author_email="miguel.urco@jro.igp.gob.pe",
15 15 url="http://jro.igp.gob.pe",
16 16 packages = {'schainpy',
17 17 'schainpy.model',
18 18 'schainpy.model.data',
19 19 'schainpy.model.graphics',
20 20 'schainpy.model.io',
21 21 'schainpy.model.proc',
22 22 'schainpy.model.serializer',
23 23 'schainpy.model.utils',
24 24 'schainpy.gui',
25 25 'schainpy.gui.figures',
26 26 'schainpy.gui.viewcontroller',
27 27 'schainpy.gui.viewer',
28 28 'schainpy.gui.viewer.windows'},
29 29 ext_package='schainpy',
30 30 py_modules=[''],
31 31 package_data={'': ['schain.conf.template'],
32 32 'schainpy.gui.figures': ['*.png','*.jpg'],
33 33 },
34 34 include_package_data=False,
35 35 scripts =['schainpy/gui/schainGUI',
36 36 'schainpy/scripts/schain'],
37 37 ext_modules=[Extension("cSchain", ["schainpy/model/proc/extensions.c"])],
38 38 install_requires=[
39 39 "scipy >= 0.14.0",
40 40 "h5py >= 2.2.1",
41 41 "matplotlib >= 1.4.2",
42 42 "pyfits >= 3.4",
43 43 "numpy >= 1.11.2",
44 44 "paramiko >= 2.1.2",
45 45 "paho-mqtt >= 1.2",
46 46 "zmq",
47 "fuzzywuzzy"
47 48 ],
48 ) No newline at end of file
49 )
General Comments 0
You need to be logged in to leave comments. Login now