##// END OF EJS Templates
antes de la nueva 2.3
J Gomez -
r958:2f4ff9a3b28d merge
parent child
Show More
@@ -1,1321 +1,1323
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
71 time.sleep(3)
70 72
71 73
72 74 class ParameterConf():
73 75
74 76 id = None
75 77 name = None
76 78 value = None
77 79 format = None
78 80
79 81 __formated_value = None
80 82
81 83 ELEMENTNAME = 'Parameter'
82 84
83 85 def __init__(self):
84 86
85 87 self.format = 'str'
86 88
87 89 def getElementName(self):
88 90
89 91 return self.ELEMENTNAME
90 92
91 93 def getValue(self):
92 94
93 95 value = self.value
94 96 format = self.format
95 97
96 98 if self.__formated_value != None:
97 99
98 100 return self.__formated_value
99 101
100 102 if format == 'obj':
101 103 return value
102 104
103 105 if format == 'str':
104 106 self.__formated_value = str(value)
105 107 return self.__formated_value
106 108
107 109 if value == '':
108 110 raise ValueError, "%s: This parameter value is empty" %self.name
109 111
110 112 if format == 'list':
111 113 strList = value.split(',')
112 114
113 115 self.__formated_value = strList
114 116
115 117 return self.__formated_value
116 118
117 119 if format == 'intlist':
118 120 """
119 121 Example:
120 122 value = (0,1,2)
121 123 """
122 124
123 125 new_value = ast.literal_eval(value)
124 126
125 127 if type(new_value) not in (tuple, list):
126 128 new_value = [int(new_value)]
127 129
128 130 self.__formated_value = new_value
129 131
130 132 return self.__formated_value
131 133
132 134 if format == 'floatlist':
133 135 """
134 136 Example:
135 137 value = (0.5, 1.4, 2.7)
136 138 """
137 139
138 140 new_value = ast.literal_eval(value)
139 141
140 142 if type(new_value) not in (tuple, list):
141 143 new_value = [float(new_value)]
142 144
143 145 self.__formated_value = new_value
144 146
145 147 return self.__formated_value
146 148
147 149 if format == 'date':
148 150 strList = value.split('/')
149 151 intList = [int(x) for x in strList]
150 152 date = datetime.date(intList[0], intList[1], intList[2])
151 153
152 154 self.__formated_value = date
153 155
154 156 return self.__formated_value
155 157
156 158 if format == 'time':
157 159 strList = value.split(':')
158 160 intList = [int(x) for x in strList]
159 161 time = datetime.time(intList[0], intList[1], intList[2])
160 162
161 163 self.__formated_value = time
162 164
163 165 return self.__formated_value
164 166
165 167 if format == 'pairslist':
166 168 """
167 169 Example:
168 170 value = (0,1),(1,2)
169 171 """
170 172
171 173 new_value = ast.literal_eval(value)
172 174
173 175 if type(new_value) not in (tuple, list):
174 176 raise ValueError, "%s has to be a tuple or list of pairs" %value
175 177
176 178 if type(new_value[0]) not in (tuple, list):
177 179 if len(new_value) != 2:
178 180 raise ValueError, "%s has to be a tuple or list of pairs" %value
179 181 new_value = [new_value]
180 182
181 183 for thisPair in new_value:
182 184 if len(thisPair) != 2:
183 185 raise ValueError, "%s has to be a tuple or list of pairs" %value
184 186
185 187 self.__formated_value = new_value
186 188
187 189 return self.__formated_value
188 190
189 191 if format == 'multilist':
190 192 """
191 193 Example:
192 194 value = (0,1,2),(3,4,5)
193 195 """
194 196 multiList = ast.literal_eval(value)
195 197
196 198 if type(multiList[0]) == int:
197 199 multiList = ast.literal_eval("(" + value + ")")
198 200
199 201 self.__formated_value = multiList
200 202
201 203 return self.__formated_value
202 204
203 205 if format == 'bool':
204 206 value = int(value)
205 207
206 208 if format == 'int':
207 209 value = float(value)
208 210
209 211 format_func = eval(format)
210 212
211 213 self.__formated_value = format_func(value)
212 214
213 215 return self.__formated_value
214 216
215 217 def updateId(self, new_id):
216 218
217 219 self.id = str(new_id)
218 220
219 221 def setup(self, id, name, value, format='str'):
220 222
221 223 self.id = str(id)
222 224 self.name = name
223 225 if format == 'obj':
224 226 self.value = value
225 227 else:
226 228 self.value = str(value)
227 229 self.format = str.lower(format)
228 230
229 231 self.getValue()
230 232
231 233 return 1
232 234
233 235 def update(self, name, value, format='str'):
234 236
235 237 self.name = name
236 238 self.value = str(value)
237 239 self.format = format
238 240
239 241 def makeXml(self, opElement):
240 242 if self.name not in ('queue',):
241 243 parmElement = SubElement(opElement, self.ELEMENTNAME)
242 244 parmElement.set('id', str(self.id))
243 245 parmElement.set('name', self.name)
244 246 parmElement.set('value', self.value)
245 247 parmElement.set('format', self.format)
246 248
247 249 def readXml(self, parmElement):
248 250
249 251 self.id = parmElement.get('id')
250 252 self.name = parmElement.get('name')
251 253 self.value = parmElement.get('value')
252 254 self.format = str.lower(parmElement.get('format'))
253 255
254 256 #Compatible with old signal chain version
255 257 if self.format == 'int' and self.name == 'idfigure':
256 258 self.name = 'id'
257 259
258 260 def printattr(self):
259 261
260 262 print "Parameter[%s]: name = %s, value = %s, format = %s" %(self.id, self.name, self.value, self.format)
261 263
262 264 class OperationConf():
263 265
264 266 id = None
265 267 name = None
266 268 priority = None
267 269 type = None
268 270
269 271 parmConfObjList = []
270 272
271 273 ELEMENTNAME = 'Operation'
272 274
273 275 def __init__(self):
274 276
275 277 self.id = '0'
276 278 self.name = None
277 279 self.priority = None
278 280 self.type = 'self'
279 281
280 282
281 283 def __getNewId(self):
282 284
283 285 return int(self.id)*10 + len(self.parmConfObjList) + 1
284 286
285 287 def updateId(self, new_id):
286 288
287 289 self.id = str(new_id)
288 290
289 291 n = 1
290 292 for parmObj in self.parmConfObjList:
291 293
292 294 idParm = str(int(new_id)*10 + n)
293 295 parmObj.updateId(idParm)
294 296
295 297 n += 1
296 298
297 299 def getElementName(self):
298 300
299 301 return self.ELEMENTNAME
300 302
301 303 def getParameterObjList(self):
302 304
303 305 return self.parmConfObjList
304 306
305 307 def getParameterObj(self, parameterName):
306 308
307 309 for parmConfObj in self.parmConfObjList:
308 310
309 311 if parmConfObj.name != parameterName:
310 312 continue
311 313
312 314 return parmConfObj
313 315
314 316 return None
315 317
316 318 def getParameterObjfromValue(self, parameterValue):
317 319
318 320 for parmConfObj in self.parmConfObjList:
319 321
320 322 if parmConfObj.getValue() != parameterValue:
321 323 continue
322 324
323 325 return parmConfObj.getValue()
324 326
325 327 return None
326 328
327 329 def getParameterValue(self, parameterName):
328 330
329 331 parameterObj = self.getParameterObj(parameterName)
330 332
331 333 # if not parameterObj:
332 334 # return None
333 335
334 336 value = parameterObj.getValue()
335 337
336 338 return value
337 339
338 340
339 341 def getKwargs(self):
340 342
341 343 kwargs = {}
342 344
343 345 for parmConfObj in self.parmConfObjList:
344 346 if self.name == 'run' and parmConfObj.name == 'datatype':
345 347 continue
346 348
347 349 kwargs[parmConfObj.name] = parmConfObj.getValue()
348 350
349 351 return kwargs
350 352
351 353 def setup(self, id, name, priority, type):
352 354
353 355 self.id = str(id)
354 356 self.name = name
355 357 self.type = type
356 358 self.priority = priority
357 359
358 360 self.parmConfObjList = []
359 361
360 362 def removeParameters(self):
361 363
362 364 for obj in self.parmConfObjList:
363 365 del obj
364 366
365 367 self.parmConfObjList = []
366 368
367 369 def addParameter(self, name, value, format='str'):
368 370
369 371 id = self.__getNewId()
370 372
371 373 parmConfObj = ParameterConf()
372 374 if not parmConfObj.setup(id, name, value, format):
373 375 return None
374 376
375 377 self.parmConfObjList.append(parmConfObj)
376 378
377 379 return parmConfObj
378 380
379 381 def changeParameter(self, name, value, format='str'):
380 382
381 383 parmConfObj = self.getParameterObj(name)
382 384 parmConfObj.update(name, value, format)
383 385
384 386 return parmConfObj
385 387
386 388 def makeXml(self, procUnitElement):
387 389
388 390 opElement = SubElement(procUnitElement, self.ELEMENTNAME)
389 391 opElement.set('id', str(self.id))
390 392 opElement.set('name', self.name)
391 393 opElement.set('type', self.type)
392 394 opElement.set('priority', str(self.priority))
393 395
394 396 for parmConfObj in self.parmConfObjList:
395 397 parmConfObj.makeXml(opElement)
396 398
397 399 def readXml(self, opElement):
398 400
399 401 self.id = opElement.get('id')
400 402 self.name = opElement.get('name')
401 403 self.type = opElement.get('type')
402 404 self.priority = opElement.get('priority')
403 405
404 406 #Compatible with old signal chain version
405 407 #Use of 'run' method instead 'init'
406 408 if self.type == 'self' and self.name == 'init':
407 409 self.name = 'run'
408 410
409 411 self.parmConfObjList = []
410 412
411 413 parmElementList = opElement.iter(ParameterConf().getElementName())
412 414
413 415 for parmElement in parmElementList:
414 416 parmConfObj = ParameterConf()
415 417 parmConfObj.readXml(parmElement)
416 418
417 419 #Compatible with old signal chain version
418 420 #If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER
419 421 if self.type != 'self' and self.name == 'Plot':
420 422 if parmConfObj.format == 'str' and parmConfObj.name == 'type':
421 423 self.name = parmConfObj.value
422 424 continue
423 425
424 426 self.parmConfObjList.append(parmConfObj)
425 427
426 428 def printattr(self):
427 429
428 430 print "%s[%s]: name = %s, type = %s, priority = %s" %(self.ELEMENTNAME,
429 431 self.id,
430 432 self.name,
431 433 self.type,
432 434 self.priority)
433 435
434 436 for parmConfObj in self.parmConfObjList:
435 437 parmConfObj.printattr()
436 438
437 439 def createObject(self, plotter_queue=None):
438 440
439 441
440 442 if self.type == 'self':
441 443 raise ValueError, "This operation type cannot be created"
442 444
443 445 if self.type == 'plotter':
444 446 #Plotter(plotter_name)
445 447 if not plotter_queue:
446 448 raise ValueError, "plotter_queue is not defined. Use:\nmyProject = Project()\nmyProject.setPlotterQueue(plotter_queue)"
447 449
448 450 opObj = Plotter(self.name, plotter_queue)
449 451
450 452 if self.type == 'external' or self.type == 'other':
451 453
452 454 className = eval(self.name)
453 455 kwargs = self.getKwargs()
454 456
455 457 opObj = className(**kwargs)
456 458
457 459 return opObj
458 460
459 461
460 462 class ProcUnitConf():
461 463
462 464 id = None
463 465 name = None
464 466 datatype = None
465 467 inputId = None
466 468 parentId = None
467 469
468 470 opConfObjList = []
469 471
470 472 procUnitObj = None
471 473 opObjList = []
472 474
473 475 ELEMENTNAME = 'ProcUnit'
474 476
475 477 def __init__(self):
476 478
477 479 self.id = None
478 480 self.datatype = None
479 481 self.name = None
480 482 self.inputId = None
481 483
482 484 self.opConfObjList = []
483 485
484 486 self.procUnitObj = None
485 487 self.opObjDict = {}
486 488
487 489 def __getPriority(self):
488 490
489 491 return len(self.opConfObjList)+1
490 492
491 493 def __getNewId(self):
492 494
493 495 return int(self.id)*10 + len(self.opConfObjList) + 1
494 496
495 497 def getElementName(self):
496 498
497 499 return self.ELEMENTNAME
498 500
499 501 def getId(self):
500 502
501 503 return self.id
502 504
503 505 def updateId(self, new_id, parentId=parentId):
504 506
505 507
506 508 new_id = int(parentId)*10 + (int(self.id) % 10)
507 509 new_inputId = int(parentId)*10 + (int(self.inputId) % 10)
508 510
509 511 #If this proc unit has not inputs
510 512 if self.inputId == '0':
511 513 new_inputId = 0
512 514
513 515 n = 1
514 516 for opConfObj in self.opConfObjList:
515 517
516 518 idOp = str(int(new_id)*10 + n)
517 519 opConfObj.updateId(idOp)
518 520
519 521 n += 1
520 522
521 523 self.parentId = str(parentId)
522 524 self.id = str(new_id)
523 525 self.inputId = str(new_inputId)
524 526
525 527
526 528 def getInputId(self):
527 529
528 530 return self.inputId
529 531
530 532 def getOperationObjList(self):
531 533
532 534 return self.opConfObjList
533 535
534 536 def getOperationObj(self, name=None):
535 537
536 538 for opConfObj in self.opConfObjList:
537 539
538 540 if opConfObj.name != name:
539 541 continue
540 542
541 543 return opConfObj
542 544
543 545 return None
544 546
545 547 def getOpObjfromParamValue(self, value=None):
546 548
547 549 for opConfObj in self.opConfObjList:
548 550 if opConfObj.getParameterObjfromValue(parameterValue=value) != value:
549 551 continue
550 552 return opConfObj
551 553 return None
552 554
553 555 def getProcUnitObj(self):
554 556
555 557 return self.procUnitObj
556 558
557 559 def setup(self, id, name, datatype, inputId, parentId=None):
558 560
559 561 #Compatible with old signal chain version
560 562 if datatype==None and name==None:
561 563 raise ValueError, "datatype or name should be defined"
562 564
563 565 if name==None:
564 566 if 'Proc' in datatype:
565 567 name = datatype
566 568 else:
567 569 name = '%sProc' %(datatype)
568 570
569 571 if datatype==None:
570 572 datatype = name.replace('Proc','')
571 573
572 574 self.id = str(id)
573 575 self.name = name
574 576 self.datatype = datatype
575 577 self.inputId = inputId
576 578 self.parentId = parentId
577 579
578 580 self.opConfObjList = []
579 581
580 582 self.addOperation(name='run', optype='self')
581 583
582 584 def removeOperations(self):
583 585
584 586 for obj in self.opConfObjList:
585 587 del obj
586 588
587 589 self.opConfObjList = []
588 590 self.addOperation(name='run')
589 591
590 592 def addParameter(self, **kwargs):
591 593 '''
592 594 Add parameters to "run" operation
593 595 '''
594 596 opObj = self.opConfObjList[0]
595 597
596 598 opObj.addParameter(**kwargs)
597 599
598 600 return opObj
599 601
600 602 def addOperation(self, name, optype='self'):
601 603
602 604 id = self.__getNewId()
603 605 priority = self.__getPriority()
604 606
605 607 opConfObj = OperationConf()
606 608 opConfObj.setup(id, name=name, priority=priority, type=optype)
607 609
608 610 self.opConfObjList.append(opConfObj)
609 611
610 612 return opConfObj
611 613
612 614 def makeXml(self, projectElement):
613 615
614 616 procUnitElement = SubElement(projectElement, self.ELEMENTNAME)
615 617 procUnitElement.set('id', str(self.id))
616 618 procUnitElement.set('name', self.name)
617 619 procUnitElement.set('datatype', self.datatype)
618 620 procUnitElement.set('inputId', str(self.inputId))
619 621
620 622 for opConfObj in self.opConfObjList:
621 623 opConfObj.makeXml(procUnitElement)
622 624
623 625 def readXml(self, upElement):
624 626
625 627 self.id = upElement.get('id')
626 628 self.name = upElement.get('name')
627 629 self.datatype = upElement.get('datatype')
628 630 self.inputId = upElement.get('inputId')
629 631
630 632 if self.ELEMENTNAME == "ReadUnit":
631 633 self.datatype = self.datatype.replace("Reader", "")
632 634
633 635 if self.ELEMENTNAME == "ProcUnit":
634 636 self.datatype = self.datatype.replace("Proc", "")
635 637
636 638 if self.inputId == 'None':
637 639 self.inputId = '0'
638 640
639 641 self.opConfObjList = []
640 642
641 643 opElementList = upElement.iter(OperationConf().getElementName())
642 644
643 645 for opElement in opElementList:
644 646 opConfObj = OperationConf()
645 647 opConfObj.readXml(opElement)
646 648 self.opConfObjList.append(opConfObj)
647 649
648 650 def printattr(self):
649 651
650 652 print "%s[%s]: name = %s, datatype = %s, inputId = %s" %(self.ELEMENTNAME,
651 653 self.id,
652 654 self.name,
653 655 self.datatype,
654 656 self.inputId)
655 657
656 658 for opConfObj in self.opConfObjList:
657 659 opConfObj.printattr()
658 660
659 661
660 662 def getKwargs(self):
661 663
662 664 opObj = self.opConfObjList[0]
663 665 kwargs = opObj.getKwargs()
664 666
665 667 return kwargs
666 668
667 669 def createObjects(self, plotter_queue=None):
668 670
669 671 className = eval(self.name)
670 672 kwargs = self.getKwargs()
671 673 procUnitObj = className(**kwargs)
672 674
673 675 for opConfObj in self.opConfObjList:
674 676
675 677 if opConfObj.type=='self' and self.name=='run':
676 678 continue
677 679 elif opConfObj.type=='self':
678 680 procUnitObj.addOperationKwargs(opConfObj.id, **opConfObj.getKwargs())
679 681 continue
680 682
681 683 opObj = opConfObj.createObject(plotter_queue)
682 684
683 685 self.opObjDict[opConfObj.id] = opObj
684 686
685 687 procUnitObj.addOperation(opObj, opConfObj.id)
686 688
687 689 self.procUnitObj = procUnitObj
688 690
689 691 return procUnitObj
690 692
691 693 def run(self):
692 694
693 695 is_ok = False
694 696
695 697 for opConfObj in self.opConfObjList:
696 698
697 699 kwargs = {}
698 700 for parmConfObj in opConfObj.getParameterObjList():
699 701 if opConfObj.name == 'run' and parmConfObj.name == 'datatype':
700 702 continue
701 703
702 704 kwargs[parmConfObj.name] = parmConfObj.getValue()
703 705
704 706 #ini = time.time()
705 707
706 708 #print "\tRunning the '%s' operation with %s" %(opConfObj.name, opConfObj.id)
707 709 sts = self.procUnitObj.call(opType = opConfObj.type,
708 710 opName = opConfObj.name,
709 711 opId = opConfObj.id,
710 712 )
711 713
712 714 # total_time = time.time() - ini
713 715 #
714 716 # if total_time > 0.002:
715 717 # print "%s::%s took %f seconds" %(self.name, opConfObj.name, total_time)
716 718
717 719 is_ok = is_ok or sts
718 720
719 721 return is_ok
720 722
721 723 def close(self):
722 724
723 725 for opConfObj in self.opConfObjList:
724 726 if opConfObj.type == 'self':
725 727 continue
726 728
727 729 opObj = self.procUnitObj.getOperationObj(opConfObj.id)
728 730 opObj.close()
729 731
730 732 self.procUnitObj.close()
731 733
732 734 return
733 735
734 736 class ReadUnitConf(ProcUnitConf):
735 737
736 738 path = None
737 739 startDate = None
738 740 endDate = None
739 741 startTime = None
740 742 endTime = None
741 743
742 744 ELEMENTNAME = 'ReadUnit'
743 745
744 746 def __init__(self):
745 747
746 748 self.id = None
747 749 self.datatype = None
748 750 self.name = None
749 751 self.inputId = None
750 752
751 753 self.parentId = None
752 754
753 755 self.opConfObjList = []
754 756 self.opObjList = []
755 757
756 758 def getElementName(self):
757 759
758 760 return self.ELEMENTNAME
759 761
760 762 def setup(self, id, name, datatype, path, startDate="", endDate="", startTime="", endTime="", parentId=None, queue=None, **kwargs):
761 763
762 764 #Compatible with old signal chain version
763 765 if datatype==None and name==None:
764 766 raise ValueError, "datatype or name should be defined"
765 767
766 768 if name==None:
767 769 if 'Reader' in datatype:
768 770 name = datatype
769 771 else:
770 772 name = '%sReader' %(datatype)
771 773
772 774 if datatype==None:
773 775 datatype = name.replace('Reader','')
774 776
775 777 self.id = id
776 778 self.name = name
777 779 self.datatype = datatype
778 780
779 781 self.path = os.path.abspath(path)
780 782 self.startDate = startDate
781 783 self.endDate = endDate
782 784 self.startTime = startTime
783 785 self.endTime = endTime
784 786
785 787 self.inputId = '0'
786 788 self.parentId = parentId
787 789 self.queue = queue
788 790 self.addRunOperation(**kwargs)
789 791
790 792 def update(self, datatype, path, startDate, endDate, startTime, endTime, parentId=None, name=None, **kwargs):
791 793
792 794 #Compatible with old signal chain version
793 795 if datatype==None and name==None:
794 796 raise ValueError, "datatype or name should be defined"
795 797
796 798 if name==None:
797 799 if 'Reader' in datatype:
798 800 name = datatype
799 801 else:
800 802 name = '%sReader' %(datatype)
801 803
802 804 if datatype==None:
803 805 datatype = name.replace('Reader','')
804 806
805 807 self.datatype = datatype
806 808 self.name = name
807 809 self.path = path
808 810 self.startDate = startDate
809 811 self.endDate = endDate
810 812 self.startTime = startTime
811 813 self.endTime = endTime
812 814
813 815 self.inputId = '0'
814 816 self.parentId = parentId
815 817
816 818 self.updateRunOperation(**kwargs)
817 819
818 820 def removeOperations(self):
819 821
820 822 for obj in self.opConfObjList:
821 823 del obj
822 824
823 825 self.opConfObjList = []
824 826
825 827 def addRunOperation(self, **kwargs):
826 828
827 829 opObj = self.addOperation(name = 'run', optype = 'self')
828 830
829 831 opObj.addParameter(name='datatype' , value=self.datatype, format='str')
830 832 opObj.addParameter(name='path' , value=self.path, format='str')
831 833 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
832 834 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
833 835 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
834 836 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
835 837 opObj.addParameter(name='queue' , value=self.queue, format='obj')
836 838
837 839 for key, value in kwargs.items():
838 840 opObj.addParameter(name=key, value=value, format=type(value).__name__)
839 841
840 842 return opObj
841 843
842 844 def updateRunOperation(self, **kwargs):
843 845
844 846 opObj = self.getOperationObj(name = 'run')
845 847 opObj.removeParameters()
846 848
847 849 opObj.addParameter(name='datatype' , value=self.datatype, format='str')
848 850 opObj.addParameter(name='path' , value=self.path, format='str')
849 851 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
850 852 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
851 853 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
852 854 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
853 855
854 856 for key, value in kwargs.items():
855 857 opObj.addParameter(name=key, value=value, format=type(value).__name__)
856 858
857 859 return opObj
858 860
859 861 # def makeXml(self, projectElement):
860 862 #
861 863 # procUnitElement = SubElement(projectElement, self.ELEMENTNAME)
862 864 # procUnitElement.set('id', str(self.id))
863 865 # procUnitElement.set('name', self.name)
864 866 # procUnitElement.set('datatype', self.datatype)
865 867 # procUnitElement.set('inputId', str(self.inputId))
866 868 #
867 869 # for opConfObj in self.opConfObjList:
868 870 # opConfObj.makeXml(procUnitElement)
869 871
870 872 def readXml(self, upElement):
871 873
872 874 self.id = upElement.get('id')
873 875 self.name = upElement.get('name')
874 876 self.datatype = upElement.get('datatype')
875 877 self.inputId = upElement.get('inputId')
876 878
877 879 if self.ELEMENTNAME == "ReadUnit":
878 880 self.datatype = self.datatype.replace("Reader", "")
879 881
880 882 if self.inputId == 'None':
881 883 self.inputId = '0'
882 884
883 885 self.opConfObjList = []
884 886
885 887 opElementList = upElement.iter(OperationConf().getElementName())
886 888
887 889 for opElement in opElementList:
888 890 opConfObj = OperationConf()
889 891 opConfObj.readXml(opElement)
890 892 self.opConfObjList.append(opConfObj)
891 893
892 894 if opConfObj.name == 'run':
893 895 self.path = opConfObj.getParameterValue('path')
894 896 self.startDate = opConfObj.getParameterValue('startDate')
895 897 self.endDate = opConfObj.getParameterValue('endDate')
896 898 self.startTime = opConfObj.getParameterValue('startTime')
897 899 self.endTime = opConfObj.getParameterValue('endTime')
898 900
899 901 class Project():
900 902
901 903 id = None
902 904 name = None
903 905 description = None
904 906 filename = None
905 907
906 908 procUnitConfObjDict = None
907 909
908 910 ELEMENTNAME = 'Project'
909 911
910 912 plotterQueue = None
911 913
912 914 def __init__(self, plotter_queue=None):
913 915
914 916 self.id = None
915 917 self.name = None
916 918 self.description = None
917 919
918 920 self.plotterQueue = plotter_queue
919 921
920 922 self.procUnitConfObjDict = {}
921 923
922 924 def __getNewId(self):
923 925
924 926 idList = self.procUnitConfObjDict.keys()
925 927
926 928 id = int(self.id)*10
927 929
928 930 while True:
929 931 id += 1
930 932
931 933 if str(id) in idList:
932 934 continue
933 935
934 936 break
935 937
936 938 return str(id)
937 939
938 940 def getElementName(self):
939 941
940 942 return self.ELEMENTNAME
941 943
942 944 def getId(self):
943 945
944 946 return self.id
945 947
946 948 def updateId(self, new_id):
947 949
948 950 self.id = str(new_id)
949 951
950 952 keyList = self.procUnitConfObjDict.keys()
951 953 keyList.sort()
952 954
953 955 n = 1
954 956 newProcUnitConfObjDict = {}
955 957
956 958 for procKey in keyList:
957 959
958 960 procUnitConfObj = self.procUnitConfObjDict[procKey]
959 961 idProcUnit = str(int(self.id)*10 + n)
960 962 procUnitConfObj.updateId(idProcUnit, parentId = self.id)
961 963
962 964 newProcUnitConfObjDict[idProcUnit] = procUnitConfObj
963 965 n += 1
964 966
965 967 self.procUnitConfObjDict = newProcUnitConfObjDict
966 968
967 969 def setup(self, id, name, description):
968 970
969 971 self.id = str(id)
970 972 self.name = name
971 973 self.description = description
972 974
973 975 def update(self, name, description):
974 976
975 977 self.name = name
976 978 self.description = description
977 979
978 980 def addReadUnit(self, id=None, datatype=None, name=None, **kwargs):
979 981
980 982 if id is None:
981 983 idReadUnit = self.__getNewId()
982 984 else:
983 985 idReadUnit = str(id)
984 986
985 987 readUnitConfObj = ReadUnitConf()
986 988 readUnitConfObj.setup(idReadUnit, name, datatype, parentId=self.id, **kwargs)
987 989
988 990 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
989 991
990 992 return readUnitConfObj
991 993
992 994 def addProcUnit(self, inputId='0', datatype=None, name=None):
993 995
994 996 idProcUnit = self.__getNewId()
995 997
996 998 procUnitConfObj = ProcUnitConf()
997 999 procUnitConfObj.setup(idProcUnit, name, datatype, inputId, parentId=self.id)
998 1000
999 1001 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
1000 1002
1001 1003 return procUnitConfObj
1002 1004
1003 1005 def removeProcUnit(self, id):
1004 1006
1005 1007 if id in self.procUnitConfObjDict.keys():
1006 1008 self.procUnitConfObjDict.pop(id)
1007 1009
1008 1010 def getReadUnitId(self):
1009 1011
1010 1012 readUnitConfObj = self.getReadUnitObj()
1011 1013
1012 1014 return readUnitConfObj.id
1013 1015
1014 1016 def getReadUnitObj(self):
1015 1017
1016 1018 for obj in self.procUnitConfObjDict.values():
1017 1019 if obj.getElementName() == "ReadUnit":
1018 1020 return obj
1019 1021
1020 1022 return None
1021 1023
1022 1024 def getProcUnitObj(self, id=None, name=None):
1023 1025
1024 1026 if id != None:
1025 1027 return self.procUnitConfObjDict[id]
1026 1028
1027 1029 if name != None:
1028 1030 return self.getProcUnitObjByName(name)
1029 1031
1030 1032 return None
1031 1033
1032 1034 def getProcUnitObjByName(self, name):
1033 1035
1034 1036 for obj in self.procUnitConfObjDict.values():
1035 1037 if obj.name == name:
1036 1038 return obj
1037 1039
1038 1040 return None
1039 1041
1040 1042 def procUnitItems(self):
1041 1043
1042 1044 return self.procUnitConfObjDict.items()
1043 1045
1044 1046 def makeXml(self):
1045 1047
1046 1048 projectElement = Element('Project')
1047 1049 projectElement.set('id', str(self.id))
1048 1050 projectElement.set('name', self.name)
1049 1051 projectElement.set('description', self.description)
1050 1052
1051 1053 for procUnitConfObj in self.procUnitConfObjDict.values():
1052 1054 procUnitConfObj.makeXml(projectElement)
1053 1055
1054 1056 self.projectElement = projectElement
1055 1057
1056 1058 def writeXml(self, filename=None):
1057 1059
1058 1060 if filename == None:
1059 1061 if self.filename:
1060 1062 filename = self.filename
1061 1063 else:
1062 1064 filename = "schain.xml"
1063 1065
1064 1066 if not filename:
1065 1067 print "filename has not been defined. Use setFilename(filename) for do it."
1066 1068 return 0
1067 1069
1068 1070 abs_file = os.path.abspath(filename)
1069 1071
1070 1072 if not os.access(os.path.dirname(abs_file), os.W_OK):
1071 1073 print "No write permission on %s" %os.path.dirname(abs_file)
1072 1074 return 0
1073 1075
1074 1076 if os.path.isfile(abs_file) and not(os.access(abs_file, os.W_OK)):
1075 1077 print "File %s already exists and it could not be overwriten" %abs_file
1076 1078 return 0
1077 1079
1078 1080 self.makeXml()
1079 1081
1080 1082 ElementTree(self.projectElement).write(abs_file, method='xml')
1081 1083
1082 1084 self.filename = abs_file
1083 1085
1084 1086 return 1
1085 1087
1086 1088 def readXml(self, filename = None):
1087 1089
1088 1090 if not filename:
1089 1091 print "filename is not defined"
1090 1092 return 0
1091 1093
1092 1094 abs_file = os.path.abspath(filename)
1093 1095
1094 1096 if not os.path.isfile(abs_file):
1095 1097 print "%s file does not exist" %abs_file
1096 1098 return 0
1097 1099
1098 1100 self.projectElement = None
1099 1101 self.procUnitConfObjDict = {}
1100 1102
1101 1103 try:
1102 1104 self.projectElement = ElementTree().parse(abs_file)
1103 1105 except:
1104 1106 print "Error reading %s, verify file format" %filename
1105 1107 return 0
1106 1108
1107 1109 self.project = self.projectElement.tag
1108 1110
1109 1111 self.id = self.projectElement.get('id')
1110 1112 self.name = self.projectElement.get('name')
1111 1113 self.description = self.projectElement.get('description')
1112 1114
1113 1115 readUnitElementList = self.projectElement.iter(ReadUnitConf().getElementName())
1114 1116
1115 1117 for readUnitElement in readUnitElementList:
1116 1118 readUnitConfObj = ReadUnitConf()
1117 1119 readUnitConfObj.readXml(readUnitElement)
1118 1120
1119 1121 if readUnitConfObj.parentId == None:
1120 1122 readUnitConfObj.parentId = self.id
1121 1123
1122 1124 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
1123 1125
1124 1126 procUnitElementList = self.projectElement.iter(ProcUnitConf().getElementName())
1125 1127
1126 1128 for procUnitElement in procUnitElementList:
1127 1129 procUnitConfObj = ProcUnitConf()
1128 1130 procUnitConfObj.readXml(procUnitElement)
1129 1131
1130 1132 if procUnitConfObj.parentId == None:
1131 1133 procUnitConfObj.parentId = self.id
1132 1134
1133 1135 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
1134 1136
1135 1137 self.filename = abs_file
1136 1138
1137 1139 return 1
1138 1140
1139 1141 def printattr(self):
1140 1142
1141 1143 print "Project[%s]: name = %s, description = %s" %(self.id,
1142 1144 self.name,
1143 1145 self.description)
1144 1146
1145 1147 for procUnitConfObj in self.procUnitConfObjDict.values():
1146 1148 procUnitConfObj.printattr()
1147 1149
1148 1150 def createObjects(self):
1149 1151
1150 1152 for procUnitConfObj in self.procUnitConfObjDict.values():
1151 1153 procUnitConfObj.createObjects(self.plotterQueue)
1152 1154
1153 1155 def __connect(self, objIN, thisObj):
1154 1156
1155 1157 thisObj.setInput(objIN.getOutputObj())
1156 1158
1157 1159 def connectObjects(self):
1158 1160
1159 1161 for thisPUConfObj in self.procUnitConfObjDict.values():
1160 1162
1161 1163 inputId = thisPUConfObj.getInputId()
1162 1164
1163 1165 if int(inputId) == 0:
1164 1166 continue
1165 1167
1166 1168 #Get input object
1167 1169 puConfINObj = self.procUnitConfObjDict[inputId]
1168 1170 puObjIN = puConfINObj.getProcUnitObj()
1169 1171
1170 1172 #Get current object
1171 1173 thisPUObj = thisPUConfObj.getProcUnitObj()
1172 1174
1173 1175 self.__connect(puObjIN, thisPUObj)
1174 1176
1175 1177 def __handleError(self, procUnitConfObj, send_email=True):
1176 1178
1177 1179 import socket
1178 1180
1179 1181 err = traceback.format_exception(sys.exc_info()[0],
1180 1182 sys.exc_info()[1],
1181 1183 sys.exc_info()[2])
1182 1184
1183 1185 print "***** Error occurred in %s *****" %(procUnitConfObj.name)
1184 1186 print "***** %s" %err[-1]
1185 1187
1186 1188 message = "".join(err)
1187 1189
1188 1190 sys.stderr.write(message)
1189 1191
1190 1192 if not send_email:
1191 1193 return
1192 1194
1193 1195 subject = "SChain v%s: Error running %s\n" %(schainpy.__version__, procUnitConfObj.name)
1194 1196
1195 1197 subtitle = "%s: %s\n" %(procUnitConfObj.getElementName() ,procUnitConfObj.name)
1196 1198 subtitle += "Hostname: %s\n" %socket.gethostbyname(socket.gethostname())
1197 1199 subtitle += "Working directory: %s\n" %os.path.abspath("./")
1198 1200 subtitle += "Configuration file: %s\n" %self.filename
1199 1201 subtitle += "Time: %s\n" %str(datetime.datetime.now())
1200 1202
1201 1203 readUnitConfObj = self.getReadUnitObj()
1202 1204 if readUnitConfObj:
1203 1205 subtitle += "\nInput parameters:\n"
1204 1206 subtitle += "[Data path = %s]\n" %readUnitConfObj.path
1205 1207 subtitle += "[Data type = %s]\n" %readUnitConfObj.datatype
1206 1208 subtitle += "[Start date = %s]\n" %readUnitConfObj.startDate
1207 1209 subtitle += "[End date = %s]\n" %readUnitConfObj.endDate
1208 1210 subtitle += "[Start time = %s]\n" %readUnitConfObj.startTime
1209 1211 subtitle += "[End time = %s]\n" %readUnitConfObj.endTime
1210 1212
1211 1213 adminObj = schainpy.admin.SchainNotify()
1212 1214 adminObj.sendAlert(message=message,
1213 1215 subject=subject,
1214 1216 subtitle=subtitle,
1215 1217 filename=self.filename)
1216 1218
1217 1219 def isPaused(self):
1218 1220 return 0
1219 1221
1220 1222 def isStopped(self):
1221 1223 return 0
1222 1224
1223 1225 def runController(self):
1224 1226 """
1225 1227 returns 0 when this process has been stopped, 1 otherwise
1226 1228 """
1227 1229
1228 1230 if self.isPaused():
1229 1231 print "Process suspended"
1230 1232
1231 1233 while True:
1232 1234 sleep(0.1)
1233 1235
1234 1236 if not self.isPaused():
1235 1237 break
1236 1238
1237 1239 if self.isStopped():
1238 1240 break
1239 1241
1240 1242 print "Process reinitialized"
1241 1243
1242 1244 if self.isStopped():
1243 1245 print "Process stopped"
1244 1246 return 0
1245 1247
1246 1248 return 1
1247 1249
1248 1250 def setFilename(self, filename):
1249 1251
1250 1252 self.filename = filename
1251 1253
1252 1254 def setPlotterQueue(self, plotter_queue):
1253 1255
1254 1256 raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class"
1255 1257
1256 1258 def getPlotterQueue(self):
1257 1259
1258 1260 raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class"
1259 1261
1260 1262 def useExternalPlotter(self):
1261 1263
1262 1264 raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class"
1263 1265
1264 1266 def run(self):
1265 1267
1266 1268 print
1267 1269 print "*"*60
1268 1270 print " Starting SIGNAL CHAIN PROCESSING v%s " %schainpy.__version__
1269 1271 print "*"*60
1270 1272 print
1271 1273
1272 1274 keyList = self.procUnitConfObjDict.keys()
1273 1275 keyList.sort()
1274 1276
1275 1277 while(True):
1276 1278
1277 1279 is_ok = False
1278 1280
1279 1281 for procKey in keyList:
1280 1282 # print "Running the '%s' process with %s" %(procUnitConfObj.name, procUnitConfObj.id)
1281 1283
1282 1284 procUnitConfObj = self.procUnitConfObjDict[procKey]
1283 1285
1284 1286 try:
1285 1287 sts = procUnitConfObj.run()
1286 1288 is_ok = is_ok or sts
1287 1289 except KeyboardInterrupt:
1288 1290 is_ok = False
1289 1291 break
1290 1292 except ValueError, e:
1291 1293 sleep(0.5)
1292 1294 self.__handleError(procUnitConfObj, send_email=True)
1293 1295 is_ok = False
1294 1296 break
1295 1297 except:
1296 1298 sleep(0.5)
1297 1299 self.__handleError(procUnitConfObj)
1298 1300 is_ok = False
1299 1301 break
1300 1302
1301 1303 #If every process unit finished so end process
1302 1304 if not(is_ok):
1303 1305 # print "Every process unit have finished"
1304 1306 break
1305 1307
1306 1308 if not self.runController():
1307 1309 break
1308 1310
1309 1311 #Closing every process
1310 1312 for procKey in keyList:
1311 1313 procUnitConfObj = self.procUnitConfObjDict[procKey]
1312 1314 procUnitConfObj.close()
1313 1315
1314 1316 print "Process finished"
1315 1317
1316 1318 def start(self):
1317 1319
1318 1320 self.writeXml()
1319 1321 self.createObjects()
1320 1322 self.connectObjects()
1321 1323 self.run()
@@ -1,1225 +1,1225
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 return self.timeInterval1
1220 1220
1221 1221 def getNoise(self):
1222 1222
1223 1223 return self.spc_noise
1224 1224
1225 1225 timeInterval = property(getTimeInterval)
@@ -1,693 +1,736
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
40 self.figure2 = None #JM modificatiom
41 41 self.axes = []
42 42 self.localtime = kwargs.pop('localtime', True)
43 43 self.show = kwargs.get('show', True)
44 44 self.save = kwargs.get('save', False)
45 45 self.colormap = kwargs.get('colormap', self.colormap)
46 46 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
47 47 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
48 48 self.showprofile = kwargs.get('showprofile', True)
49 49 self.title = kwargs.get('wintitle', '')
50 50 self.xaxis = kwargs.get('xaxis', 'frequency')
51 51 self.zmin = kwargs.get('zmin', None)
52 52 self.zmax = kwargs.get('zmax', None)
53 53 self.xmin = kwargs.get('xmin', None)
54 54 self.xmax = kwargs.get('xmax', None)
55 55 self.xrange = kwargs.get('xrange', 24)
56 56 self.ymin = kwargs.get('ymin', None)
57 57 self.ymax = kwargs.get('ymax', None)
58 self.__MAXNUMY = kwargs.get('decimation', 80)
58 59 self.throttle_value = 5
60 self.times = []
59 61
60 62 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
61 63
62 64 if x_buffer.shape[0] < 2:
63 65 return x_buffer, y_buffer, z_buffer
64 66
65 67 deltas = x_buffer[1:] - x_buffer[0:-1]
66 68 x_median = np.median(deltas)
67 69
68 70 index = np.where(deltas > 5*x_median)
69 71
70 72 if len(index[0]) != 0:
71 73 z_buffer[::, index[0], ::] = self.__missing
72 74 z_buffer = np.ma.masked_inside(z_buffer,
73 75 0.99*self.__missing,
74 76 1.01*self.__missing)
75 77
76 78 return x_buffer, y_buffer, z_buffer
77 79
78 80 def decimate(self):
79 81
80 82 # dx = int(len(self.x)/self.__MAXNUMX) + 1
81 83 dy = int(len(self.y)/self.__MAXNUMY) + 1
82 84
83 85 # x = self.x[::dx]
84 86 x = self.x
85 87 y = self.y[::dy]
86 88 z = self.z[::, ::, ::dy]
87 89
88 90 return x, y, z
89 91
90 92 def __plot(self):
91 93
92 94 print 'plotting...{}'.format(self.CODE)
93 95
94 96 if self.show:
95 97 print 'showing'
96 98 self.figure.show()
99 self.figure2.show()
97 100
98 101 self.plot()
99 102 plt.tight_layout()
100 103 self.figure.canvas.manager.set_window_title('{} {} - Date:{}'.format(self.title, self.CODE.upper(),
101 104 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')))
105 self.figure2.canvas.manager.set_window_title('{} {} - Date:{}'.format(self.title, self.CODE.upper(),
106 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')))
102 107
103 108 if self.save:
104 109 figname = os.path.join(self.save, '{}_{}.png'.format(self.CODE,
105 110 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
106 111 print 'Saving figure: {}'.format(figname)
107 112 self.figure.savefig(figname)
113 figname2 = os.path.join(self.save, '{}_{}2.png'.format(self.CODE,
114 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
115 print 'Saving figure: {}'.format(figname2)
116 self.figure2.savefig(figname2)
108 117
109 118 self.figure.canvas.draw()
119 self.figure2.canvas.draw()
110 120
111 121 def plot(self):
112 122
113 123 print 'plotting...{}'.format(self.CODE.upper())
114 124 return
115 125
116 126 def run(self):
117 127
118 128 print '[Starting] {}'.format(self.name)
119 129 context = zmq.Context()
120 130 receiver = context.socket(zmq.SUB)
121 131 receiver.setsockopt(zmq.SUBSCRIBE, '')
122 132 receiver.setsockopt(zmq.CONFLATE, self.CONFLATE)
123 133 receiver.connect("ipc:///tmp/zmq.plots")
124
134 seconds_passed = 0
125 135 while True:
126 136 try:
127 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)
137 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)#flags=zmq.NOBLOCK
138 self.started = self.data['STARTED']
128 139 self.dataOut = self.data['dataOut']
140
141 if (len(self.times) < len(self.data['times']) and not self.started and self.data['ENDED']):
142 continue
143
129 144 self.times = self.data['times']
130 145 self.times.sort()
131 146 self.throttle_value = self.data['throttle']
132 147 self.min_time = self.times[0]
133 148 self.max_time = self.times[-1]
134 149
135 150 if self.isConfig is False:
151 print 'setting up'
136 152 self.setup()
137 153 self.isConfig = True
138 self.__plot()
154 self.__plot()
139 155
140 156 if self.data['ENDED'] is True:
157 print '********GRAPHIC ENDED********'
158 self.ended = True
141 159 self.isConfig = False
160 self.__plot()
161 elif seconds_passed >= self.data['throttle']:
162 print 'passed', seconds_passed
163 self.__plot()
164 seconds_passed = 0
142 165
143 166 except zmq.Again as e:
144 167 print 'Waiting for data...'
145 plt.pause(self.throttle_value)
168 plt.pause(2)
169 seconds_passed += 2
146 170
147 171 def close(self):
148 172 if self.dataOut:
149 173 self.__plot()
150 174
151 175
152 176 class PlotSpectraData(PlotData):
153 177
154 178 CODE = 'spc'
155 179 colormap = 'jro'
156 180 CONFLATE = False
157 181
158 182 def setup(self):
159 183
160 184 ncolspan = 1
161 185 colspan = 1
162 186 self.ncols = int(numpy.sqrt(self.dataOut.nChannels)+0.9)
163 187 self.nrows = int(self.dataOut.nChannels*1./self.ncols + 0.9)
164 188 self.width = 3.6*self.ncols
165 189 self.height = 3.2*self.nrows
166 190 if self.showprofile:
167 191 ncolspan = 3
168 192 colspan = 2
169 193 self.width += 1.2*self.ncols
170 194
171 195 self.ylabel = 'Range [Km]'
172 196 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
173 197
174 198 if self.figure is None:
175 199 self.figure = plt.figure(figsize=(self.width, self.height),
176 200 edgecolor='k',
177 201 facecolor='w')
178 202 else:
179 203 self.figure.clf()
180 204
181 205 n = 0
182 206 for y in range(self.nrows):
183 207 for x in range(self.ncols):
184 208 if n >= self.dataOut.nChannels:
185 209 break
186 210 ax = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan), 1, colspan)
187 211 if self.showprofile:
188 212 ax.ax_profile = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan+colspan), 1, 1)
189 213
190 214 ax.firsttime = True
191 215 self.axes.append(ax)
192 216 n += 1
193 217
194 218 def plot(self):
195 219
196 220 if self.xaxis == "frequency":
197 221 x = self.dataOut.getFreqRange(1)/1000.
198 222 xlabel = "Frequency (kHz)"
199 223 elif self.xaxis == "time":
200 224 x = self.dataOut.getAcfRange(1)
201 225 xlabel = "Time (ms)"
202 226 else:
203 227 x = self.dataOut.getVelRange(1)
204 228 xlabel = "Velocity (m/s)"
205 229
206 230 y = self.dataOut.getHeiRange()
207 231 z = self.data[self.CODE]
208 232
209 233 for n, ax in enumerate(self.axes):
210 234
211 235 if ax.firsttime:
212 236 self.xmax = self.xmax if self.xmax else np.nanmax(x)
213 237 self.xmin = self.xmin if self.xmin else -self.xmax
214 238 self.ymin = self.ymin if self.ymin else np.nanmin(y)
215 239 self.ymax = self.ymax if self.ymax else np.nanmax(y)
216 240 self.zmin = self.zmin if self.zmin else np.nanmin(z)
217 241 self.zmax = self.zmax if self.zmax else np.nanmax(z)
218 242 ax.plot = ax.pcolormesh(x, y, z[n].T,
219 243 vmin=self.zmin,
220 244 vmax=self.zmax,
221 245 cmap=plt.get_cmap(self.colormap)
222 246 )
223 247 divider = make_axes_locatable(ax)
224 248 cax = divider.new_horizontal(size='3%', pad=0.05)
225 249 self.figure.add_axes(cax)
226 250 plt.colorbar(ax.plot, cax)
227 251
228 252 ax.set_xlim(self.xmin, self.xmax)
229 253 ax.set_ylim(self.ymin, self.ymax)
230 254
231 255 ax.set_ylabel(self.ylabel)
232 256 ax.set_xlabel(xlabel)
233 257
234 258 ax.firsttime = False
235 259
236 260 if self.showprofile:
237 261 ax.plot_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
238 262 ax.ax_profile.set_xlim(self.zmin, self.zmax)
239 263 ax.ax_profile.set_ylim(self.ymin, self.ymax)
240 264 ax.ax_profile.set_xlabel('dB')
241 265 ax.ax_profile.grid(b=True, axis='x')
242 266 ax.plot_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
243 267 color="k", linestyle="dashed", lw=2)[0]
244 268 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
245 269 else:
246 270 ax.plot.set_array(z[n].T.ravel())
247 271 if self.showprofile:
248 272 ax.plot_profile.set_data(self.data['rti'][self.max_time][n], y)
249 273 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
250 274
251 275 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
252 276 size=8)
253 277 self.saveTime = self.max_time
254 278
255 279
256 280 class PlotCrossSpectraData(PlotData):
257 281
258 282 CODE = 'cspc'
259 283 zmin_coh = None
260 284 zmax_coh = None
261 285 zmin_phase = None
262 286 zmax_phase = None
263 287 CONFLATE = False
264 288
265 289 def setup(self):
266 290
267 291 ncolspan = 1
268 292 colspan = 1
269 293 self.ncols = 2
270 294 self.nrows = self.dataOut.nPairs
271 295 self.width = 3.6*self.ncols
272 296 self.height = 3.2*self.nrows
273 297
274 298 self.ylabel = 'Range [Km]'
275 299 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
276 300
277 301 if self.figure is None:
278 302 self.figure = plt.figure(figsize=(self.width, self.height),
279 303 edgecolor='k',
280 304 facecolor='w')
281 305 else:
282 306 self.figure.clf()
283 307
284 308 for y in range(self.nrows):
285 309 for x in range(self.ncols):
286 310 ax = plt.subplot2grid((self.nrows, self.ncols), (y, x), 1, 1)
287 311 ax.firsttime = True
288 312 self.axes.append(ax)
289 313
290 314 def plot(self):
291 315
292 316 if self.xaxis == "frequency":
293 317 x = self.dataOut.getFreqRange(1)/1000.
294 318 xlabel = "Frequency (kHz)"
295 319 elif self.xaxis == "time":
296 320 x = self.dataOut.getAcfRange(1)
297 321 xlabel = "Time (ms)"
298 322 else:
299 323 x = self.dataOut.getVelRange(1)
300 324 xlabel = "Velocity (m/s)"
301 325
302 326 y = self.dataOut.getHeiRange()
303 327 z_coh = self.data['cspc_coh']
304 328 z_phase = self.data['cspc_phase']
305 329
306 330 for n in range(self.nrows):
307 331 ax = self.axes[2*n]
308 332 ax1 = self.axes[2*n+1]
309 333 if ax.firsttime:
310 334 self.xmax = self.xmax if self.xmax else np.nanmax(x)
311 335 self.xmin = self.xmin if self.xmin else -self.xmax
312 336 self.ymin = self.ymin if self.ymin else np.nanmin(y)
313 337 self.ymax = self.ymax if self.ymax else np.nanmax(y)
314 338 self.zmin_coh = self.zmin_coh if self.zmin_coh else 0.0
315 339 self.zmax_coh = self.zmax_coh if self.zmax_coh else 1.0
316 340 self.zmin_phase = self.zmin_phase if self.zmin_phase else -180
317 341 self.zmax_phase = self.zmax_phase if self.zmax_phase else 180
318 342
319 343 ax.plot = ax.pcolormesh(x, y, z_coh[n].T,
320 344 vmin=self.zmin_coh,
321 345 vmax=self.zmax_coh,
322 346 cmap=plt.get_cmap(self.colormap_coh)
323 347 )
324 348 divider = make_axes_locatable(ax)
325 349 cax = divider.new_horizontal(size='3%', pad=0.05)
326 350 self.figure.add_axes(cax)
327 351 plt.colorbar(ax.plot, cax)
328 352
329 353 ax.set_xlim(self.xmin, self.xmax)
330 354 ax.set_ylim(self.ymin, self.ymax)
331 355
332 356 ax.set_ylabel(self.ylabel)
333 357 ax.set_xlabel(xlabel)
334 358 ax.firsttime = False
335 359
336 360 ax1.plot = ax1.pcolormesh(x, y, z_phase[n].T,
337 361 vmin=self.zmin_phase,
338 362 vmax=self.zmax_phase,
339 363 cmap=plt.get_cmap(self.colormap_phase)
340 364 )
341 365 divider = make_axes_locatable(ax1)
342 366 cax = divider.new_horizontal(size='3%', pad=0.05)
343 367 self.figure.add_axes(cax)
344 368 plt.colorbar(ax1.plot, cax)
345 369
346 370 ax1.set_xlim(self.xmin, self.xmax)
347 371 ax1.set_ylim(self.ymin, self.ymax)
348 372
349 373 ax1.set_ylabel(self.ylabel)
350 374 ax1.set_xlabel(xlabel)
351 375 ax1.firsttime = False
352 376 else:
353 377 ax.plot.set_array(z_coh[n].T.ravel())
354 378 ax1.plot.set_array(z_phase[n].T.ravel())
355 379
356 380 ax.set_title('Coherence Ch{} * Ch{}'.format(self.dataOut.pairsList[n][0], self.dataOut.pairsList[n][1]), size=8)
357 381 ax1.set_title('Phase Ch{} * Ch{}'.format(self.dataOut.pairsList[n][0], self.dataOut.pairsList[n][1]), size=8)
358 382 self.saveTime = self.max_time
359 383
360 384
361 385 class PlotSpectraMeanData(PlotSpectraData):
362 386
363 387 CODE = 'spc_mean'
364 388 colormap = 'jet'
365 389
366 390 def plot(self):
367 391
368 392 if self.xaxis == "frequency":
369 393 x = self.dataOut.getFreqRange(1)/1000.
370 394 xlabel = "Frequency (kHz)"
371 395 elif self.xaxis == "time":
372 396 x = self.dataOut.getAcfRange(1)
373 397 xlabel = "Time (ms)"
374 398 else:
375 399 x = self.dataOut.getVelRange(1)
376 400 xlabel = "Velocity (m/s)"
377 401
378 402 y = self.dataOut.getHeiRange()
379 403 z = self.data['spc']
380 404 mean = self.data['mean'][self.max_time]
381 405
382 406 for n, ax in enumerate(self.axes):
383 407
384 408 if ax.firsttime:
385 409 self.xmax = self.xmax if self.xmax else np.nanmax(x)
386 410 self.xmin = self.xmin if self.xmin else -self.xmax
387 411 self.ymin = self.ymin if self.ymin else np.nanmin(y)
388 412 self.ymax = self.ymax if self.ymax else np.nanmax(y)
389 413 self.zmin = self.zmin if self.zmin else np.nanmin(z)
390 414 self.zmax = self.zmax if self.zmax else np.nanmax(z)
391 415 ax.plt = ax.pcolormesh(x, y, z[n].T,
392 416 vmin=self.zmin,
393 417 vmax=self.zmax,
394 418 cmap=plt.get_cmap(self.colormap)
395 419 )
396 420 ax.plt_dop = ax.plot(mean[n], y,
397 421 color='k')[0]
398 422
399 423 divider = make_axes_locatable(ax)
400 424 cax = divider.new_horizontal(size='3%', pad=0.05)
401 425 self.figure.add_axes(cax)
402 426 plt.colorbar(ax.plt, cax)
403 427
404 428 ax.set_xlim(self.xmin, self.xmax)
405 429 ax.set_ylim(self.ymin, self.ymax)
406 430
407 431 ax.set_ylabel(self.ylabel)
408 432 ax.set_xlabel(xlabel)
409 433
410 434 ax.firsttime = False
411 435
412 436 if self.showprofile:
413 437 ax.plt_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
414 438 ax.ax_profile.set_xlim(self.zmin, self.zmax)
415 439 ax.ax_profile.set_ylim(self.ymin, self.ymax)
416 440 ax.ax_profile.set_xlabel('dB')
417 441 ax.ax_profile.grid(b=True, axis='x')
418 442 ax.plt_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
419 443 color="k", linestyle="dashed", lw=2)[0]
420 444 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
421 445 else:
422 446 ax.plt.set_array(z[n].T.ravel())
423 447 ax.plt_dop.set_data(mean[n], y)
424 448 if self.showprofile:
425 449 ax.plt_profile.set_data(self.data['rti'][self.max_time][n], y)
426 450 ax.plt_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
427 451
428 452 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
429 453 size=8)
430 454 self.saveTime = self.max_time
431 455
432 456
433 457 class PlotRTIData(PlotData):
434 458
435 459 CODE = 'rti'
436 460 colormap = 'jro'
437 461
438 462 def setup(self):
439 463 self.ncols = 1
440 464 self.nrows = self.dataOut.nChannels
441 465 self.width = 10
442 466 self.height = 2.2*self.nrows if self.nrows<6 else 12
443 467 if self.nrows==1:
444 468 self.height += 1
445 469 self.ylabel = 'Range [Km]'
446 470 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
447 471
448 472 if self.figure is None:
449 473 self.figure = plt.figure(figsize=(self.width, self.height),
450 474 edgecolor='k',
451 475 facecolor='w')
452 476 else:
453 477 self.figure.clf()
454 478 self.axes = []
455 479
456 for n in range(self.nrows):
457 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
458 ax.firsttime = True
459 self.axes.append(ax)
480 if self.figure2 is None:
481 self.figure2 = plt.figure(figsize=(self.width, self.height),
482 edgecolor='k',
483 facecolor='w')
484 else:
485 self.figure2.clf()
486 self.axes = []
487
488 ax = self.figure.add_subplot(1,1,1)
489 #ax = self.figure( n+1)
490 ax.firsttime = True
491 self.axes.append(ax)
492
493 ax = self.figure2.add_subplot(1,1,1)
494 #ax = self.figure( n+1)
495 ax.firsttime = True
496 self.axes.append(ax)
497 # for n in range(self.nrows):
498 # ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
499 # #ax = self.figure( n+1)
500 # ax.firsttime = True
501 # self.axes.append(ax)
502
460 503
461 504 def plot(self):
462 505
463 506 self.x = np.array(self.times)
464 507 self.y = self.dataOut.getHeiRange()
465 508 self.z = []
466 509
467 510 for ch in range(self.nrows):
468 511 self.z.append([self.data[self.CODE][t][ch] for t in self.times])
469 512
470 513 self.z = np.array(self.z)
471 514 for n, ax in enumerate(self.axes):
472
473 515 x, y, z = self.fill_gaps(*self.decimate())
474 516 xmin = self.min_time
475 517 xmax = xmin+self.xrange*60*60
518 self.zmin = self.zmin if self.zmin else np.min(self.z)
519 self.zmax = self.zmax if self.zmax else np.max(self.z)
476 520 if ax.firsttime:
477 521 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
478 522 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
479 self.zmin = self.zmin if self.zmin else np.nanmin(self.z)
480 self.zmax = self.zmax if self.zmax else np.nanmax(self.z)
481 523 plot = ax.pcolormesh(x, y, z[n].T,
482 524 vmin=self.zmin,
483 525 vmax=self.zmax,
484 526 cmap=plt.get_cmap(self.colormap)
485 527 )
486 528 divider = make_axes_locatable(ax)
487 529 cax = divider.new_horizontal(size='2%', pad=0.05)
488 self.figure.add_axes(cax)
530 #self.figure.add_axes(cax)
531 #self.figure2.add_axes(cax)
489 532 plt.colorbar(plot, cax)
490 533 ax.set_ylim(self.ymin, self.ymax)
491 534
492 535 ax.xaxis.set_major_formatter(FuncFormatter(func))
493 536 ax.xaxis.set_major_locator(LinearLocator(6))
494 537
495 538 ax.set_ylabel(self.ylabel)
496 539
497 540 # if self.xmin is None:
498 541 # xmin = self.min_time
499 542 # else:
500 543 # xmin = (datetime.datetime.combine(self.dataOut.datatime.date(),
501 544 # datetime.time(self.xmin, 0, 0))-d1970).total_seconds()
502 545
503 546 ax.set_xlim(xmin, xmax)
504 547 ax.firsttime = False
505 548 else:
506 549 ax.collections.remove(ax.collections[0])
507 550 ax.set_xlim(xmin, xmax)
508 551 plot = ax.pcolormesh(x, y, z[n].T,
509 552 vmin=self.zmin,
510 553 vmax=self.zmax,
511 554 cmap=plt.get_cmap(self.colormap)
512 555 )
513 556 ax.set_title('{} {}'.format(self.titles[n],
514 557 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
515 558 size=8)
516 559
517 560 self.saveTime = self.min_time
518 561
519 562
520 563 class PlotCOHData(PlotRTIData):
521 564
522 565 CODE = 'coh'
523 566
524 567 def setup(self):
525 568
526 569 self.ncols = 1
527 570 self.nrows = self.dataOut.nPairs
528 571 self.width = 10
529 572 self.height = 2.2*self.nrows if self.nrows<6 else 12
530 573 if self.nrows==1:
531 574 self.height += 1
532 575 self.ylabel = 'Range [Km]'
533 576 self.titles = ['{} Ch{} * Ch{}'.format(self.CODE.upper(), x[0], x[1]) for x in self.dataOut.pairsList]
534 577
535 578 if self.figure is None:
536 579 self.figure = plt.figure(figsize=(self.width, self.height),
537 580 edgecolor='k',
538 581 facecolor='w')
539 582 else:
540 583 self.figure.clf()
541 584 self.axes = []
542 585
543 586 for n in range(self.nrows):
544 587 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
545 588 ax.firsttime = True
546 589 self.axes.append(ax)
547 590
548 591
549 592 class PlotNoiseData(PlotData):
550 593 CODE = 'noise'
551 594
552 595 def setup(self):
553 596
554 597 self.ncols = 1
555 598 self.nrows = 1
556 599 self.width = 10
557 600 self.height = 3.2
558 601 self.ylabel = 'Intensity [dB]'
559 602 self.titles = ['Noise']
560 603
561 604 if self.figure is None:
562 605 self.figure = plt.figure(figsize=(self.width, self.height),
563 606 edgecolor='k',
564 607 facecolor='w')
565 608 else:
566 609 self.figure.clf()
567 610 self.axes = []
568 611
569 612 self.ax = self.figure.add_subplot(self.nrows, self.ncols, 1)
570 613 self.ax.firsttime = True
571 614
572 615 def plot(self):
573 616
574 617 x = self.times
575 618 xmin = self.min_time
576 619 xmax = xmin+self.xrange*60*60
577 620 if self.ax.firsttime:
578 621 for ch in self.dataOut.channelList:
579 622 y = [self.data[self.CODE][t][ch] for t in self.times]
580 623 self.ax.plot(x, y, lw=1, label='Ch{}'.format(ch))
581 624 self.ax.firsttime = False
582 625 self.ax.xaxis.set_major_formatter(FuncFormatter(func))
583 626 self.ax.xaxis.set_major_locator(LinearLocator(6))
584 627 self.ax.set_ylabel(self.ylabel)
585 628 plt.legend()
586 629 else:
587 630 for ch in self.dataOut.channelList:
588 631 y = [self.data[self.CODE][t][ch] for t in self.times]
589 632 self.ax.lines[ch].set_data(x, y)
590 633
591 634 self.ax.set_xlim(xmin, xmax)
592 635 self.ax.set_ylim(min(y)-5, max(y)+5)
593 636 self.saveTime = self.min_time
594 637
595 638
596 639 class PlotWindProfilerData(PlotRTIData):
597 640 CODE = 'wind'
598 641 colormap = 'seismic'
599 642
600 643 def setup(self):
601 644 self.ncols = 1
602 645 self.nrows = self.dataOut.data_output.shape[0]
603 646 self.width = 10
604 647 self.height = 2.2*self.nrows
605 648 self.ylabel = 'Height [Km]'
606 649 self.titles = ['Zonal' ,'Meridional', 'Vertical']
607 650 self.clabels = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
608 651 self.windFactor = [1, 1, 100]
609 652
610 653 if self.figure is None:
611 654 self.figure = plt.figure(figsize=(self.width, self.height),
612 655 edgecolor='k',
613 656 facecolor='w')
614 657 else:
615 658 self.figure.clf()
616 659 self.axes = []
617 660
618 661 for n in range(self.nrows):
619 662 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
620 663 ax.firsttime = True
621 664 self.axes.append(ax)
622 665
623 666 def plot(self):
624 667
625 668 self.x = np.array(self.times)
626 669 self.y = self.dataOut.heightList
627 670 self.z = []
628 671
629 672 for ch in range(self.nrows):
630 673 self.z.append([self.data[self.CODE][t][ch] for t in self.times])
631 674
632 675 self.z = np.array(self.z)
633 676 self.z = numpy.ma.masked_invalid(self.z)
634 677
635 678 cmap=plt.get_cmap(self.colormap)
636 679 cmap.set_bad('white', 1.)
637 680
638 681 for n, ax in enumerate(self.axes):
639 682 x, y, z = self.fill_gaps(*self.decimate())
640 683 xmin = self.min_time
641 684 xmax = xmin+self.xrange*60*60
642 685 if ax.firsttime:
643 686 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
644 687 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
645 688 self.zmax = self.zmax if self.zmax else numpy.nanmax(abs(self.z[:-1, :]))
646 689 self.zmin = self.zmin if self.zmin else -self.zmax
647 690
648 691 plot = ax.pcolormesh(x, y, z[n].T*self.windFactor[n],
649 692 vmin=self.zmin,
650 693 vmax=self.zmax,
651 694 cmap=cmap
652 695 )
653 696 divider = make_axes_locatable(ax)
654 697 cax = divider.new_horizontal(size='2%', pad=0.05)
655 698 cax.set_ylabel(self.clabels[n])
656 699 self.figure.add_axes(cax)
657 700 plt.colorbar(plot, cax)
658 701 ax.set_ylim(self.ymin, self.ymax)
659 702
660 703 ax.xaxis.set_major_formatter(FuncFormatter(func))
661 704 ax.xaxis.set_major_locator(LinearLocator(6))
662 705
663 706 ax.set_ylabel(self.ylabel)
664 707
665 708 ax.set_xlim(xmin, xmax)
666 709 ax.firsttime = False
667 710 else:
668 711 ax.collections.remove(ax.collections[0])
669 712 ax.set_xlim(xmin, xmax)
670 713 plot = ax.pcolormesh(x, y, z[n].T*self.windFactor[n],
671 714 vmin=self.zmin,
672 715 vmax=self.zmax,
673 716 cmap=plt.get_cmap(self.colormap)
674 717 )
675 718 ax.set_title('{} {}'.format(self.titles[n],
676 719 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
677 720 size=8)
678 721
679 722 self.saveTime = self.min_time
680 723
681 724
682 725 class PlotSNRData(PlotRTIData):
683 726 CODE = 'snr'
684 727 colormap = 'jet'
685 728
686 729 class PlotDOPData(PlotRTIData):
687 730 CODE = 'dop'
688 731 colormap = 'jet'
689 732
690 733
691 734 class PlotPHASEData(PlotCOHData):
692 735 CODE = 'phase'
693 736 colormap = 'seismic'
@@ -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,346 +1,346
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 6 import inspect
7 7 from fuzzywuzzy import process
8 8
9 9 def checkKwargs(method, kwargs):
10 10 currentKwargs = kwargs
11 11 choices = inspect.getargspec(method).args
12 12 try:
13 13 choices.remove('self')
14 14 except Exception as e:
15 15 pass
16 16
17 17 try:
18 18 choices.remove('dataOut')
19 19 except Exception as e:
20 20 pass
21 21
22 22 for kwarg in kwargs:
23 23 fuzz = process.extractOne(kwarg, choices)
24 24 if fuzz is None:
25 25 continue
26 26 if fuzz[1] < 100:
27 raise Exception('\x1b[2;30;43mDid you mean {} instead of {} in {}? \x1b[0m'.
27 raise Exception('\x1b[0;32;40mDid you mean {} instead of {} in {}? \x1b[0m'.
28 28 format(fuzz[0], kwarg, method.__self__.__class__.__name__))
29 29
30 30 class ProcessingUnit(object):
31 31
32 32 """
33 33 Esta es la clase base para el procesamiento de datos.
34 34
35 35 Contiene el metodo "call" para llamar operaciones. Las operaciones pueden ser:
36 36 - Metodos internos (callMethod)
37 37 - Objetos del tipo Operation (callObject). Antes de ser llamados, estos objetos
38 38 tienen que ser agreagados con el metodo "add".
39 39
40 40 """
41 41 # objeto de datos de entrada (Voltage, Spectra o Correlation)
42 42 dataIn = None
43 43 dataInList = []
44 44
45 45 # objeto de datos de entrada (Voltage, Spectra o Correlation)
46 46 dataOut = None
47 47
48 48 operations2RunDict = None
49 49
50 50 isConfig = False
51 51
52 52
53 53 def __init__(self, *args, **kwargs):
54 54
55 55 self.dataIn = None
56 56 self.dataInList = []
57 57
58 58 self.dataOut = None
59 59
60 60 self.operations2RunDict = {}
61 61 self.operationKwargs = {}
62 62
63 63 self.isConfig = False
64 64
65 65 self.args = args
66 66 self.kwargs = kwargs
67 67 checkKwargs(self.run, kwargs)
68 68
69 69 def getAllowedArgs(self):
70 70 return inspect.getargspec(self.run).args
71 71
72 72 def addOperationKwargs(self, objId, **kwargs):
73 73 '''
74 74 '''
75 75
76 76 self.operationKwargs[objId] = kwargs
77 77
78 78
79 79 def addOperation(self, opObj, objId):
80 80
81 81 """
82 82 Agrega un objeto del tipo "Operation" (opObj) a la lista de objetos "self.objectList" y retorna el
83 83 identificador asociado a este objeto.
84 84
85 85 Input:
86 86
87 87 object : objeto de la clase "Operation"
88 88
89 89 Return:
90 90
91 91 objId : identificador del objeto, necesario para ejecutar la operacion
92 92 """
93 93
94 94 self.operations2RunDict[objId] = opObj
95 95
96 96 return objId
97 97
98 98 def getOperationObj(self, objId):
99 99
100 100 if objId not in self.operations2RunDict.keys():
101 101 return None
102 102
103 103 return self.operations2RunDict[objId]
104 104
105 105 def operation(self, **kwargs):
106 106
107 107 """
108 108 Operacion directa sobre la data (dataOut.data). Es necesario actualizar los valores de los
109 109 atributos del objeto dataOut
110 110
111 111 Input:
112 112
113 113 **kwargs : Diccionario de argumentos de la funcion a ejecutar
114 114 """
115 115
116 116 raise NotImplementedError
117 117
118 118 def callMethod(self, name, opId):
119 119
120 120 """
121 121 Ejecuta el metodo con el nombre "name" y con argumentos **kwargs de la propia clase.
122 122
123 123 Input:
124 124 name : nombre del metodo a ejecutar
125 125
126 126 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
127 127
128 128 """
129 129
130 130 #Checking the inputs
131 131 if name == 'run':
132 132
133 133 if not self.checkInputs():
134 134 self.dataOut.flagNoData = True
135 135 return False
136 136 else:
137 137 #Si no es un metodo RUN la entrada es la misma dataOut (interna)
138 138 if self.dataOut is not None and self.dataOut.isEmpty():
139 139 return False
140 140
141 141 #Getting the pointer to method
142 142 methodToCall = getattr(self, name)
143 143
144 144 #Executing the self method
145 145
146 146 if hasattr(self, 'mp'):
147 147 if name=='run':
148 148 if self.mp is False:
149 149 self.mp = True
150 150 self.start()
151 151 else:
152 152 methodToCall(**self.operationKwargs[opId])
153 153 else:
154 154 if name=='run':
155 155 methodToCall(**self.kwargs)
156 156 else:
157 157 methodToCall(**self.operationKwargs[opId])
158 158
159 159 if self.dataOut is None:
160 160 return False
161 161
162 162 if self.dataOut.isEmpty():
163 163 return False
164 164
165 165 return True
166 166
167 167 def callObject(self, objId):
168 168
169 169 """
170 170 Ejecuta la operacion asociada al identificador del objeto "objId"
171 171
172 172 Input:
173 173
174 174 objId : identificador del objeto a ejecutar
175 175
176 176 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
177 177
178 178 Return:
179 179
180 180 None
181 181 """
182 182
183 183 if self.dataOut is not None and self.dataOut.isEmpty():
184 184 return False
185 185
186 186 externalProcObj = self.operations2RunDict[objId]
187 187
188 188 if hasattr(externalProcObj, 'mp'):
189 189 if externalProcObj.mp is False:
190 190 self.operationKwargs[objId] = externalProcObj.kwargs
191 191 externalProcObj.mp = True
192 192 externalProcObj.start()
193 193 else:
194 194 externalProcObj.run(self.dataOut, **externalProcObj.kwargs)
195 195 self.operationKwargs[objId] = externalProcObj.kwargs
196 196
197 197 return True
198 198
199 199 def call(self, opType, opName=None, opId=None):
200 200
201 201 """
202 202 Return True si ejecuta la operacion interna nombrada "opName" o la operacion externa
203 203 identificada con el id "opId"; con los argumentos "**kwargs".
204 204
205 205 False si la operacion no se ha ejecutado.
206 206
207 207 Input:
208 208
209 209 opType : Puede ser "self" o "external"
210 210
211 211 Depende del tipo de operacion para llamar a:callMethod or callObject:
212 212
213 213 1. If opType = "self": Llama a un metodo propio de esta clase:
214 214
215 215 name_method = getattr(self, name)
216 216 name_method(**kwargs)
217 217
218 218
219 219 2. If opType = "other" o"external": Llama al metodo "run()" de una instancia de la
220 220 clase "Operation" o de un derivado de ella:
221 221
222 222 instanceName = self.operationList[opId]
223 223 instanceName.run(**kwargs)
224 224
225 225 opName : Si la operacion es interna (opType = 'self'), entonces el "opName" sera
226 226 usada para llamar a un metodo interno de la clase Processing
227 227
228 228 opId : Si la operacion es externa (opType = 'other' o 'external), entonces el
229 229 "opId" sera usada para llamar al metodo "run" de la clase Operation
230 230 registrada anteriormente con ese Id
231 231
232 232 Exception:
233 233 Este objeto de tipo Operation debe de haber sido agregado antes con el metodo:
234 234 "addOperation" e identificado con el valor "opId" = el id de la operacion.
235 235 De lo contrario retornara un error del tipo ValueError
236 236
237 237 """
238 238
239 239 if opType == 'self':
240 240
241 241 if not opName:
242 242 raise ValueError, "opName parameter should be defined"
243 243
244 244 sts = self.callMethod(opName, opId)
245 245
246 246 elif opType == 'other' or opType == 'external' or opType == 'plotter':
247 247
248 248 if not opId:
249 249 raise ValueError, "opId parameter should be defined"
250 250
251 251 if opId not in self.operations2RunDict.keys():
252 252 raise ValueError, "Any operation with id=%s has been added" %str(opId)
253 253
254 254 sts = self.callObject(opId)
255 255
256 256 else:
257 257 raise ValueError, "opType should be 'self', 'external' or 'plotter'; and not '%s'" %opType
258 258
259 259 return sts
260 260
261 261 def setInput(self, dataIn):
262 262
263 263 self.dataIn = dataIn
264 264 self.dataInList.append(dataIn)
265 265
266 266 def getOutputObj(self):
267 267
268 268 return self.dataOut
269 269
270 270 def checkInputs(self):
271 271
272 272 for thisDataIn in self.dataInList:
273 273
274 274 if thisDataIn.isEmpty():
275 275 return False
276 276
277 277 return True
278 278
279 279 def setup(self):
280 280
281 281 raise NotImplementedError
282 282
283 283 def run(self):
284 284
285 285 raise NotImplementedError
286 286
287 287 def close(self):
288 288 #Close every thread, queue or any other object here is it is neccesary.
289 289 return
290 290
291 291 class Operation(object):
292 292
293 293 """
294 294 Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit
295 295 y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de
296 296 acumulacion dentro de esta clase
297 297
298 298 Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer)
299 299
300 300 """
301 301
302 302 __buffer = None
303 303 isConfig = False
304 304
305 305 def __init__(self, **kwargs):
306 306
307 307 self.__buffer = None
308 308 self.isConfig = False
309 309 self.kwargs = kwargs
310 310 checkKwargs(self.run, kwargs)
311 311
312 312 def getAllowedArgs(self):
313 313 return inspect.getargspec(self.run).args
314 314
315 315 def setup(self):
316 316
317 317 self.isConfig = True
318 318
319 319 raise NotImplementedError
320 320
321 321 def run(self, dataIn, **kwargs):
322 322
323 323 """
324 324 Realiza las operaciones necesarias sobre la dataIn.data y actualiza los
325 325 atributos del objeto dataIn.
326 326
327 327 Input:
328 328
329 329 dataIn : objeto del tipo JROData
330 330
331 331 Return:
332 332
333 333 None
334 334
335 335 Affected:
336 336 __buffer : buffer de recepcion de datos.
337 337
338 338 """
339 339 if not self.isConfig:
340 340 self.setup(**kwargs)
341 341
342 342 raise NotImplementedError
343 343
344 344 def close(self):
345 345
346 346 pass
@@ -1,445 +1,457
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 == 'wind':
371 377 self.data[plottype][t] = self.dataOut.data_output
372 378 if self.realtime:
373 379 self.data_web['timestamp'] = t
374 380 if plottype == 'spc':
375 381 self.data_web[plottype] = roundFloats(decimate(self.data[plottype]).tolist())
376 382 elif plottype == 'cspc':
377 383 self.data_web['cspc_coh'] = roundFloats(decimate(self.data['cspc_coh']).tolist())
378 384 self.data_web['cspc_phase'] = roundFloats(decimate(self.data['cspc_phase']).tolist())
379 385 elif plottype == 'noise':
380 386 self.data_web['noise'] = roundFloats(self.data['noise'][t].tolist())
381 387 else:
382 388 self.data_web[plottype] = roundFloats(decimate(self.data[plottype][t]).tolist())
383 389 self.data_web['interval'] = self.dataOut.getTimeInterval()
384 390 self.data_web['type'] = plottype
385 391
386 392 def run(self):
387 393
388 394 print '[Starting] {} from {}'.format(self.name, self.address)
389 395
390 396 self.context = zmq.Context()
391 397 self.receiver = self.context.socket(zmq.PULL)
392 398 self.receiver.bind(self.address)
393 399 monitor = self.receiver.get_monitor_socket()
394 400 self.sender = self.context.socket(zmq.PUB)
395 401 if self.realtime:
396 402 self.sender_web = self.context.socket(zmq.PUB)
397 403 self.sender_web.connect(self.plot_address)
398 404 time.sleep(1)
399 405 self.sender.bind("ipc:///tmp/zmq.plots")
400
406 time.sleep(3)
401 407 t = Thread(target=self.event_monitor, args=(monitor,))
402 408 t.start()
403 409
404 410 while True:
405 411 self.dataOut = self.receiver.recv_pyobj()
406 412 # print '[Receiving] {} - {}'.format(self.dataOut.type,
407 413 # self.dataOut.datatime.ctime())
408 414
409 415 self.update()
410 416
417 if self.dataOut.firstdata is True:
418 self.data['STARTED'] = True
419
420
411 421 if self.dataOut.finished is True:
412 422 self.send(self.data)
413 423 self.connections -= 1
414 424 if self.connections == 0 and self.started:
415 425 self.ended = True
416 426 self.data['ENDED'] = True
417 427 self.send(self.data)
418 428 self.setup()
429 self.started = False
419 430 else:
420 431 if self.realtime:
421 432 self.send(self.data)
422 433 self.sender_web.send_string(json.dumps(self.data_web))
423 434 else:
424 435 self.sendData(self.send, self.data)
425 436 self.started = True
426 437
438 self.data['STARTED'] = False
427 439 return
428 440
429 441 def sendToWeb(self):
430 442
431 443 if not self.isWebConfig:
432 444 context = zmq.Context()
433 445 sender_web_config = context.socket(zmq.PUB)
434 446 if 'tcp://' in self.plot_address:
435 447 dum, address, port = self.plot_address.split(':')
436 448 conf_address = '{}:{}:{}'.format(dum, address, int(port)+1)
437 449 else:
438 450 conf_address = self.plot_address + '.config'
439 451 sender_web_config.bind(conf_address)
440 452 time.sleep(1)
441 453 for kwargs in self.operationKwargs.values():
442 454 if 'plot' in kwargs:
443 455 print '[Sending] Config data to web for {}'.format(kwargs['code'].upper())
444 456 sender_web_config.send_string(json.dumps(kwargs))
445 457 self.isWebConfig = True
@@ -1,99 +1,100
1 1 import argparse
2 2
3 3 from schainpy.controller import Project, multiSchain
4 4
5 5 desc = "HF_EXAMPLE"
6 6 path='/home/ci-81/Documents/DATA/HFADATA/hfdata_2017/pdata/sp1_f0'
7 path = '/media/ci-81/Huancayo/DATA/hfradar_2016/pdata/sp1_f1'
7 8 def fiber(cursor, skip, q, dt):
8 9
9 10 controllerObj = Project()
10 11
11 12 controllerObj.setup(id='191', name='test01', description=desc)
12 13
13 14 readUnitConfObj = controllerObj.addReadUnit(datatype='SpectraReader',
14 15 path=path,
15 16 startDate=dt,
16 17 endDate=dt,
17 18 startTime="00:00:00",
18 19 endTime="23:59:59",
19 20 online=0,
20 21 #set=1426485881,
21 22 delay=10,
22 23 walk=1,
23 24 queue=q,
24 25 cursor=cursor,
25 26 skip=skip,
26 27 #timezone=-5*3600
27 28 )
28 29
29 30 # #opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock')
30 31 #
31 32 procUnitConfObj2 = controllerObj.addProcUnit(datatype='Spectra', inputId=readUnitConfObj.getId())
32 33 opObj10 = procUnitConfObj2.addOperation(name='removeInterference')
33 34
34 35 # procUnitConfObj2.addParameter(name='nipp', value='5', format='int')
35 36
36 37 procUnitConfObj3 = controllerObj.addProcUnit(datatype='ParametersProc', inputId=readUnitConfObj.getId())
37 38 opObj11 = procUnitConfObj3.addOperation(name='SpectralMoments', optype='other')
38 39
39 40 #
40 41 # opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='other')
41 42 # opObj11.addParameter(name='id', value='1000', format='int')
42 43 # opObj11.addParameter(name='wintitle', value='HF_Jicamarca_Spc', format='str')
43 44 # opObj11.addParameter(name='channelList', value='0', format='intlist')
44 45 # opObj11.addParameter(name='zmin', value='-120', format='float')
45 46 # opObj11.addParameter(name='zmax', value='-70', format='float')
46 47 # opObj11.addParameter(name='save', value='1', format='int')
47 48 # opObj11.addParameter(name='figpath', value=figpath, format='str')
48 49
49 50 # opObj11 = procUnitConfObj3.addOperation(name='Parameters1Plot', optype='other')
50 51 # opObj11.addParameter(name='channelList', value='0', format='intList')
51 52
52 53 # opObj11.addParameter(name='id', value='2000', format='int')
53 54 # opObj11.addParameter(name='colormap', value='0', format='bool')
54 55 # opObj11.addParameter(name='onlySNR', value='1', format='bool')
55 56 # opObj11.addParameter(name='DOP', value='0', format='bool')
56 57 # opObj11.addParameter(name='showSNR', value='1', format='bool')
57 58 # opObj11.addParameter(name='SNRthresh', value='0', format='int')
58 59 # opObj11.addParameter(name='SNRmin', value='-10', format='int')
59 60 # opObj11.addParameter(name='SNRmax', value='30', format='int')
60 61
61 62 # opObj11.addParameter(name='showSNR', value='1', format='int')
62 63 # # opObj11.addParameter(name='channelList', value='0', format='intlist')
63 64 # # opObj11.addParameter(name='xmin', value='0', format='float')
64 65 # opObj11.addParameter(name='xmin', value='0', format='float')
65 66 # opObj11.addParameter(name='xmax', value='24', format='float')
66 67
67 68 # opObj11.addParameter(name='zmin', value='-110', format='float')
68 69 # opObj11.addParameter(name='zmax', value='-70', format='float')
69 70 # opObj11.addParameter(name='save', value='0', format='int')
70 71 # # opObj11.addParameter(name='figpath', value='/tmp/', format='str')
71 72 #
72 73 opObj12 = procUnitConfObj3.addOperation(name='PublishData', optype='other')
73 74 #opObj12.addParameter(name='server', value='tcp://10.10.10.82:3001', format='int')
74 75 opObj12.addParameter(name='zeromq', value=1, format='int')
75 76
76 77
77 78 # opObj13 = procUnitConfObj3.addOperation(name='PublishData', optype='other')
78 79 # opObj13.addParameter(name='zeromq', value=1, format='int')
79 80 # opObj13.addParameter(name='server', value="juanca", format='str')
80 81
81 82 # opObj12.addParameter(name='delay', value=1, format='int')
82 83
83 84
84 85 # print "Escribiendo el archivo XML"
85 86 # controllerObj.writeXml(filename)
86 87 # print "Leyendo el archivo XML"
87 88 # controllerObj.readXml(filename)
88 89
89 90
90 91 # timeit.timeit('controllerObj.run()', number=2)
91 92
92 93 controllerObj.start()
93 94
94 95
95 96 if __name__ == '__main__':
96 97 parser = argparse.ArgumentParser(description='Set number of parallel processes')
97 98 parser.add_argument('--nProcess', default=1, type=int)
98 99 args = parser.parse_args()
99 multiSchain(fiber, nProcess=8, startDate='2017/02/10', endDate='2017/02/12')
100 multiSchain(fiber, nProcess=8, startDate='2016/04/23', endDate='2016/04/27')
@@ -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,78 +1,78
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 19 #proc1.addParameter(name='plottypes', value='rti,coh,phase,snr,dop', format='str')
20 proc1.addParameter(name='plottypes', value='rti,coh,phase,snr', format='str')
20 #proc1.addParameter(name='plottypes', value='rti,coh,phase,snr', format='str')
21 proc1.addParameter(name='plottypes', value='dop', format='str')
22
21 23 proc1.addParameter(name='throttle', value='10', format='int')
22 24 #proc1.addParameter(name='server', value='tcp://10.10.10.82:7000', format='str')
23 25 ## TODO Agregar direccion de server de publicacion a graficos como variable
24 26
27 """
25 28 op1 = proc1.addOperation(name='PlotRTIData', optype='other')
26 29 op1.addParameter(name='wintitle', value='HF System', format='str')
27 30 op1.addParameter(name='save', value='/home/ci-81/Pictures', format='str')
28 31 op1.addParameter(name='show', value='0', format='bool')
29 32 op1.addParameter(name='zmin', value='-110', format='float')
30 33 op1.addParameter(name='zmax', value='-50', format='float')
31 34 op1.addParameter(name='colormap', value='jet', format='str')
32 35 #
33 36 op2 = proc1.addOperation(name='PlotCOHData', optype='other')
34 37 op2.addParameter(name='wintitle', value='HF System', format='str')
35 38 op2.addParameter(name='zmin', value='0.001', format='float')
36 39 op2.addParameter(name='zmax', value='1', format='float')
37 40 op2.addParameter(name='save', value='/home/ci-81/Pictures', format='str')
38 41 op2.addParameter(name='colormap', value='jet', format='str')
39 42 op2.addParameter(name='show', value='0', format='bool')
40 43 # #
41 44
42 45 op6 = proc1.addOperation(name='PlotPHASEData', optype='other')
43 46 op6.addParameter(name='wintitle', value='HF System', format='str')
44 47 op6.addParameter(name='save', value='/home/ci-81/Pictures', format='str')
45 48 op6.addParameter(name='show', value='1', format='bool')
46 49 #
47 50
48 51 # proc2 = controllerObj.addProcUnit(name='ReceiverData')
49 52 # proc2.addParameter(name='server', value='juanca', format='str')
50 53 # proc2.addParameter(name='plottypes', value='snr,dop', format='str')
51 54 #
55
52 56 op3 = proc1.addOperation(name='PlotSNRData', optype='other')
53 57 op3.addParameter(name='wintitle', value='HF System SNR0', format='str')
54 58 op3.addParameter(name='save', value='/home/ci-81/Pictures', format='str')
55 59 op3.addParameter(name='show', value='0', format='bool')
56 60 op3.addParameter(name='zmin', value='-10', format='int')
57 61 op3.addParameter(name='zmax', value='30', format='int')
58 62 op3.addParameter(name='SNRthresh', value='0', format='float')
63 """
59 64 #
65 op5 = proc1.addOperation(name='PlotDOPData', optype='other')
66 op5.addParameter(name='wintitle', value='HF System DOP', format='str')
67 op5.addParameter(name='save', value='/home/ci-81/Pictures', format='str')
68 op5.addParameter(name='show', value='1', format='bool')
69 op5.addParameter(name='zmin', value='-120', format='float')
70 op5.addParameter(name='zmax', value='120', format='float')
71 op5.addParameter(name='colormap', value='RdBu_r', format='str')
60 72 """
61 73 op4 = proc1.addOperation(name='PlotSNRData1', optype='other')
62 74 op4.addParameter(name='wintitle', value='HF System SNR1', format='str')
63 75 op4.addParameter(name='save', value='/home/ci-81/Pictures', format='str')
64 76 op4.addParameter(name='show', value='0', format='bool')
65
66
67 op5 = proc1.addOperation(name='PlotDOPData', optype='other')
68 op5.addParameter(name='wintitle', value='HF System DOP', format='str')
69 op5.addParameter(name='save', value='/home/ci-81/Pictures', format='str')
70 op5.addParameter(name='show', value='0', format='bool')
71 op5.addParameter(name='colormap', value='jet', format='str')
72 77 """
73
74
75
76
77
78 78 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/ci-81/Documents/DATA/HFADATA/hfdata_2017/pdata/sp1_f0" /><Parameter format="date" id="191113" name="startDate" value="2017/02/12" /><Parameter format="date" id="191114" name="endDate" value="2017/02/12" /><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="9" /><Parameter format="int" id="191119" name="skip" value="90" /><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" /></Operation></ProcUnit><ProcUnit datatype="Spectra" id="1912" inputId="1911" name="SpectraProc"><Operation id="19121" name="run" priority="1" type="self" /><Operation id="19122" name="removeInterference" priority="2" 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="/media/ci-81/Huancayo/DATA/hfradar_2016/pdata/sp1_f1" /><Parameter format="date" id="191113" name="startDate" value="2016/04/23" /><Parameter format="date" id="191114" name="endDate" value="2016/04/23" /><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="6" /><Parameter format="int" id="191119" name="skip" value="16" /><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" /></Operation></ProcUnit><ProcUnit datatype="Spectra" id="1912" inputId="1911" name="SpectraProc"><Operation id="19121" name="run" priority="1" type="self" /><Operation id="19122" name="removeInterference" priority="2" 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