##// END OF EJS Templates
Merge remote-tracking branch 'HF/ind_plt_chs' into schain_mp
Juan C. Espinoza -
r1003:62df0cc8d2f7 merge
parent child
Show More
@@ -1,1326 +1,1328
1 1 '''
2 2 Created on September , 2012
3 3 @author:
4 4 '''
5 5
6 6 import sys
7 7 import ast
8 8 import datetime
9 9 import traceback
10 10 import math
11 11 import time
12 12 from multiprocessing import Process, Queue, cpu_count
13 13
14 14 import schainpy
15 15 import schainpy.admin
16 16
17 17 from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring
18 18 from xml.dom import minidom
19 19
20 20 from schainpy.model import *
21 21 from time import sleep
22 22
23 23 def prettify(elem):
24 24 """Return a pretty-printed XML string for the Element.
25 25 """
26 26 rough_string = tostring(elem, 'utf-8')
27 27 reparsed = minidom.parseString(rough_string)
28 28 return reparsed.toprettyxml(indent=" ")
29 29
30 30 def multiSchain(child, nProcess=cpu_count(), startDate=None, endDate=None, by_day=False):
31 31 skip = 0
32 32 cursor = 0
33 33 nFiles = None
34 34 processes = []
35 35 dt1 = datetime.datetime.strptime(startDate, '%Y/%m/%d')
36 36 dt2 = datetime.datetime.strptime(endDate, '%Y/%m/%d')
37 37 days = (dt2 - dt1).days
38 38
39 39 for day in range(days+1):
40 40 skip = 0
41 41 cursor = 0
42 42 q = Queue()
43 43 processes = []
44 44 dt = (dt1 + datetime.timedelta(day)).strftime('%Y/%m/%d')
45 45 firstProcess = Process(target=child, args=(cursor, skip, q, dt))
46 46 firstProcess.start()
47 47 if by_day:
48 48 continue
49 49 nFiles = q.get()
50 50 if nFiles==0:
51 51 continue
52 52 firstProcess.terminate()
53 53 skip = int(math.ceil(nFiles/nProcess))
54 54 while True:
55 55 processes.append(Process(target=child, args=(cursor, skip, q, dt)))
56 56 processes[cursor].start()
57 57 if nFiles < cursor*skip:
58 58 break
59 59 cursor += 1
60 60
61 61 def beforeExit(exctype, value, trace):
62 62 for process in processes:
63 63 process.terminate()
64 64 process.join()
65 65 print traceback.print_tb(trace)
66 66
67 67 sys.excepthook = beforeExit
68 68
69 69 for process in processes:
70 70 process.join()
71 71 process.terminate()
72
72 73 time.sleep(3)
73 74
75
74 76 class ParameterConf():
75 77
76 78 id = None
77 79 name = None
78 80 value = None
79 81 format = None
80 82
81 83 __formated_value = None
82 84
83 85 ELEMENTNAME = 'Parameter'
84 86
85 87 def __init__(self):
86 88
87 89 self.format = 'str'
88 90
89 91 def getElementName(self):
90 92
91 93 return self.ELEMENTNAME
92 94
93 95 def getValue(self):
94 96
95 97 value = self.value
96 98 format = self.format
97 99
98 100 if self.__formated_value != None:
99 101
100 102 return self.__formated_value
101 103
102 104 if format == 'obj':
103 105 return value
104 106
105 107 if format == 'str':
106 108 self.__formated_value = str(value)
107 109 return self.__formated_value
108 110
109 111 if value == '':
110 112 raise ValueError, "%s: This parameter value is empty" %self.name
111 113
112 114 if format == 'list':
113 115 strList = value.split(',')
114 116
115 117 self.__formated_value = strList
116 118
117 119 return self.__formated_value
118 120
119 121 if format == 'intlist':
120 122 """
121 123 Example:
122 124 value = (0,1,2)
123 125 """
124 126
125 127 new_value = ast.literal_eval(value)
126 128
127 129 if type(new_value) not in (tuple, list):
128 130 new_value = [int(new_value)]
129 131
130 132 self.__formated_value = new_value
131 133
132 134 return self.__formated_value
133 135
134 136 if format == 'floatlist':
135 137 """
136 138 Example:
137 139 value = (0.5, 1.4, 2.7)
138 140 """
139 141
140 142 new_value = ast.literal_eval(value)
141 143
142 144 if type(new_value) not in (tuple, list):
143 145 new_value = [float(new_value)]
144 146
145 147 self.__formated_value = new_value
146 148
147 149 return self.__formated_value
148 150
149 151 if format == 'date':
150 152 strList = value.split('/')
151 153 intList = [int(x) for x in strList]
152 154 date = datetime.date(intList[0], intList[1], intList[2])
153 155
154 156 self.__formated_value = date
155 157
156 158 return self.__formated_value
157 159
158 160 if format == 'time':
159 161 strList = value.split(':')
160 162 intList = [int(x) for x in strList]
161 163 time = datetime.time(intList[0], intList[1], intList[2])
162 164
163 165 self.__formated_value = time
164 166
165 167 return self.__formated_value
166 168
167 169 if format == 'pairslist':
168 170 """
169 171 Example:
170 172 value = (0,1),(1,2)
171 173 """
172 174
173 175 new_value = ast.literal_eval(value)
174 176
175 177 if type(new_value) not in (tuple, list):
176 178 raise ValueError, "%s has to be a tuple or list of pairs" %value
177 179
178 180 if type(new_value[0]) not in (tuple, list):
179 181 if len(new_value) != 2:
180 182 raise ValueError, "%s has to be a tuple or list of pairs" %value
181 183 new_value = [new_value]
182 184
183 185 for thisPair in new_value:
184 186 if len(thisPair) != 2:
185 187 raise ValueError, "%s has to be a tuple or list of pairs" %value
186 188
187 189 self.__formated_value = new_value
188 190
189 191 return self.__formated_value
190 192
191 193 if format == 'multilist':
192 194 """
193 195 Example:
194 196 value = (0,1,2),(3,4,5)
195 197 """
196 198 multiList = ast.literal_eval(value)
197 199
198 200 if type(multiList[0]) == int:
199 201 multiList = ast.literal_eval("(" + value + ")")
200 202
201 203 self.__formated_value = multiList
202 204
203 205 return self.__formated_value
204 206
205 207 if format == 'bool':
206 208 value = int(value)
207 209
208 210 if format == 'int':
209 211 value = float(value)
210 212
211 213 format_func = eval(format)
212 214
213 215 self.__formated_value = format_func(value)
214 216
215 217 return self.__formated_value
216 218
217 219 def updateId(self, new_id):
218 220
219 221 self.id = str(new_id)
220 222
221 223 def setup(self, id, name, value, format='str'):
222 224 self.id = str(id)
223 225 self.name = name
224 226 if format == 'obj':
225 227 self.value = value
226 228 else:
227 229 self.value = str(value)
228 230 self.format = str.lower(format)
229 231
230 232 self.getValue()
231 233
232 234 return 1
233 235
234 236 def update(self, name, value, format='str'):
235 237
236 238 self.name = name
237 239 self.value = str(value)
238 240 self.format = format
239 241
240 242 def makeXml(self, opElement):
241 243 if self.name not in ('queue',):
242 244 parmElement = SubElement(opElement, self.ELEMENTNAME)
243 245 parmElement.set('id', str(self.id))
244 246 parmElement.set('name', self.name)
245 247 parmElement.set('value', self.value)
246 248 parmElement.set('format', self.format)
247 249
248 250 def readXml(self, parmElement):
249 251
250 252 self.id = parmElement.get('id')
251 253 self.name = parmElement.get('name')
252 254 self.value = parmElement.get('value')
253 255 self.format = str.lower(parmElement.get('format'))
254 256
255 257 #Compatible with old signal chain version
256 258 if self.format == 'int' and self.name == 'idfigure':
257 259 self.name = 'id'
258 260
259 261 def printattr(self):
260 262
261 263 print "Parameter[%s]: name = %s, value = %s, format = %s" %(self.id, self.name, self.value, self.format)
262 264
263 265 class OperationConf():
264 266
265 267 id = None
266 268 name = None
267 269 priority = None
268 270 type = None
269 271
270 272 parmConfObjList = []
271 273
272 274 ELEMENTNAME = 'Operation'
273 275
274 276 def __init__(self):
275 277
276 278 self.id = '0'
277 279 self.name = None
278 280 self.priority = None
279 281 self.type = 'self'
280 282
281 283
282 284 def __getNewId(self):
283 285
284 286 return int(self.id)*10 + len(self.parmConfObjList) + 1
285 287
286 288 def updateId(self, new_id):
287 289
288 290 self.id = str(new_id)
289 291
290 292 n = 1
291 293 for parmObj in self.parmConfObjList:
292 294
293 295 idParm = str(int(new_id)*10 + n)
294 296 parmObj.updateId(idParm)
295 297
296 298 n += 1
297 299
298 300 def getElementName(self):
299 301
300 302 return self.ELEMENTNAME
301 303
302 304 def getParameterObjList(self):
303 305
304 306 return self.parmConfObjList
305 307
306 308 def getParameterObj(self, parameterName):
307 309
308 310 for parmConfObj in self.parmConfObjList:
309 311
310 312 if parmConfObj.name != parameterName:
311 313 continue
312 314
313 315 return parmConfObj
314 316
315 317 return None
316 318
317 319 def getParameterObjfromValue(self, parameterValue):
318 320
319 321 for parmConfObj in self.parmConfObjList:
320 322
321 323 if parmConfObj.getValue() != parameterValue:
322 324 continue
323 325
324 326 return parmConfObj.getValue()
325 327
326 328 return None
327 329
328 330 def getParameterValue(self, parameterName):
329 331
330 332 parameterObj = self.getParameterObj(parameterName)
331 333
332 334 # if not parameterObj:
333 335 # return None
334 336
335 337 value = parameterObj.getValue()
336 338
337 339 return value
338 340
339 341
340 342 def getKwargs(self):
341 343
342 344 kwargs = {}
343 345
344 346 for parmConfObj in self.parmConfObjList:
345 347 if self.name == 'run' and parmConfObj.name == 'datatype':
346 348 continue
347 349
348 350 kwargs[parmConfObj.name] = parmConfObj.getValue()
349 351
350 352 return kwargs
351 353
352 354 def setup(self, id, name, priority, type):
353 355
354 356 self.id = str(id)
355 357 self.name = name
356 358 self.type = type
357 359 self.priority = priority
358 360
359 361 self.parmConfObjList = []
360 362
361 363 def removeParameters(self):
362 364
363 365 for obj in self.parmConfObjList:
364 366 del obj
365 367
366 368 self.parmConfObjList = []
367 369
368 370 def addParameter(self, name, value, format='str'):
369 371
370 372 id = self.__getNewId()
371 373
372 374 parmConfObj = ParameterConf()
373 375 if not parmConfObj.setup(id, name, value, format):
374 376 return None
375 377
376 378 self.parmConfObjList.append(parmConfObj)
377 379
378 380 return parmConfObj
379 381
380 382 def changeParameter(self, name, value, format='str'):
381 383
382 384 parmConfObj = self.getParameterObj(name)
383 385 parmConfObj.update(name, value, format)
384 386
385 387 return parmConfObj
386 388
387 389 def makeXml(self, procUnitElement):
388 390
389 391 opElement = SubElement(procUnitElement, self.ELEMENTNAME)
390 392 opElement.set('id', str(self.id))
391 393 opElement.set('name', self.name)
392 394 opElement.set('type', self.type)
393 395 opElement.set('priority', str(self.priority))
394 396
395 397 for parmConfObj in self.parmConfObjList:
396 398 parmConfObj.makeXml(opElement)
397 399
398 400 def readXml(self, opElement):
399 401
400 402 self.id = opElement.get('id')
401 403 self.name = opElement.get('name')
402 404 self.type = opElement.get('type')
403 405 self.priority = opElement.get('priority')
404 406
405 407 #Compatible with old signal chain version
406 408 #Use of 'run' method instead 'init'
407 409 if self.type == 'self' and self.name == 'init':
408 410 self.name = 'run'
409 411
410 412 self.parmConfObjList = []
411 413
412 414 parmElementList = opElement.iter(ParameterConf().getElementName())
413 415
414 416 for parmElement in parmElementList:
415 417 parmConfObj = ParameterConf()
416 418 parmConfObj.readXml(parmElement)
417 419
418 420 #Compatible with old signal chain version
419 421 #If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER
420 422 if self.type != 'self' and self.name == 'Plot':
421 423 if parmConfObj.format == 'str' and parmConfObj.name == 'type':
422 424 self.name = parmConfObj.value
423 425 continue
424 426
425 427 self.parmConfObjList.append(parmConfObj)
426 428
427 429 def printattr(self):
428 430
429 431 print "%s[%s]: name = %s, type = %s, priority = %s" %(self.ELEMENTNAME,
430 432 self.id,
431 433 self.name,
432 434 self.type,
433 435 self.priority)
434 436
435 437 for parmConfObj in self.parmConfObjList:
436 438 parmConfObj.printattr()
437 439
438 440 def createObject(self, plotter_queue=None):
439 441
440 442
441 443 if self.type == 'self':
442 444 raise ValueError, "This operation type cannot be created"
443 445
444 446 if self.type == 'plotter':
445 447 #Plotter(plotter_name)
446 448 if not plotter_queue:
447 449 raise ValueError, "plotter_queue is not defined. Use:\nmyProject = Project()\nmyProject.setPlotterQueue(plotter_queue)"
448 450
449 451 opObj = Plotter(self.name, plotter_queue)
450 452
451 453 if self.type == 'external' or self.type == 'other':
452 454
453 455 className = eval(self.name)
454 456 kwargs = self.getKwargs()
455 457
456 458 opObj = className(**kwargs)
457 459
458 460 return opObj
459 461
460 462
461 463 class ProcUnitConf():
462 464
463 465 id = None
464 466 name = None
465 467 datatype = None
466 468 inputId = None
467 469 parentId = None
468 470
469 471 opConfObjList = []
470 472
471 473 procUnitObj = None
472 474 opObjList = []
473 475
474 476 ELEMENTNAME = 'ProcUnit'
475 477
476 478 def __init__(self):
477 479
478 480 self.id = None
479 481 self.datatype = None
480 482 self.name = None
481 483 self.inputId = None
482 484
483 485 self.opConfObjList = []
484 486
485 487 self.procUnitObj = None
486 488 self.opObjDict = {}
487 489
488 490 def __getPriority(self):
489 491
490 492 return len(self.opConfObjList)+1
491 493
492 494 def __getNewId(self):
493 495
494 496 return int(self.id)*10 + len(self.opConfObjList) + 1
495 497
496 498 def getElementName(self):
497 499
498 500 return self.ELEMENTNAME
499 501
500 502 def getId(self):
501 503
502 504 return self.id
503 505
504 506 def updateId(self, new_id, parentId=parentId):
505 507
506 508
507 509 new_id = int(parentId)*10 + (int(self.id) % 10)
508 510 new_inputId = int(parentId)*10 + (int(self.inputId) % 10)
509 511
510 512 #If this proc unit has not inputs
511 513 if self.inputId == '0':
512 514 new_inputId = 0
513 515
514 516 n = 1
515 517 for opConfObj in self.opConfObjList:
516 518
517 519 idOp = str(int(new_id)*10 + n)
518 520 opConfObj.updateId(idOp)
519 521
520 522 n += 1
521 523
522 524 self.parentId = str(parentId)
523 525 self.id = str(new_id)
524 526 self.inputId = str(new_inputId)
525 527
526 528
527 529 def getInputId(self):
528 530
529 531 return self.inputId
530 532
531 533 def getOperationObjList(self):
532 534
533 535 return self.opConfObjList
534 536
535 537 def getOperationObj(self, name=None):
536 538
537 539 for opConfObj in self.opConfObjList:
538 540
539 541 if opConfObj.name != name:
540 542 continue
541 543
542 544 return opConfObj
543 545
544 546 return None
545 547
546 548 def getOpObjfromParamValue(self, value=None):
547 549
548 550 for opConfObj in self.opConfObjList:
549 551 if opConfObj.getParameterObjfromValue(parameterValue=value) != value:
550 552 continue
551 553 return opConfObj
552 554 return None
553 555
554 556 def getProcUnitObj(self):
555 557
556 558 return self.procUnitObj
557 559
558 560 def setup(self, id, name, datatype, inputId, parentId=None):
559 561
560 562 #Compatible with old signal chain version
561 563 if datatype==None and name==None:
562 564 raise ValueError, "datatype or name should be defined"
563 565
564 566 if name==None:
565 567 if 'Proc' in datatype:
566 568 name = datatype
567 569 else:
568 570 name = '%sProc' %(datatype)
569 571
570 572 if datatype==None:
571 573 datatype = name.replace('Proc','')
572 574
573 575 self.id = str(id)
574 576 self.name = name
575 577 self.datatype = datatype
576 578 self.inputId = inputId
577 579 self.parentId = parentId
578 580
579 581 self.opConfObjList = []
580 582
581 583 self.addOperation(name='run', optype='self')
582 584
583 585 def removeOperations(self):
584 586
585 587 for obj in self.opConfObjList:
586 588 del obj
587 589
588 590 self.opConfObjList = []
589 591 self.addOperation(name='run')
590 592
591 593 def addParameter(self, **kwargs):
592 594 '''
593 595 Add parameters to "run" operation
594 596 '''
595 597 opObj = self.opConfObjList[0]
596 598
597 599 opObj.addParameter(**kwargs)
598 600
599 601 return opObj
600 602
601 603 def addOperation(self, name, optype='self'):
602 604
603 605 id = self.__getNewId()
604 606 priority = self.__getPriority()
605 607
606 608 opConfObj = OperationConf()
607 609 opConfObj.setup(id, name=name, priority=priority, type=optype)
608 610
609 611 self.opConfObjList.append(opConfObj)
610 612
611 613 return opConfObj
612 614
613 615 def makeXml(self, projectElement):
614 616
615 617 procUnitElement = SubElement(projectElement, self.ELEMENTNAME)
616 618 procUnitElement.set('id', str(self.id))
617 619 procUnitElement.set('name', self.name)
618 620 procUnitElement.set('datatype', self.datatype)
619 621 procUnitElement.set('inputId', str(self.inputId))
620 622
621 623 for opConfObj in self.opConfObjList:
622 624 opConfObj.makeXml(procUnitElement)
623 625
624 626 def readXml(self, upElement):
625 627
626 628 self.id = upElement.get('id')
627 629 self.name = upElement.get('name')
628 630 self.datatype = upElement.get('datatype')
629 631 self.inputId = upElement.get('inputId')
630 632
631 633 if self.ELEMENTNAME == "ReadUnit":
632 634 self.datatype = self.datatype.replace("Reader", "")
633 635
634 636 if self.ELEMENTNAME == "ProcUnit":
635 637 self.datatype = self.datatype.replace("Proc", "")
636 638
637 639 if self.inputId == 'None':
638 640 self.inputId = '0'
639 641
640 642 self.opConfObjList = []
641 643
642 644 opElementList = upElement.iter(OperationConf().getElementName())
643 645
644 646 for opElement in opElementList:
645 647 opConfObj = OperationConf()
646 648 opConfObj.readXml(opElement)
647 649 self.opConfObjList.append(opConfObj)
648 650
649 651 def printattr(self):
650 652
651 653 print "%s[%s]: name = %s, datatype = %s, inputId = %s" %(self.ELEMENTNAME,
652 654 self.id,
653 655 self.name,
654 656 self.datatype,
655 657 self.inputId)
656 658
657 659 for opConfObj in self.opConfObjList:
658 660 opConfObj.printattr()
659 661
660 662
661 663 def getKwargs(self):
662 664
663 665 opObj = self.opConfObjList[0]
664 666 kwargs = opObj.getKwargs()
665 667
666 668 return kwargs
667 669
668 670 def createObjects(self, plotter_queue=None):
669 671
670 672 className = eval(self.name)
671 673 kwargs = self.getKwargs()
672 674 procUnitObj = className(**kwargs)
673 675
674 676 for opConfObj in self.opConfObjList:
675 677
676 678 if opConfObj.type=='self' and self.name=='run':
677 679 continue
678 680 elif opConfObj.type=='self':
679 681 procUnitObj.addOperationKwargs(opConfObj.id, **opConfObj.getKwargs())
680 682 continue
681 683
682 684 opObj = opConfObj.createObject(plotter_queue)
683 685
684 686 self.opObjDict[opConfObj.id] = opObj
685 687
686 688 procUnitObj.addOperation(opObj, opConfObj.id)
687 689
688 690 self.procUnitObj = procUnitObj
689 691
690 692 return procUnitObj
691 693
692 694 def run(self):
693 695
694 696 is_ok = False
695 697
696 698 for opConfObj in self.opConfObjList:
697 699
698 700 kwargs = {}
699 701 for parmConfObj in opConfObj.getParameterObjList():
700 702 if opConfObj.name == 'run' and parmConfObj.name == 'datatype':
701 703 continue
702 704
703 705 kwargs[parmConfObj.name] = parmConfObj.getValue()
704 706
705 707 #ini = time.time()
706 708
707 709 #print "\tRunning the '%s' operation with %s" %(opConfObj.name, opConfObj.id)
708 710 sts = self.procUnitObj.call(opType = opConfObj.type,
709 711 opName = opConfObj.name,
710 712 opId = opConfObj.id,
711 713 )
712 714
713 715 # total_time = time.time() - ini
714 716 #
715 717 # if total_time > 0.002:
716 718 # print "%s::%s took %f seconds" %(self.name, opConfObj.name, total_time)
717 719
718 720 is_ok = is_ok or sts
719 721
720 722 return is_ok
721 723
722 724 def close(self):
723 725
724 726 for opConfObj in self.opConfObjList:
725 727 if opConfObj.type == 'self':
726 728 continue
727 729
728 730 opObj = self.procUnitObj.getOperationObj(opConfObj.id)
729 731 opObj.close()
730 732
731 733 self.procUnitObj.close()
732 734
733 735 return
734 736
735 737 class ReadUnitConf(ProcUnitConf):
736 738
737 739 path = None
738 740 startDate = None
739 741 endDate = None
740 742 startTime = None
741 743 endTime = None
742 744
743 745 ELEMENTNAME = 'ReadUnit'
744 746
745 747 def __init__(self):
746 748
747 749 self.id = None
748 750 self.datatype = None
749 751 self.name = None
750 752 self.inputId = None
751 753
752 754 self.parentId = None
753 755
754 756 self.opConfObjList = []
755 757 self.opObjList = []
756 758
757 759 def getElementName(self):
758 760
759 761 return self.ELEMENTNAME
760 762
761 763 def setup(self, id, name, datatype, path='', startDate="", endDate="", startTime="",
762 764 endTime="", parentId=None, queue=None, server=None, **kwargs):
763 765
764 766 #Compatible with old signal chain version
765 767 if datatype==None and name==None:
766 768 raise ValueError, "datatype or name should be defined"
767 769
768 770 if name==None:
769 771 if 'Reader' in datatype:
770 772 name = datatype
771 773 else:
772 774 name = '%sReader' %(datatype)
773 775 if datatype==None:
774 776 datatype = name.replace('Reader','')
775 777
776 778 self.id = id
777 779 self.name = name
778 780 self.datatype = datatype
779 781 if path != '':
780 782 self.path = os.path.abspath(path)
781 783 self.startDate = startDate
782 784 self.endDate = endDate
783 785 self.startTime = startTime
784 786 self.endTime = endTime
785 787
786 788 self.inputId = '0'
787 789 self.parentId = parentId
788 790 self.queue = queue
789 791 self.server = server
790 792 self.addRunOperation(**kwargs)
791 793
792 794 def update(self, datatype, path, startDate, endDate, startTime, endTime, parentId=None, name=None, **kwargs):
793 795
794 796 #Compatible with old signal chain version
795 797 if datatype==None and name==None:
796 798 raise ValueError, "datatype or name should be defined"
797 799
798 800 if name==None:
799 801 if 'Reader' in datatype:
800 802 name = datatype
801 803 else:
802 804 name = '%sReader' %(datatype)
803 805
804 806 if datatype==None:
805 807 datatype = name.replace('Reader','')
806 808
807 809 self.datatype = datatype
808 810 self.name = name
809 811 self.path = path
810 812 self.startDate = startDate
811 813 self.endDate = endDate
812 814 self.startTime = startTime
813 815 self.endTime = endTime
814 816
815 817 self.inputId = '0'
816 818 self.parentId = parentId
817 819
818 820 self.updateRunOperation(**kwargs)
819 821
820 822 def removeOperations(self):
821 823
822 824 for obj in self.opConfObjList:
823 825 del obj
824 826
825 827 self.opConfObjList = []
826 828
827 829 def addRunOperation(self, **kwargs):
828 830
829 831 opObj = self.addOperation(name = 'run', optype = 'self')
830 832
831 833 if self.server is None:
832 834 opObj.addParameter(name='datatype' , value=self.datatype, format='str')
833 835 opObj.addParameter(name='path' , value=self.path, format='str')
834 836 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
835 837 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
836 838 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
837 839 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
838 840 opObj.addParameter(name='queue' , value=self.queue, format='obj')
839 841 for key, value in kwargs.items():
840 842 opObj.addParameter(name=key, value=value, format=type(value).__name__)
841 843 else:
842 844 opObj.addParameter(name='server' , value=self.server, format='str')
843 845
844 846
845 847 return opObj
846 848
847 849 def updateRunOperation(self, **kwargs):
848 850
849 851 opObj = self.getOperationObj(name = 'run')
850 852 opObj.removeParameters()
851 853
852 854 opObj.addParameter(name='datatype' , value=self.datatype, format='str')
853 855 opObj.addParameter(name='path' , value=self.path, format='str')
854 856 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
855 857 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
856 858 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
857 859 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
858 860
859 861 for key, value in kwargs.items():
860 862 opObj.addParameter(name=key, value=value, format=type(value).__name__)
861 863
862 864 return opObj
863 865
864 866 # def makeXml(self, projectElement):
865 867 #
866 868 # procUnitElement = SubElement(projectElement, self.ELEMENTNAME)
867 869 # procUnitElement.set('id', str(self.id))
868 870 # procUnitElement.set('name', self.name)
869 871 # procUnitElement.set('datatype', self.datatype)
870 872 # procUnitElement.set('inputId', str(self.inputId))
871 873 #
872 874 # for opConfObj in self.opConfObjList:
873 875 # opConfObj.makeXml(procUnitElement)
874 876
875 877 def readXml(self, upElement):
876 878
877 879 self.id = upElement.get('id')
878 880 self.name = upElement.get('name')
879 881 self.datatype = upElement.get('datatype')
880 882 self.inputId = upElement.get('inputId')
881 883
882 884 if self.ELEMENTNAME == "ReadUnit":
883 885 self.datatype = self.datatype.replace("Reader", "")
884 886
885 887 if self.inputId == 'None':
886 888 self.inputId = '0'
887 889
888 890 self.opConfObjList = []
889 891
890 892 opElementList = upElement.iter(OperationConf().getElementName())
891 893
892 894 for opElement in opElementList:
893 895 opConfObj = OperationConf()
894 896 opConfObj.readXml(opElement)
895 897 self.opConfObjList.append(opConfObj)
896 898
897 899 if opConfObj.name == 'run':
898 900 self.path = opConfObj.getParameterValue('path')
899 901 self.startDate = opConfObj.getParameterValue('startDate')
900 902 self.endDate = opConfObj.getParameterValue('endDate')
901 903 self.startTime = opConfObj.getParameterValue('startTime')
902 904 self.endTime = opConfObj.getParameterValue('endTime')
903 905
904 906 class Project():
905 907
906 908 id = None
907 909 name = None
908 910 description = None
909 911 filename = None
910 912
911 913 procUnitConfObjDict = None
912 914
913 915 ELEMENTNAME = 'Project'
914 916
915 917 plotterQueue = None
916 918
917 919 def __init__(self, plotter_queue=None):
918 920
919 921 self.id = None
920 922 self.name = None
921 923 self.description = None
922 924
923 925 self.plotterQueue = plotter_queue
924 926
925 927 self.procUnitConfObjDict = {}
926 928
927 929 def __getNewId(self):
928 930
929 931 idList = self.procUnitConfObjDict.keys()
930 932
931 933 id = int(self.id)*10
932 934
933 935 while True:
934 936 id += 1
935 937
936 938 if str(id) in idList:
937 939 continue
938 940
939 941 break
940 942
941 943 return str(id)
942 944
943 945 def getElementName(self):
944 946
945 947 return self.ELEMENTNAME
946 948
947 949 def getId(self):
948 950
949 951 return self.id
950 952
951 953 def updateId(self, new_id):
952 954
953 955 self.id = str(new_id)
954 956
955 957 keyList = self.procUnitConfObjDict.keys()
956 958 keyList.sort()
957 959
958 960 n = 1
959 961 newProcUnitConfObjDict = {}
960 962
961 963 for procKey in keyList:
962 964
963 965 procUnitConfObj = self.procUnitConfObjDict[procKey]
964 966 idProcUnit = str(int(self.id)*10 + n)
965 967 procUnitConfObj.updateId(idProcUnit, parentId = self.id)
966 968
967 969 newProcUnitConfObjDict[idProcUnit] = procUnitConfObj
968 970 n += 1
969 971
970 972 self.procUnitConfObjDict = newProcUnitConfObjDict
971 973
972 974 def setup(self, id, name, description):
973 975
974 976 self.id = str(id)
975 977 self.name = name
976 978 self.description = description
977 979
978 980 def update(self, name, description):
979 981
980 982 self.name = name
981 983 self.description = description
982 984
983 985 def addReadUnit(self, id=None, datatype=None, name=None, **kwargs):
984 986
985 987 if id is None:
986 988 idReadUnit = self.__getNewId()
987 989 else:
988 990 idReadUnit = str(id)
989 991
990 992 readUnitConfObj = ReadUnitConf()
991 993 readUnitConfObj.setup(idReadUnit, name, datatype, parentId=self.id, **kwargs)
992 994
993 995 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
994 996
995 997 return readUnitConfObj
996 998
997 999 def addProcUnit(self, inputId='0', datatype=None, name=None):
998 1000
999 1001 idProcUnit = self.__getNewId()
1000 1002
1001 1003 procUnitConfObj = ProcUnitConf()
1002 1004 procUnitConfObj.setup(idProcUnit, name, datatype, inputId, parentId=self.id)
1003 1005
1004 1006 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
1005 1007
1006 1008 return procUnitConfObj
1007 1009
1008 1010 def removeProcUnit(self, id):
1009 1011
1010 1012 if id in self.procUnitConfObjDict.keys():
1011 1013 self.procUnitConfObjDict.pop(id)
1012 1014
1013 1015 def getReadUnitId(self):
1014 1016
1015 1017 readUnitConfObj = self.getReadUnitObj()
1016 1018
1017 1019 return readUnitConfObj.id
1018 1020
1019 1021 def getReadUnitObj(self):
1020 1022
1021 1023 for obj in self.procUnitConfObjDict.values():
1022 1024 if obj.getElementName() == "ReadUnit":
1023 1025 return obj
1024 1026
1025 1027 return None
1026 1028
1027 1029 def getProcUnitObj(self, id=None, name=None):
1028 1030
1029 1031 if id != None:
1030 1032 return self.procUnitConfObjDict[id]
1031 1033
1032 1034 if name != None:
1033 1035 return self.getProcUnitObjByName(name)
1034 1036
1035 1037 return None
1036 1038
1037 1039 def getProcUnitObjByName(self, name):
1038 1040
1039 1041 for obj in self.procUnitConfObjDict.values():
1040 1042 if obj.name == name:
1041 1043 return obj
1042 1044
1043 1045 return None
1044 1046
1045 1047 def procUnitItems(self):
1046 1048
1047 1049 return self.procUnitConfObjDict.items()
1048 1050
1049 1051 def makeXml(self):
1050 1052
1051 1053 projectElement = Element('Project')
1052 1054 projectElement.set('id', str(self.id))
1053 1055 projectElement.set('name', self.name)
1054 1056 projectElement.set('description', self.description)
1055 1057
1056 1058 for procUnitConfObj in self.procUnitConfObjDict.values():
1057 1059 procUnitConfObj.makeXml(projectElement)
1058 1060
1059 1061 self.projectElement = projectElement
1060 1062
1061 1063 def writeXml(self, filename=None):
1062 1064
1063 1065 if filename == None:
1064 1066 if self.filename:
1065 1067 filename = self.filename
1066 1068 else:
1067 1069 filename = "schain.xml"
1068 1070
1069 1071 if not filename:
1070 1072 print "filename has not been defined. Use setFilename(filename) for do it."
1071 1073 return 0
1072 1074
1073 1075 abs_file = os.path.abspath(filename)
1074 1076
1075 1077 if not os.access(os.path.dirname(abs_file), os.W_OK):
1076 1078 print "No write permission on %s" %os.path.dirname(abs_file)
1077 1079 return 0
1078 1080
1079 1081 if os.path.isfile(abs_file) and not(os.access(abs_file, os.W_OK)):
1080 1082 print "File %s already exists and it could not be overwriten" %abs_file
1081 1083 return 0
1082 1084
1083 1085 self.makeXml()
1084 1086
1085 1087 ElementTree(self.projectElement).write(abs_file, method='xml')
1086 1088
1087 1089 self.filename = abs_file
1088 1090
1089 1091 return 1
1090 1092
1091 1093 def readXml(self, filename = None):
1092 1094
1093 1095 if not filename:
1094 1096 print "filename is not defined"
1095 1097 return 0
1096 1098
1097 1099 abs_file = os.path.abspath(filename)
1098 1100
1099 1101 if not os.path.isfile(abs_file):
1100 1102 print "%s file does not exist" %abs_file
1101 1103 return 0
1102 1104
1103 1105 self.projectElement = None
1104 1106 self.procUnitConfObjDict = {}
1105 1107
1106 1108 try:
1107 1109 self.projectElement = ElementTree().parse(abs_file)
1108 1110 except:
1109 1111 print "Error reading %s, verify file format" %filename
1110 1112 return 0
1111 1113
1112 1114 self.project = self.projectElement.tag
1113 1115
1114 1116 self.id = self.projectElement.get('id')
1115 1117 self.name = self.projectElement.get('name')
1116 1118 self.description = self.projectElement.get('description')
1117 1119
1118 1120 readUnitElementList = self.projectElement.iter(ReadUnitConf().getElementName())
1119 1121
1120 1122 for readUnitElement in readUnitElementList:
1121 1123 readUnitConfObj = ReadUnitConf()
1122 1124 readUnitConfObj.readXml(readUnitElement)
1123 1125
1124 1126 if readUnitConfObj.parentId == None:
1125 1127 readUnitConfObj.parentId = self.id
1126 1128
1127 1129 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
1128 1130
1129 1131 procUnitElementList = self.projectElement.iter(ProcUnitConf().getElementName())
1130 1132
1131 1133 for procUnitElement in procUnitElementList:
1132 1134 procUnitConfObj = ProcUnitConf()
1133 1135 procUnitConfObj.readXml(procUnitElement)
1134 1136
1135 1137 if procUnitConfObj.parentId == None:
1136 1138 procUnitConfObj.parentId = self.id
1137 1139
1138 1140 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
1139 1141
1140 1142 self.filename = abs_file
1141 1143
1142 1144 return 1
1143 1145
1144 1146 def printattr(self):
1145 1147
1146 1148 print "Project[%s]: name = %s, description = %s" %(self.id,
1147 1149 self.name,
1148 1150 self.description)
1149 1151
1150 1152 for procUnitConfObj in self.procUnitConfObjDict.values():
1151 1153 procUnitConfObj.printattr()
1152 1154
1153 1155 def createObjects(self):
1154 1156
1155 1157 for procUnitConfObj in self.procUnitConfObjDict.values():
1156 1158 procUnitConfObj.createObjects(self.plotterQueue)
1157 1159
1158 1160 def __connect(self, objIN, thisObj):
1159 1161
1160 1162 thisObj.setInput(objIN.getOutputObj())
1161 1163
1162 1164 def connectObjects(self):
1163 1165
1164 1166 for thisPUConfObj in self.procUnitConfObjDict.values():
1165 1167
1166 1168 inputId = thisPUConfObj.getInputId()
1167 1169
1168 1170 if int(inputId) == 0:
1169 1171 continue
1170 1172
1171 1173 #Get input object
1172 1174 puConfINObj = self.procUnitConfObjDict[inputId]
1173 1175 puObjIN = puConfINObj.getProcUnitObj()
1174 1176
1175 1177 #Get current object
1176 1178 thisPUObj = thisPUConfObj.getProcUnitObj()
1177 1179
1178 1180 self.__connect(puObjIN, thisPUObj)
1179 1181
1180 1182 def __handleError(self, procUnitConfObj, send_email=True):
1181 1183
1182 1184 import socket
1183 1185
1184 1186 err = traceback.format_exception(sys.exc_info()[0],
1185 1187 sys.exc_info()[1],
1186 1188 sys.exc_info()[2])
1187 1189
1188 1190 print "***** Error occurred in %s *****" %(procUnitConfObj.name)
1189 1191 print "***** %s" %err[-1]
1190 1192
1191 1193 message = "".join(err)
1192 1194
1193 1195 sys.stderr.write(message)
1194 1196
1195 1197 if not send_email:
1196 1198 return
1197 1199
1198 1200 subject = "SChain v%s: Error running %s\n" %(schainpy.__version__, procUnitConfObj.name)
1199 1201
1200 1202 subtitle = "%s: %s\n" %(procUnitConfObj.getElementName() ,procUnitConfObj.name)
1201 1203 subtitle += "Hostname: %s\n" %socket.gethostbyname(socket.gethostname())
1202 1204 subtitle += "Working directory: %s\n" %os.path.abspath("./")
1203 1205 subtitle += "Configuration file: %s\n" %self.filename
1204 1206 subtitle += "Time: %s\n" %str(datetime.datetime.now())
1205 1207
1206 1208 readUnitConfObj = self.getReadUnitObj()
1207 1209 if readUnitConfObj:
1208 1210 subtitle += "\nInput parameters:\n"
1209 1211 subtitle += "[Data path = %s]\n" %readUnitConfObj.path
1210 1212 subtitle += "[Data type = %s]\n" %readUnitConfObj.datatype
1211 1213 subtitle += "[Start date = %s]\n" %readUnitConfObj.startDate
1212 1214 subtitle += "[End date = %s]\n" %readUnitConfObj.endDate
1213 1215 subtitle += "[Start time = %s]\n" %readUnitConfObj.startTime
1214 1216 subtitle += "[End time = %s]\n" %readUnitConfObj.endTime
1215 1217
1216 1218 adminObj = schainpy.admin.SchainNotify()
1217 1219 adminObj.sendAlert(message=message,
1218 1220 subject=subject,
1219 1221 subtitle=subtitle,
1220 1222 filename=self.filename)
1221 1223
1222 1224 def isPaused(self):
1223 1225 return 0
1224 1226
1225 1227 def isStopped(self):
1226 1228 return 0
1227 1229
1228 1230 def runController(self):
1229 1231 """
1230 1232 returns 0 when this process has been stopped, 1 otherwise
1231 1233 """
1232 1234
1233 1235 if self.isPaused():
1234 1236 print "Process suspended"
1235 1237
1236 1238 while True:
1237 1239 sleep(0.1)
1238 1240
1239 1241 if not self.isPaused():
1240 1242 break
1241 1243
1242 1244 if self.isStopped():
1243 1245 break
1244 1246
1245 1247 print "Process reinitialized"
1246 1248
1247 1249 if self.isStopped():
1248 1250 print "Process stopped"
1249 1251 return 0
1250 1252
1251 1253 return 1
1252 1254
1253 1255 def setFilename(self, filename):
1254 1256
1255 1257 self.filename = filename
1256 1258
1257 1259 def setPlotterQueue(self, plotter_queue):
1258 1260
1259 1261 raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class"
1260 1262
1261 1263 def getPlotterQueue(self):
1262 1264
1263 1265 raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class"
1264 1266
1265 1267 def useExternalPlotter(self):
1266 1268
1267 1269 raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class"
1268 1270
1269 1271 def run(self):
1270 1272
1271 1273 print
1272 1274 print "*"*60
1273 1275 print " Starting SIGNAL CHAIN PROCESSING v%s " %schainpy.__version__
1274 1276 print "*"*60
1275 1277 print
1276 1278
1277 1279 keyList = self.procUnitConfObjDict.keys()
1278 1280 keyList.sort()
1279 1281
1280 1282 while(True):
1281 1283
1282 1284 is_ok = False
1283 1285
1284 1286 for procKey in keyList:
1285 1287 # print "Running the '%s' process with %s" %(procUnitConfObj.name, procUnitConfObj.id)
1286 1288
1287 1289 procUnitConfObj = self.procUnitConfObjDict[procKey]
1288 1290
1289 1291 try:
1290 1292 sts = procUnitConfObj.run()
1291 1293 is_ok = is_ok or sts
1292 1294 except KeyboardInterrupt:
1293 1295 is_ok = False
1294 1296 break
1295 1297 except ValueError, e:
1296 1298 sleep(0.5)
1297 1299 self.__handleError(procUnitConfObj, send_email=True)
1298 1300 is_ok = False
1299 1301 break
1300 1302 except:
1301 1303 sleep(0.5)
1302 1304 self.__handleError(procUnitConfObj)
1303 1305 is_ok = False
1304 1306 break
1305 1307
1306 1308 #If every process unit finished so end process
1307 1309 if not(is_ok):
1308 1310 # print "Every process unit have finished"
1309 1311 break
1310 1312
1311 1313 if not self.runController():
1312 1314 break
1313 1315
1314 1316 #Closing every process
1315 1317 for procKey in keyList:
1316 1318 procUnitConfObj = self.procUnitConfObjDict[procKey]
1317 1319 procUnitConfObj.close()
1318 1320
1319 1321 print "Process finished"
1320 1322
1321 1323 def start(self, filename=None):
1322 1324
1323 1325 self.writeXml(filename)
1324 1326 self.createObjects()
1325 1327 self.connectObjects()
1326 1328 self.run()
@@ -1,775 +1,955
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 import glob
9 10 matplotlib.use('TkAgg')
10 11 import matplotlib.pyplot as plt
11 12 from mpl_toolkits.axes_grid1 import make_axes_locatable
12 13 from matplotlib.ticker import FuncFormatter, LinearLocator
13 14 from multiprocessing import Process
14 15
15 16 from schainpy.model.proc.jroproc_base import Operation
16 17
17 18 plt.ion()
18 19
19 20 func = lambda x, pos: ('%s') %(datetime.datetime.fromtimestamp(x).strftime('%H:%M'))
20 21
21 22 d1970 = datetime.datetime(1970,1,1)
22 23
23 24 class PlotData(Operation, Process):
24 25
25 26 CODE = 'Figure'
26 27 colormap = 'jro'
27 28 CONFLATE = False
28 29 __MAXNUMX = 80
29 30 __missing = 1E30
30 31
31 32 def __init__(self, **kwargs):
32 33
33 34 Operation.__init__(self, plot=True, **kwargs)
34 35 Process.__init__(self)
35 36 self.kwargs['code'] = self.CODE
36 37 self.mp = False
37 38 self.dataOut = None
38 39 self.isConfig = False
39 40 self.figure = None
40 41 self.axes = []
41 42 self.localtime = kwargs.pop('localtime', True)
42 43 self.show = kwargs.get('show', True)
43 44 self.save = kwargs.get('save', False)
44 45 self.colormap = kwargs.get('colormap', self.colormap)
45 46 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
46 47 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
47 48 self.showprofile = kwargs.get('showprofile', True)
48 49 self.title = kwargs.get('wintitle', '')
49 50 self.xaxis = kwargs.get('xaxis', 'frequency')
50 51 self.zmin = kwargs.get('zmin', None)
51 52 self.zmax = kwargs.get('zmax', None)
52 53 self.xmin = kwargs.get('xmin', None)
53 54 self.xmax = kwargs.get('xmax', None)
54 55 self.xrange = kwargs.get('xrange', 24)
55 56 self.ymin = kwargs.get('ymin', None)
56 57 self.ymax = kwargs.get('ymax', None)
57 58 self.__MAXNUMY = kwargs.get('decimation', 80)
58 59 self.throttle_value = 5
59 60 self.times = []
60 61 #self.interactive = self.kwargs['parent']
61 62
63 '''
64 this new parameter is created to plot data from varius channels at different figures
65 1. crear una lista de figuras donde se puedan plotear las figuras,
66 2. dar las opciones de configuracion a cada figura, estas opciones son iguales para ambas figuras
67 3. probar?
68 '''
69 self.ind_plt_ch = kwargs.get('ind_plt_ch', False)
70 self.figurelist = None
71
62 72
63 73 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
64 74
65 75 if x_buffer.shape[0] < 2:
66 76 return x_buffer, y_buffer, z_buffer
67 77
68 78 deltas = x_buffer[1:] - x_buffer[0:-1]
69 79 x_median = np.median(deltas)
70 80
71 81 index = np.where(deltas > 5*x_median)
72 82
73 83 if len(index[0]) != 0:
74 84 z_buffer[::, index[0], ::] = self.__missing
75 85 z_buffer = np.ma.masked_inside(z_buffer,
76 86 0.99*self.__missing,
77 87 1.01*self.__missing)
78 88
79 89 return x_buffer, y_buffer, z_buffer
80 90
81 91 def decimate(self):
82 92
83 93 # dx = int(len(self.x)/self.__MAXNUMX) + 1
84 94 dy = int(len(self.y)/self.__MAXNUMY) + 1
85 95
86 96 # x = self.x[::dx]
87 97 x = self.x
88 98 y = self.y[::dy]
89 99 z = self.z[::, ::, ::dy]
90 100
91 101 return x, y, z
92 102
103 '''
104 JM:
105 elimana las otras imagenes generadas debido a que lso workers no llegan en orden y le pueden
106 poner otro tiempo a la figura q no necesariamente es el ultimo.
107 Solo se realiza cuando termina la imagen.
108 Problemas:
109
110 File "/home/ci-81/workspace/schainv2.3/schainpy/model/graphics/jroplot_data.py", line 145, in __plot
111 for n, eachfigure in enumerate(self.figurelist):
112 TypeError: 'NoneType' object is not iterable
113
114 '''
115 def deleteanotherfiles(self):
116 figurenames=[]
117 if self.figurelist != None:
118 for n, eachfigure in enumerate(self.figurelist):
119 #add specific name for each channel in channelList
120 ghostfigname = os.path.join(self.save, '{}_{}_{}'.format(self.titles[n].replace(' ',''),self.CODE,
121 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d')))
122 figname = os.path.join(self.save, '{}_{}_{}.png'.format(self.titles[n].replace(' ',''),self.CODE,
123 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
124
125 for ghostfigure in glob.glob(ghostfigname+'*'): #ghostfigure will adopt all posible names of figures
126 if ghostfigure != figname:
127 os.remove(ghostfigure)
128 print 'Removing GhostFigures:' , figname
129 else :
130 '''Erasing ghost images for just on******************'''
131 ghostfigname = os.path.join(self.save, '{}_{}'.format(self.CODE,datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d')))
132 figname = os.path.join(self.save, '{}_{}.png'.format(self.CODE,datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
133 for ghostfigure in glob.glob(ghostfigname+'*'): #ghostfigure will adopt all posible names of figures
134 if ghostfigure != figname:
135 os.remove(ghostfigure)
136 print 'Removing GhostFigures:' , figname
137
93 138 def __plot(self):
94 139
95 140 print 'plotting...{}'.format(self.CODE)
96
97 if self.show:
98 self.figure.show()
99
100 self.plot()
101 plt.tight_layout()
102 self.figure.canvas.manager.set_window_title('{} {} - {}'.format(self.title, self.CODE.upper(),
141 if self.ind_plt_ch is False : #standard
142 if self.show:
143 self.figure.show()
144 self.plot()
145 plt.tight_layout()
146 self.figure.canvas.manager.set_window_title('{} {} - {}'.format(self.title, self.CODE.upper(),
103 147 datetime.datetime.fromtimestamp(self.max_time).strftime('%Y/%m/%d')))
148 else :
149 print 'len(self.figurelist): ',len(self.figurelist)
150 for n, eachfigure in enumerate(self.figurelist):
151 if self.show:
152 eachfigure.show()
153
154 self.plot()
155 eachfigure.tight_layout() # ajuste de cada subplot
156 eachfigure.canvas.manager.set_window_title('{} {} - {}'.format(self.title[n], self.CODE.upper(),
157 datetime.datetime.fromtimestamp(self.max_time).strftime('%Y/%m/%d')))
158
159 # if self.save:
160 # if self.ind_plt_ch is False : #standard
161 # figname = os.path.join(self.save, '{}_{}.png'.format(self.CODE,
162 # datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
163 # print 'Saving figure: {}'.format(figname)
164 # self.figure.savefig(figname)
165 # else :
166 # for n, eachfigure in enumerate(self.figurelist):
167 # #add specific name for each channel in channelList
168 # figname = os.path.join(self.save, '{}_{}_{}.png'.format(self.titles[n],self.CODE,
169 # datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
170 #
171 # print 'Saving figure: {}'.format(figname)
172 # eachfigure.savefig(figname)
173
174 if self.ind_plt_ch is False :
175 self.figure.canvas.draw()
176 else :
177 for eachfigure in self.figurelist:
178 eachfigure.canvas.draw()
104 179
105 180 if self.save:
106 figname = os.path.join(self.save, '{}_{}.png'.format(self.CODE,
107 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
108 print 'Saving figure: {}'.format(figname)
109 self.figure.savefig(figname)
181 if self.ind_plt_ch is False : #standard
182 figname = os.path.join(self.save, '{}_{}.png'.format(self.CODE,
183 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
184 print 'Saving figure: {}'.format(figname)
185 self.figure.savefig(figname)
186 else :
187 for n, eachfigure in enumerate(self.figurelist):
188 #add specific name for each channel in channelList
189 figname = os.path.join(self.save, '{}_{}_{}.png'.format(self.titles[n].replace(' ',''),self.CODE,
190 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
191
192 print 'Saving figure: {}'.format(figname)
193 eachfigure.savefig(figname)
110 194
111 self.figure.canvas.draw()
112 195
113 196 def plot(self):
114 197
115 198 print 'plotting...{}'.format(self.CODE.upper())
116 199 return
117 200
118 201 def run(self):
119 202
120 203 print '[Starting] {}'.format(self.name)
121 204
122 205 context = zmq.Context()
123 206 receiver = context.socket(zmq.SUB)
124 207 receiver.setsockopt(zmq.SUBSCRIBE, '')
125 208 receiver.setsockopt(zmq.CONFLATE, self.CONFLATE)
126
209
127 210 if 'server' in self.kwargs['parent']:
128 211 receiver.connect('ipc:///tmp/{}.plots'.format(self.kwargs['parent']['server']))
129 212 else:
130 213 receiver.connect("ipc:///tmp/zmq.plots")
131 214
132 215 seconds_passed = 0
133 216
134 217 while True:
135 218 try:
136 219 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)#flags=zmq.NOBLOCK
137 220 self.started = self.data['STARTED']
138 221 self.dataOut = self.data['dataOut']
139 222
140 223 if (len(self.times) < len(self.data['times']) and not self.started and self.data['ENDED']):
141 224 continue
142 225
143 226 self.times = self.data['times']
144 227 self.times.sort()
145 228 self.throttle_value = self.data['throttle']
146 229 self.min_time = self.times[0]
147 230 self.max_time = self.times[-1]
148 231
149 232 if self.isConfig is False:
150 233 print 'setting up'
151 234 self.setup()
152 235 self.isConfig = True
153 236 self.__plot()
154 237
155 238 if self.data['ENDED'] is True:
156 239 print '********GRAPHIC ENDED********'
157 240 self.ended = True
158 241 self.isConfig = False
159 242 self.__plot()
243 self.deleteanotherfiles() #CLPDG
160 244 elif seconds_passed >= self.data['throttle']:
161 245 print 'passed', seconds_passed
162 246 self.__plot()
163 247 seconds_passed = 0
164 248
165 249 except zmq.Again as e:
166 250 print 'Waiting for data...'
167 251 plt.pause(2)
168 252 seconds_passed += 2
169 253
170 254 def close(self):
171 255 if self.dataOut:
172 256 self.__plot()
173 257
174 258
175 259 class PlotSpectraData(PlotData):
176 260
177 261 CODE = 'spc'
178 262 colormap = 'jro'
179 263 CONFLATE = False
180 264
181 265 def setup(self):
182 266
183 267 ncolspan = 1
184 268 colspan = 1
185 269 self.ncols = int(numpy.sqrt(self.dataOut.nChannels)+0.9)
186 270 self.nrows = int(self.dataOut.nChannels*1./self.ncols + 0.9)
187 271 self.width = 3.6*self.ncols
188 272 self.height = 3.2*self.nrows
189 273 if self.showprofile:
190 274 ncolspan = 3
191 275 colspan = 2
192 276 self.width += 1.2*self.ncols
193 277
194 278 self.ylabel = 'Range [Km]'
195 279 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
196 280
197 281 if self.figure is None:
198 282 self.figure = plt.figure(figsize=(self.width, self.height),
199 283 edgecolor='k',
200 284 facecolor='w')
201 285 else:
202 286 self.figure.clf()
203 287
204 288 n = 0
205 289 for y in range(self.nrows):
206 290 for x in range(self.ncols):
207 291 if n >= self.dataOut.nChannels:
208 292 break
209 293 ax = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan), 1, colspan)
210 294 if self.showprofile:
211 295 ax.ax_profile = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan+colspan), 1, 1)
212 296
213 297 ax.firsttime = True
214 298 self.axes.append(ax)
215 299 n += 1
216 300
217 301 def plot(self):
218 302
219 303 if self.xaxis == "frequency":
220 304 x = self.dataOut.getFreqRange(1)/1000.
221 305 xlabel = "Frequency (kHz)"
222 306 elif self.xaxis == "time":
223 307 x = self.dataOut.getAcfRange(1)
224 308 xlabel = "Time (ms)"
225 309 else:
226 310 x = self.dataOut.getVelRange(1)
227 311 xlabel = "Velocity (m/s)"
228 312
229 313 y = self.dataOut.getHeiRange()
230 314 z = self.data[self.CODE]
231 315
232 316 for n, ax in enumerate(self.axes):
233
234 317 if ax.firsttime:
235 318 self.xmax = self.xmax if self.xmax else np.nanmax(x)
236 319 self.xmin = self.xmin if self.xmin else -self.xmax
237 320 self.ymin = self.ymin if self.ymin else np.nanmin(y)
238 321 self.ymax = self.ymax if self.ymax else np.nanmax(y)
239 322 self.zmin = self.zmin if self.zmin else np.nanmin(z)
240 323 self.zmax = self.zmax if self.zmax else np.nanmax(z)
241 324 ax.plot = ax.pcolormesh(x, y, z[n].T,
242 325 vmin=self.zmin,
243 326 vmax=self.zmax,
244 327 cmap=plt.get_cmap(self.colormap)
245 328 )
246 329 divider = make_axes_locatable(ax)
247 330 cax = divider.new_horizontal(size='3%', pad=0.05)
248 331 self.figure.add_axes(cax)
249 332 plt.colorbar(ax.plot, cax)
250 333
251 334 ax.set_xlim(self.xmin, self.xmax)
252 335 ax.set_ylim(self.ymin, self.ymax)
253 336
254 337 ax.set_ylabel(self.ylabel)
255 338 ax.set_xlabel(xlabel)
256 339
257 340 ax.firsttime = False
258 341
259 342 if self.showprofile:
260 343 ax.plot_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
261 344 ax.ax_profile.set_xlim(self.zmin, self.zmax)
262 345 ax.ax_profile.set_ylim(self.ymin, self.ymax)
263 346 ax.ax_profile.set_xlabel('dB')
264 347 ax.ax_profile.grid(b=True, axis='x')
265 348 ax.plot_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
266 349 color="k", linestyle="dashed", lw=2)[0]
267 350 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
268 351 else:
269 352 ax.plot.set_array(z[n].T.ravel())
270 353 if self.showprofile:
271 354 ax.plot_profile.set_data(self.data['rti'][self.max_time][n], y)
272 355 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
273 356
274 357 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
275 358 size=8)
276 359 self.saveTime = self.max_time
277 360
278 361
279 362 class PlotCrossSpectraData(PlotData):
280 363
281 364 CODE = 'cspc'
282 365 zmin_coh = None
283 366 zmax_coh = None
284 367 zmin_phase = None
285 368 zmax_phase = None
286 369 CONFLATE = False
287 370
288 371 def setup(self):
289 372
290 373 ncolspan = 1
291 374 colspan = 1
292 375 self.ncols = 2
293 376 self.nrows = self.dataOut.nPairs
294 377 self.width = 3.6*self.ncols
295 378 self.height = 3.2*self.nrows
296 379
297 380 self.ylabel = 'Range [Km]'
298 381 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
299 382
300 383 if self.figure is None:
301 384 self.figure = plt.figure(figsize=(self.width, self.height),
302 385 edgecolor='k',
303 386 facecolor='w')
304 387 else:
305 388 self.figure.clf()
306 389
307 390 for y in range(self.nrows):
308 391 for x in range(self.ncols):
309 392 ax = plt.subplot2grid((self.nrows, self.ncols), (y, x), 1, 1)
310 393 ax.firsttime = True
311 394 self.axes.append(ax)
312 395
313 396 def plot(self):
314 397
315 398 if self.xaxis == "frequency":
316 399 x = self.dataOut.getFreqRange(1)/1000.
317 400 xlabel = "Frequency (kHz)"
318 401 elif self.xaxis == "time":
319 402 x = self.dataOut.getAcfRange(1)
320 403 xlabel = "Time (ms)"
321 404 else:
322 405 x = self.dataOut.getVelRange(1)
323 406 xlabel = "Velocity (m/s)"
324 407
325 408 y = self.dataOut.getHeiRange()
326 409 z_coh = self.data['cspc_coh']
327 410 z_phase = self.data['cspc_phase']
328 411
329 412 for n in range(self.nrows):
330 413 ax = self.axes[2*n]
331 414 ax1 = self.axes[2*n+1]
332 415 if ax.firsttime:
333 416 self.xmax = self.xmax if self.xmax else np.nanmax(x)
334 417 self.xmin = self.xmin if self.xmin else -self.xmax
335 418 self.ymin = self.ymin if self.ymin else np.nanmin(y)
336 419 self.ymax = self.ymax if self.ymax else np.nanmax(y)
337 420 self.zmin_coh = self.zmin_coh if self.zmin_coh else 0.0
338 421 self.zmax_coh = self.zmax_coh if self.zmax_coh else 1.0
339 422 self.zmin_phase = self.zmin_phase if self.zmin_phase else -180
340 423 self.zmax_phase = self.zmax_phase if self.zmax_phase else 180
341 424
342 425 ax.plot = ax.pcolormesh(x, y, z_coh[n].T,
343 426 vmin=self.zmin_coh,
344 427 vmax=self.zmax_coh,
345 428 cmap=plt.get_cmap(self.colormap_coh)
346 429 )
347 430 divider = make_axes_locatable(ax)
348 431 cax = divider.new_horizontal(size='3%', pad=0.05)
349 432 self.figure.add_axes(cax)
350 433 plt.colorbar(ax.plot, cax)
351 434
352 435 ax.set_xlim(self.xmin, self.xmax)
353 436 ax.set_ylim(self.ymin, self.ymax)
354 437
355 438 ax.set_ylabel(self.ylabel)
356 439 ax.set_xlabel(xlabel)
357 440 ax.firsttime = False
358 441
359 442 ax1.plot = ax1.pcolormesh(x, y, z_phase[n].T,
360 443 vmin=self.zmin_phase,
361 444 vmax=self.zmax_phase,
362 445 cmap=plt.get_cmap(self.colormap_phase)
363 446 )
364 447 divider = make_axes_locatable(ax1)
365 448 cax = divider.new_horizontal(size='3%', pad=0.05)
366 449 self.figure.add_axes(cax)
367 450 plt.colorbar(ax1.plot, cax)
368 451
369 452 ax1.set_xlim(self.xmin, self.xmax)
370 453 ax1.set_ylim(self.ymin, self.ymax)
371 454
372 455 ax1.set_ylabel(self.ylabel)
373 456 ax1.set_xlabel(xlabel)
374 457 ax1.firsttime = False
375 458 else:
376 459 ax.plot.set_array(z_coh[n].T.ravel())
377 460 ax1.plot.set_array(z_phase[n].T.ravel())
378 461
379 462 ax.set_title('Coherence Ch{} * Ch{}'.format(self.dataOut.pairsList[n][0], self.dataOut.pairsList[n][1]), size=8)
380 463 ax1.set_title('Phase Ch{} * Ch{}'.format(self.dataOut.pairsList[n][0], self.dataOut.pairsList[n][1]), size=8)
381 464 self.saveTime = self.max_time
382 465
383 466
384 467 class PlotSpectraMeanData(PlotSpectraData):
385 468
386 469 CODE = 'spc_mean'
387 470 colormap = 'jet'
388 471
389 472 def plot(self):
390 473
391 474 if self.xaxis == "frequency":
392 475 x = self.dataOut.getFreqRange(1)/1000.
393 476 xlabel = "Frequency (kHz)"
394 477 elif self.xaxis == "time":
395 478 x = self.dataOut.getAcfRange(1)
396 479 xlabel = "Time (ms)"
397 480 else:
398 481 x = self.dataOut.getVelRange(1)
399 482 xlabel = "Velocity (m/s)"
400 483
401 484 y = self.dataOut.getHeiRange()
402 485 z = self.data['spc']
403 486 mean = self.data['mean'][self.max_time]
404 487
405 488 for n, ax in enumerate(self.axes):
406 489
407 490 if ax.firsttime:
408 491 self.xmax = self.xmax if self.xmax else np.nanmax(x)
409 492 self.xmin = self.xmin if self.xmin else -self.xmax
410 493 self.ymin = self.ymin if self.ymin else np.nanmin(y)
411 494 self.ymax = self.ymax if self.ymax else np.nanmax(y)
412 495 self.zmin = self.zmin if self.zmin else np.nanmin(z)
413 496 self.zmax = self.zmax if self.zmax else np.nanmax(z)
414 497 ax.plt = ax.pcolormesh(x, y, z[n].T,
415 498 vmin=self.zmin,
416 499 vmax=self.zmax,
417 500 cmap=plt.get_cmap(self.colormap)
418 501 )
419 502 ax.plt_dop = ax.plot(mean[n], y,
420 503 color='k')[0]
421 504
422 505 divider = make_axes_locatable(ax)
423 506 cax = divider.new_horizontal(size='3%', pad=0.05)
424 507 self.figure.add_axes(cax)
425 508 plt.colorbar(ax.plt, cax)
426 509
427 510 ax.set_xlim(self.xmin, self.xmax)
428 511 ax.set_ylim(self.ymin, self.ymax)
429 512
430 513 ax.set_ylabel(self.ylabel)
431 514 ax.set_xlabel(xlabel)
432 515
433 516 ax.firsttime = False
434 517
435 518 if self.showprofile:
436 519 ax.plt_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
437 520 ax.ax_profile.set_xlim(self.zmin, self.zmax)
438 521 ax.ax_profile.set_ylim(self.ymin, self.ymax)
439 522 ax.ax_profile.set_xlabel('dB')
440 523 ax.ax_profile.grid(b=True, axis='x')
441 524 ax.plt_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
442 525 color="k", linestyle="dashed", lw=2)[0]
443 526 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
444 527 else:
445 528 ax.plt.set_array(z[n].T.ravel())
446 529 ax.plt_dop.set_data(mean[n], y)
447 530 if self.showprofile:
448 531 ax.plt_profile.set_data(self.data['rti'][self.max_time][n], y)
449 532 ax.plt_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
450 533
451 534 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
452 535 size=8)
453 536 self.saveTime = self.max_time
454 537
455 538
456 539 class PlotRTIData(PlotData):
457 540
458 541 CODE = 'rti'
459 542 colormap = 'jro'
460 543
461 544 def setup(self):
462 545 self.ncols = 1
463 546 self.nrows = self.dataOut.nChannels
464 547 self.width = 10
465 self.height = 2.2*self.nrows if self.nrows<6 else 12
548 #TODO : arreglar la altura de la figura, esta hardcodeada.
549 #Se arreglo, testear!
550 if self.ind_plt_ch:
551 self.height = 3.2#*self.nrows if self.nrows<6 else 12
552 else:
553 self.height = 2.2*self.nrows if self.nrows<6 else 12
554
555 '''
466 556 if self.nrows==1:
467 557 self.height += 1
558 '''
468 559 self.ylabel = 'Range [Km]'
469 560 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
470 561
471 if self.figure is None:
472 self.figure = plt.figure(figsize=(self.width, self.height),
473 edgecolor='k',
474 facecolor='w')
475 else:
476 self.figure.clf()
477 self.axes = []
478
479 for n in range(self.nrows):
480 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
481 ax.firsttime = True
482 self.axes.append(ax)
483
484 def plot(self):
485
486 self.x = np.array(self.times)
487 self.y = self.dataOut.getHeiRange()
488 self.z = []
562 '''
563 Logica:
564 1) Si la variable ind_plt_ch es True, va a crear mas de 1 figura
565 2) guardamos "Figures" en una lista y "axes" en otra, quizas se deberia guardar el
566 axis dentro de "Figures" como un diccionario.
567 '''
568 if self.ind_plt_ch is False: #standard mode
569
570 if self.figure is None: #solo para la priemra vez
571 self.figure = plt.figure(figsize=(self.width, self.height),
572 edgecolor='k',
573 facecolor='w')
574 else:
575 self.figure.clf()
576 self.axes = []
489 577
490 for ch in range(self.nrows):
491 self.z.append([self.data[self.CODE][t][ch] for t in self.times])
492 578
493 self.z = np.array(self.z)
494 for n, ax in enumerate(self.axes):
495 x, y, z = self.fill_gaps(*self.decimate())
496 xmin = self.min_time
497 xmax = xmin+self.xrange*60*60
498 self.zmin = self.zmin if self.zmin else np.min(self.z)
499 self.zmax = self.zmax if self.zmax else np.max(self.z)
500 if ax.firsttime:
501 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
502 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
503 plot = ax.pcolormesh(x, y, z[n].T,
504 vmin=self.zmin,
505 vmax=self.zmax,
506 cmap=plt.get_cmap(self.colormap)
507 )
508 divider = make_axes_locatable(ax)
509 cax = divider.new_horizontal(size='2%', pad=0.05)
510 self.figure.add_axes(cax)
511 plt.colorbar(plot, cax)
512 ax.set_ylim(self.ymin, self.ymax)
513
514 ax.xaxis.set_major_formatter(FuncFormatter(func))
515 ax.xaxis.set_major_locator(LinearLocator(6))
579 for n in range(self.nrows):
580 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
581 #ax = self.figure(n+1)
582 ax.firsttime = True
583 self.axes.append(ax)
516 584
517 ax.set_ylabel(self.ylabel)
585 else : #append one figure foreach channel in channelList
586 if self.figurelist == None:
587 self.figurelist = []
588 for n in range(self.nrows):
589 self.figure = plt.figure(figsize=(self.width, self.height),
590 edgecolor='k',
591 facecolor='w')
592 #add always one subplot
593 self.figurelist.append(self.figure)
594
595 else : # cada dia nuevo limpia el axes, pero mantiene el figure
596 for eachfigure in self.figurelist:
597 eachfigure.clf() # eliminaria todas las figuras de la lista?
598 self.axes = []
599
600 for eachfigure in self.figurelist:
601 ax = eachfigure.add_subplot(1,1,1) #solo 1 axis por figura
602 #ax = self.figure(n+1)
603 ax.firsttime = True
604 #Cada figura tiene un distinto puntero
605 self.axes.append(ax)
606 #plt.close(eachfigure)
518 607
519 # if self.xmin is None:
520 # xmin = self.min_time
521 # else:
522 # xmin = (datetime.datetime.combine(self.dataOut.datatime.date(),
523 # datetime.time(self.xmin, 0, 0))-d1970).total_seconds()
524 608
525 ax.set_xlim(xmin, xmax)
526 ax.firsttime = False
527 else:
528 ax.collections.remove(ax.collections[0])
529 ax.set_xlim(xmin, xmax)
530 plot = ax.pcolormesh(x, y, z[n].T,
531 vmin=self.zmin,
532 vmax=self.zmax,
533 cmap=plt.get_cmap(self.colormap)
534 )
535 ax.set_title('{} {}'.format(self.titles[n],
536 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
537 size=8)
609 def plot(self):
538 610
539 self.saveTime = self.min_time
611 if self.ind_plt_ch is False: #standard mode
612 self.x = np.array(self.times)
613 self.y = self.dataOut.getHeiRange()
614 self.z = []
615
616 for ch in range(self.nrows):
617 self.z.append([self.data[self.CODE][t][ch] for t in self.times])
618
619 self.z = np.array(self.z)
620 for n, ax in enumerate(self.axes):
621 x, y, z = self.fill_gaps(*self.decimate())
622 xmin = self.min_time
623 xmax = xmin+self.xrange*60*60
624 self.zmin = self.zmin if self.zmin else np.min(self.z)
625 self.zmax = self.zmax if self.zmax else np.max(self.z)
626 if ax.firsttime:
627 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
628 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
629 plot = ax.pcolormesh(x, y, z[n].T,
630 vmin=self.zmin,
631 vmax=self.zmax,
632 cmap=plt.get_cmap(self.colormap)
633 )
634 divider = make_axes_locatable(ax)
635 cax = divider.new_horizontal(size='2%', pad=0.05)
636 self.figure.add_axes(cax)
637 plt.colorbar(plot, cax)
638 ax.set_ylim(self.ymin, self.ymax)
639 ax.xaxis.set_major_formatter(FuncFormatter(func))
640 ax.xaxis.set_major_locator(LinearLocator(6))
641 ax.set_ylabel(self.ylabel)
642 if self.xmin is None:
643 xmin = self.min_time
644 else:
645 xmin = (datetime.datetime.combine(self.dataOut.datatime.date(),
646 datetime.time(self.xmin, 0, 0))-d1970).total_seconds()
647 ax.set_xlim(xmin, xmax)
648 ax.firsttime = False
649 else:
650 ax.collections.remove(ax.collections[0])
651 ax.set_xlim(xmin, xmax)
652 plot = ax.pcolormesh(x, y, z[n].T,
653 vmin=self.zmin,
654 vmax=self.zmax,
655 cmap=plt.get_cmap(self.colormap)
656 )
657 ax.set_title('{} {}'.format(self.titles[n],
658 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
659 size=8)
660
661 self.saveTime = self.min_time
662 else :
663 self.x = np.array(self.times)
664 self.y = self.dataOut.getHeiRange()
665 self.z = []
666
667 for ch in range(self.nrows):
668 self.z.append([self.data[self.CODE][t][ch] for t in self.times])
669
670 self.z = np.array(self.z)
671 for n, eachfigure in enumerate(self.figurelist): #estaba ax in axes
672
673 x, y, z = self.fill_gaps(*self.decimate())
674 xmin = self.min_time
675 xmax = xmin+self.xrange*60*60
676 self.zmin = self.zmin if self.zmin else np.min(self.z)
677 self.zmax = self.zmax if self.zmax else np.max(self.z)
678 if self.axes[n].firsttime:
679 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
680 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
681 plot = self.axes[n].pcolormesh(x, y, z[n].T,
682 vmin=self.zmin,
683 vmax=self.zmax,
684 cmap=plt.get_cmap(self.colormap)
685 )
686 divider = make_axes_locatable(self.axes[n])
687 cax = divider.new_horizontal(size='2%', pad=0.05)
688 eachfigure.add_axes(cax)
689 #self.figure2.add_axes(cax)
690 plt.colorbar(plot, cax)
691 self.axes[n].set_ylim(self.ymin, self.ymax)
692
693 self.axes[n].xaxis.set_major_formatter(FuncFormatter(func))
694 self.axes[n].xaxis.set_major_locator(LinearLocator(6))
695
696 self.axes[n].set_ylabel(self.ylabel)
697
698 if self.xmin is None:
699 xmin = self.min_time
700 else:
701 xmin = (datetime.datetime.combine(self.dataOut.datatime.date(),
702 datetime.time(self.xmin, 0, 0))-d1970).total_seconds()
703
704 self.axes[n].set_xlim(xmin, xmax)
705 self.axes[n].firsttime = False
706 else:
707 self.axes[n].collections.remove(self.axes[n].collections[0])
708 self.axes[n].set_xlim(xmin, xmax)
709 plot = self.axes[n].pcolormesh(x, y, z[n].T,
710 vmin=self.zmin,
711 vmax=self.zmax,
712 cmap=plt.get_cmap(self.colormap)
713 )
714 self.axes[n].set_title('{} {}'.format(self.titles[n],
715 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
716 size=8)
717
718 self.saveTime = self.min_time
540 719
541 720
542 721 class PlotCOHData(PlotRTIData):
543 722
544 723 CODE = 'coh'
545 724
546 725 def setup(self):
547 726
548 727 self.ncols = 1
549 728 self.nrows = self.dataOut.nPairs
550 729 self.width = 10
551 730 self.height = 2.2*self.nrows if self.nrows<6 else 12
731 self.ind_plt_ch = False #just for coherence and phase
552 732 if self.nrows==1:
553 733 self.height += 1
554 734 self.ylabel = 'Range [Km]'
555 735 self.titles = ['{} Ch{} * Ch{}'.format(self.CODE.upper(), x[0], x[1]) for x in self.dataOut.pairsList]
556 736
557 737 if self.figure is None:
558 738 self.figure = plt.figure(figsize=(self.width, self.height),
559 739 edgecolor='k',
560 740 facecolor='w')
561 741 else:
562 742 self.figure.clf()
563 743 self.axes = []
564 744
565 745 for n in range(self.nrows):
566 746 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
567 747 ax.firsttime = True
568 748 self.axes.append(ax)
569 749
570 750
571 751 class PlotNoiseData(PlotData):
572 752 CODE = 'noise'
573 753
574 754 def setup(self):
575 755
576 756 self.ncols = 1
577 757 self.nrows = 1
578 758 self.width = 10
579 759 self.height = 3.2
580 760 self.ylabel = 'Intensity [dB]'
581 761 self.titles = ['Noise']
582 762
583 763 if self.figure is None:
584 764 self.figure = plt.figure(figsize=(self.width, self.height),
585 765 edgecolor='k',
586 766 facecolor='w')
587 767 else:
588 768 self.figure.clf()
589 769 self.axes = []
590 770
591 771 self.ax = self.figure.add_subplot(self.nrows, self.ncols, 1)
592 772 self.ax.firsttime = True
593 773
594 774 def plot(self):
595 775
596 776 x = self.times
597 777 xmin = self.min_time
598 778 xmax = xmin+self.xrange*60*60
599 779 if self.ax.firsttime:
600 780 for ch in self.dataOut.channelList:
601 781 y = [self.data[self.CODE][t][ch] for t in self.times]
602 782 self.ax.plot(x, y, lw=1, label='Ch{}'.format(ch))
603 783 self.ax.firsttime = False
604 784 self.ax.xaxis.set_major_formatter(FuncFormatter(func))
605 785 self.ax.xaxis.set_major_locator(LinearLocator(6))
606 786 self.ax.set_ylabel(self.ylabel)
607 787 plt.legend()
608 788 else:
609 789 for ch in self.dataOut.channelList:
610 790 y = [self.data[self.CODE][t][ch] for t in self.times]
611 791 self.ax.lines[ch].set_data(x, y)
612 792
613 793 self.ax.set_xlim(xmin, xmax)
614 794 self.ax.set_ylim(min(y)-5, max(y)+5)
615 795 self.saveTime = self.min_time
616 796
617 797
618 798 class PlotWindProfilerData(PlotRTIData):
619 799
620 800 CODE = 'wind'
621 801 colormap = 'seismic'
622 802
623 803 def setup(self):
624 804 self.ncols = 1
625 805 self.nrows = self.dataOut.data_output.shape[0]
626 806 self.width = 10
627 807 self.height = 2.2*self.nrows
628 808 self.ylabel = 'Height [Km]'
629 809 self.titles = ['Zonal Wind' ,'Meridional Wind', 'Vertical Wind']
630 810 self.clabels = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
631 811 self.windFactor = [1, 1, 100]
632 812
633 813 if self.figure is None:
634 814 self.figure = plt.figure(figsize=(self.width, self.height),
635 815 edgecolor='k',
636 816 facecolor='w')
637 817 else:
638 818 self.figure.clf()
639 819 self.axes = []
640 820
641 821 for n in range(self.nrows):
642 822 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
643 823 ax.firsttime = True
644 824 self.axes.append(ax)
645 825
646 826 def plot(self):
647 827
648 828 self.x = np.array(self.times)
649 829 self.y = self.dataOut.heightList
650 830 self.z = []
651 831
652 832 for ch in range(self.nrows):
653 833 self.z.append([self.data['output'][t][ch] for t in self.times])
654 834
655 835 self.z = np.array(self.z)
656 836 self.z = numpy.ma.masked_invalid(self.z)
657 837
658 838 cmap=plt.get_cmap(self.colormap)
659 839 cmap.set_bad('black', 1.)
660 840
661 841 for n, ax in enumerate(self.axes):
662 842 x, y, z = self.fill_gaps(*self.decimate())
663 843 xmin = self.min_time
664 844 xmax = xmin+self.xrange*60*60
665 845 if ax.firsttime:
666 846 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
667 847 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
668 848 self.zmax = self.zmax if self.zmax else numpy.nanmax(abs(self.z[:-1, :]))
669 849 self.zmin = self.zmin if self.zmin else -self.zmax
670 850
671 851 plot = ax.pcolormesh(x, y, z[n].T*self.windFactor[n],
672 852 vmin=self.zmin,
673 853 vmax=self.zmax,
674 854 cmap=cmap
675 855 )
676 856 divider = make_axes_locatable(ax)
677 857 cax = divider.new_horizontal(size='2%', pad=0.05)
678 858 self.figure.add_axes(cax)
679 859 cb = plt.colorbar(plot, cax)
680 860 cb.set_label(self.clabels[n])
681 861 ax.set_ylim(self.ymin, self.ymax)
682 862
683 863 ax.xaxis.set_major_formatter(FuncFormatter(func))
684 864 ax.xaxis.set_major_locator(LinearLocator(6))
685 865
686 866 ax.set_ylabel(self.ylabel)
687 867
688 868 ax.set_xlim(xmin, xmax)
689 869 ax.firsttime = False
690 870 else:
691 871 ax.collections.remove(ax.collections[0])
692 872 ax.set_xlim(xmin, xmax)
693 873 plot = ax.pcolormesh(x, y, z[n].T*self.windFactor[n],
694 874 vmin=self.zmin,
695 875 vmax=self.zmax,
696 876 cmap=plt.get_cmap(self.colormap)
697 877 )
698 878 ax.set_title('{} {}'.format(self.titles[n],
699 879 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
700 880 size=8)
701 881
702 882 self.saveTime = self.min_time
703 883
704 884
705 885 class PlotSNRData(PlotRTIData):
706 886 CODE = 'snr'
707 887 colormap = 'jet'
708 888
709 889 class PlotDOPData(PlotRTIData):
710 890 CODE = 'dop'
711 891 colormap = 'jet'
712 892
713 893
714 894 class PlotPHASEData(PlotCOHData):
715 895 CODE = 'phase'
716 896 colormap = 'seismic'
717 897
718 898
719 899 class PlotSkyMapData(PlotData):
720 900
721 901 CODE = 'met'
722 902
723 903 def setup(self):
724 904
725 905 self.ncols = 1
726 906 self.nrows = 1
727 907 self.width = 7.2
728 908 self.height = 7.2
729 909
730 910 self.xlabel = 'Zonal Zenith Angle (deg)'
731 911 self.ylabel = 'Meridional Zenith Angle (deg)'
732 912
733 913 if self.figure is None:
734 914 self.figure = plt.figure(figsize=(self.width, self.height),
735 915 edgecolor='k',
736 916 facecolor='w')
737 917 else:
738 918 self.figure.clf()
739 919
740 920 self.ax = plt.subplot2grid((self.nrows, self.ncols), (0, 0), 1, 1, polar=True)
741 921 self.ax.firsttime = True
742 922
743 923
744 924 def plot(self):
745 925
746 926 arrayParameters = np.concatenate([self.data['param'][t] for t in self.times])
747 927 error = arrayParameters[:,-1]
748 928 indValid = numpy.where(error == 0)[0]
749 929 finalMeteor = arrayParameters[indValid,:]
750 930 finalAzimuth = finalMeteor[:,3]
751 931 finalZenith = finalMeteor[:,4]
752 932
753 933 x = finalAzimuth*numpy.pi/180
754 934 y = finalZenith
755 935
756 936 if self.ax.firsttime:
757 937 self.ax.plot = self.ax.plot(x, y, 'bo', markersize=5)[0]
758 938 self.ax.set_ylim(0,90)
759 939 self.ax.set_yticks(numpy.arange(0,90,20))
760 940 self.ax.set_xlabel(self.xlabel)
761 941 self.ax.set_ylabel(self.ylabel)
762 942 self.ax.yaxis.labelpad = 40
763 943 self.ax.firsttime = False
764 944 else:
765 945 self.ax.plot.set_data(x, y)
766 946
767 947
768 948 dt1 = datetime.datetime.fromtimestamp(self.min_time).strftime('%y/%m/%d %H:%M:%S')
769 949 dt2 = datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')
770 950 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
771 951 dt2,
772 952 len(x))
773 953 self.ax.set_title(title, size=8)
774 954
775 955 self.saveTime = self.max_time
General Comments 0
You need to be logged in to leave comments. Login now