##// END OF EJS Templates
set new matplotlib version in setup, improved searchFiles for multiprocessing
Juan C. Espinoza -
r1112:4bbef2dc4ffc
parent child
Show More
@@ -1,1317 +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 11 import time
12 12 from multiprocessing import Process, cpu_count
13 13
14 14 from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring
15 15 from xml.dom import minidom
16 16
17 17 import schainpy
18 18 import schainpy.admin
19 19 from schainpy.model import *
20 20 from schainpy.utils import log
21 21
22 22 DTYPES = {
23 23 'Voltage': '.r',
24 24 'Spectra': '.pdata'
25 25 }
26 26
27 27
28 28 def MPProject(project, n=cpu_count()):
29 29 '''
30 30 Project wrapper to run schain in n processes
31 31 '''
32 32
33 33 rconf = project.getReadUnitObj()
34 34 op = rconf.getOperationObj('run')
35 35 dt1 = op.getParameterValue('startDate')
36 36 dt2 = op.getParameterValue('endDate')
37 tm1 = op.getParameterValue('startTime')
38 tm2 = op.getParameterValue('endTime')
37 39 days = (dt2 - dt1).days
38 40
39 41 for day in range(days + 1):
40 42 skip = 0
41 43 cursor = 0
42 44 processes = []
43 45 dt = dt1 + datetime.timedelta(day)
44 46 dt_str = dt.strftime('%Y/%m/%d')
45 47 reader = JRODataReader()
46 48 paths, files = reader.searchFilesOffLine(path=rconf.path,
47 49 startDate=dt,
48 50 endDate=dt,
51 startTime=tm1,
52 endTime=tm2,
49 53 ext=DTYPES[rconf.datatype])
50 54 nFiles = len(files)
51 55 if nFiles == 0:
52 56 continue
53 57 skip = int(math.ceil(nFiles / n))
54 58 while nFiles > cursor * skip:
55 59 rconf.update(startDate=dt_str, endDate=dt_str, cursor=cursor,
56 60 skip=skip)
57 61 p = project.clone()
58 62 p.start()
59 63 processes.append(p)
60 64 cursor += 1
61 65
62 66 def beforeExit(exctype, value, trace):
63 67 for process in processes:
64 68 process.terminate()
65 69 process.join()
66 70 print traceback.print_tb(trace)
67 71
68 72 sys.excepthook = beforeExit
69 73
70 74 for process in processes:
71 75 process.join()
72 76 process.terminate()
73 77
74 78 time.sleep(3)
75 79
76 80
77 81 class ParameterConf():
78 82
79 83 id = None
80 84 name = None
81 85 value = None
82 86 format = None
83 87
84 88 __formated_value = None
85 89
86 90 ELEMENTNAME = 'Parameter'
87 91
88 92 def __init__(self):
89 93
90 94 self.format = 'str'
91 95
92 96 def getElementName(self):
93 97
94 98 return self.ELEMENTNAME
95 99
96 100 def getValue(self):
97 101
98 102 value = self.value
99 103 format = self.format
100 104
101 105 if self.__formated_value != None:
102 106
103 107 return self.__formated_value
104 108
105 109 if format == 'obj':
106 110 return value
107 111
108 112 if format == 'str':
109 113 self.__formated_value = str(value)
110 114 return self.__formated_value
111 115
112 116 if value == '':
113 117 raise ValueError, '%s: This parameter value is empty' % self.name
114 118
115 119 if format == 'list':
116 120 strList = value.split(',')
117 121
118 122 self.__formated_value = strList
119 123
120 124 return self.__formated_value
121 125
122 126 if format == 'intlist':
123 127 '''
124 128 Example:
125 129 value = (0,1,2)
126 130 '''
127 131
128 132 new_value = ast.literal_eval(value)
129 133
130 134 if type(new_value) not in (tuple, list):
131 135 new_value = [int(new_value)]
132 136
133 137 self.__formated_value = new_value
134 138
135 139 return self.__formated_value
136 140
137 141 if format == 'floatlist':
138 142 '''
139 143 Example:
140 144 value = (0.5, 1.4, 2.7)
141 145 '''
142 146
143 147 new_value = ast.literal_eval(value)
144 148
145 149 if type(new_value) not in (tuple, list):
146 150 new_value = [float(new_value)]
147 151
148 152 self.__formated_value = new_value
149 153
150 154 return self.__formated_value
151 155
152 156 if format == 'date':
153 157 strList = value.split('/')
154 158 intList = [int(x) for x in strList]
155 159 date = datetime.date(intList[0], intList[1], intList[2])
156 160
157 161 self.__formated_value = date
158 162
159 163 return self.__formated_value
160 164
161 165 if format == 'time':
162 166 strList = value.split(':')
163 167 intList = [int(x) for x in strList]
164 168 time = datetime.time(intList[0], intList[1], intList[2])
165 169
166 170 self.__formated_value = time
167 171
168 172 return self.__formated_value
169 173
170 174 if format == 'pairslist':
171 175 '''
172 176 Example:
173 177 value = (0,1),(1,2)
174 178 '''
175 179
176 180 new_value = ast.literal_eval(value)
177 181
178 182 if type(new_value) not in (tuple, list):
179 183 raise ValueError, '%s has to be a tuple or list of pairs' % value
180 184
181 185 if type(new_value[0]) not in (tuple, list):
182 186 if len(new_value) != 2:
183 187 raise ValueError, '%s has to be a tuple or list of pairs' % value
184 188 new_value = [new_value]
185 189
186 190 for thisPair in new_value:
187 191 if len(thisPair) != 2:
188 192 raise ValueError, '%s has to be a tuple or list of pairs' % value
189 193
190 194 self.__formated_value = new_value
191 195
192 196 return self.__formated_value
193 197
194 198 if format == 'multilist':
195 199 '''
196 200 Example:
197 201 value = (0,1,2),(3,4,5)
198 202 '''
199 203 multiList = ast.literal_eval(value)
200 204
201 205 if type(multiList[0]) == int:
202 206 multiList = ast.literal_eval('(' + value + ')')
203 207
204 208 self.__formated_value = multiList
205 209
206 210 return self.__formated_value
207 211
208 212 if format == 'bool':
209 213 value = int(value)
210 214
211 215 if format == 'int':
212 216 value = float(value)
213 217
214 218 format_func = eval(format)
215 219
216 220 self.__formated_value = format_func(value)
217 221
218 222 return self.__formated_value
219 223
220 224 def updateId(self, new_id):
221 225
222 226 self.id = str(new_id)
223 227
224 228 def setup(self, id, name, value, format='str'):
225 229 self.id = str(id)
226 230 self.name = name
227 231 if format == 'obj':
228 232 self.value = value
229 233 else:
230 234 self.value = str(value)
231 235 self.format = str.lower(format)
232 236
233 237 self.getValue()
234 238
235 239 return 1
236 240
237 241 def update(self, name, value, format='str'):
238 242
239 243 self.name = name
240 244 self.value = str(value)
241 245 self.format = format
242 246
243 247 def makeXml(self, opElement):
244 248 if self.name not in ('queue',):
245 249 parmElement = SubElement(opElement, self.ELEMENTNAME)
246 250 parmElement.set('id', str(self.id))
247 251 parmElement.set('name', self.name)
248 252 parmElement.set('value', self.value)
249 253 parmElement.set('format', self.format)
250 254
251 255 def readXml(self, parmElement):
252 256
253 257 self.id = parmElement.get('id')
254 258 self.name = parmElement.get('name')
255 259 self.value = parmElement.get('value')
256 260 self.format = str.lower(parmElement.get('format'))
257 261
258 262 # Compatible with old signal chain version
259 263 if self.format == 'int' and self.name == 'idfigure':
260 264 self.name = 'id'
261 265
262 266 def printattr(self):
263 267
264 268 print 'Parameter[%s]: name = %s, value = %s, format = %s' % (self.id, self.name, self.value, self.format)
265 269
266 270
267 271 class OperationConf():
268 272
269 273 id = None
270 274 name = None
271 275 priority = None
272 276 type = None
273 277
274 278 parmConfObjList = []
275 279
276 280 ELEMENTNAME = 'Operation'
277 281
278 282 def __init__(self):
279 283
280 284 self.id = '0'
281 285 self.name = None
282 286 self.priority = None
283 287 self.type = 'self'
284 288
285 289 def __getNewId(self):
286 290
287 291 return int(self.id) * 10 + len(self.parmConfObjList) + 1
288 292
289 293 def updateId(self, new_id):
290 294
291 295 self.id = str(new_id)
292 296
293 297 n = 1
294 298 for parmObj in self.parmConfObjList:
295 299
296 300 idParm = str(int(new_id) * 10 + n)
297 301 parmObj.updateId(idParm)
298 302
299 303 n += 1
300 304
301 305 def getElementName(self):
302 306
303 307 return self.ELEMENTNAME
304 308
305 309 def getParameterObjList(self):
306 310
307 311 return self.parmConfObjList
308 312
309 313 def getParameterObj(self, parameterName):
310 314
311 315 for parmConfObj in self.parmConfObjList:
312 316
313 317 if parmConfObj.name != parameterName:
314 318 continue
315 319
316 320 return parmConfObj
317 321
318 322 return None
319 323
320 324 def getParameterObjfromValue(self, parameterValue):
321 325
322 326 for parmConfObj in self.parmConfObjList:
323 327
324 328 if parmConfObj.getValue() != parameterValue:
325 329 continue
326 330
327 331 return parmConfObj.getValue()
328 332
329 333 return None
330 334
331 335 def getParameterValue(self, parameterName):
332 336
333 337 parameterObj = self.getParameterObj(parameterName)
334 338
335 339 # if not parameterObj:
336 340 # return None
337 341
338 342 value = parameterObj.getValue()
339 343
340 344 return value
341 345
342 346 def getKwargs(self):
343 347
344 348 kwargs = {}
345 349
346 350 for parmConfObj in self.parmConfObjList:
347 351 if self.name == 'run' and parmConfObj.name == 'datatype':
348 352 continue
349 353
350 354 kwargs[parmConfObj.name] = parmConfObj.getValue()
351 355
352 356 return kwargs
353 357
354 358 def setup(self, id, name, priority, type):
355 359
356 360 self.id = str(id)
357 361 self.name = name
358 362 self.type = type
359 363 self.priority = priority
360 364
361 365 self.parmConfObjList = []
362 366
363 367 def removeParameters(self):
364 368
365 369 for obj in self.parmConfObjList:
366 370 del obj
367 371
368 372 self.parmConfObjList = []
369 373
370 374 def addParameter(self, name, value, format='str'):
371 375
372 376 if value is None:
373 377 return None
374 378 id = self.__getNewId()
375 379
376 380 parmConfObj = ParameterConf()
377 381 if not parmConfObj.setup(id, name, value, format):
378 382 return None
379 383
380 384 self.parmConfObjList.append(parmConfObj)
381 385
382 386 return parmConfObj
383 387
384 388 def changeParameter(self, name, value, format='str'):
385 389
386 390 parmConfObj = self.getParameterObj(name)
387 391 parmConfObj.update(name, value, format)
388 392
389 393 return parmConfObj
390 394
391 395 def makeXml(self, procUnitElement):
392 396
393 397 opElement = SubElement(procUnitElement, self.ELEMENTNAME)
394 398 opElement.set('id', str(self.id))
395 399 opElement.set('name', self.name)
396 400 opElement.set('type', self.type)
397 401 opElement.set('priority', str(self.priority))
398 402
399 403 for parmConfObj in self.parmConfObjList:
400 404 parmConfObj.makeXml(opElement)
401 405
402 406 def readXml(self, opElement):
403 407
404 408 self.id = opElement.get('id')
405 409 self.name = opElement.get('name')
406 410 self.type = opElement.get('type')
407 411 self.priority = opElement.get('priority')
408 412
409 413 # Compatible with old signal chain version
410 414 # Use of 'run' method instead 'init'
411 415 if self.type == 'self' and self.name == 'init':
412 416 self.name = 'run'
413 417
414 418 self.parmConfObjList = []
415 419
416 420 parmElementList = opElement.iter(ParameterConf().getElementName())
417 421
418 422 for parmElement in parmElementList:
419 423 parmConfObj = ParameterConf()
420 424 parmConfObj.readXml(parmElement)
421 425
422 426 # Compatible with old signal chain version
423 427 # If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER
424 428 if self.type != 'self' and self.name == 'Plot':
425 429 if parmConfObj.format == 'str' and parmConfObj.name == 'type':
426 430 self.name = parmConfObj.value
427 431 continue
428 432
429 433 self.parmConfObjList.append(parmConfObj)
430 434
431 435 def printattr(self):
432 436
433 437 print '%s[%s]: name = %s, type = %s, priority = %s' % (self.ELEMENTNAME,
434 438 self.id,
435 439 self.name,
436 440 self.type,
437 441 self.priority)
438 442
439 443 for parmConfObj in self.parmConfObjList:
440 444 parmConfObj.printattr()
441 445
442 446 def createObject(self, plotter_queue=None):
443 447
444 448 if self.type == 'self':
445 449 raise ValueError, 'This operation type cannot be created'
446 450
447 451 if self.type == 'plotter':
448 452 if not plotter_queue:
449 453 raise ValueError, 'plotter_queue is not defined. Use:\nmyProject = Project()\nmyProject.setPlotterQueue(plotter_queue)'
450 454
451 455 opObj = Plotter(self.name, plotter_queue)
452 456
453 457 if self.type == 'external' or self.type == 'other':
454 458
455 459 className = eval(self.name)
456 460 kwargs = self.getKwargs()
457 461
458 462 opObj = className(**kwargs)
459 463
460 464 return opObj
461 465
462 466
463 467 class ProcUnitConf():
464 468
465 469 id = None
466 470 name = None
467 471 datatype = None
468 472 inputId = None
469 473 parentId = None
470 474
471 475 opConfObjList = []
472 476
473 477 procUnitObj = None
474 478 opObjList = []
475 479
476 480 ELEMENTNAME = 'ProcUnit'
477 481
478 482 def __init__(self):
479 483
480 484 self.id = None
481 485 self.datatype = None
482 486 self.name = None
483 487 self.inputId = None
484 488
485 489 self.opConfObjList = []
486 490
487 491 self.procUnitObj = None
488 492 self.opObjDict = {}
489 493
490 494 def __getPriority(self):
491 495
492 496 return len(self.opConfObjList) + 1
493 497
494 498 def __getNewId(self):
495 499
496 500 return int(self.id) * 10 + len(self.opConfObjList) + 1
497 501
498 502 def getElementName(self):
499 503
500 504 return self.ELEMENTNAME
501 505
502 506 def getId(self):
503 507
504 508 return self.id
505 509
506 510 def updateId(self, new_id, parentId=parentId):
507 511
508 512 new_id = int(parentId) * 10 + (int(self.id) % 10)
509 513 new_inputId = int(parentId) * 10 + (int(self.inputId) % 10)
510 514
511 515 # If this proc unit has not inputs
512 516 if self.inputId == '0':
513 517 new_inputId = 0
514 518
515 519 n = 1
516 520 for opConfObj in self.opConfObjList:
517 521
518 522 idOp = str(int(new_id) * 10 + n)
519 523 opConfObj.updateId(idOp)
520 524
521 525 n += 1
522 526
523 527 self.parentId = str(parentId)
524 528 self.id = str(new_id)
525 529 self.inputId = str(new_inputId)
526 530
527 531 def getInputId(self):
528 532
529 533 return self.inputId
530 534
531 535 def getOperationObjList(self):
532 536
533 537 return self.opConfObjList
534 538
535 539 def getOperationObj(self, name=None):
536 540
537 541 for opConfObj in self.opConfObjList:
538 542
539 543 if opConfObj.name != name:
540 544 continue
541 545
542 546 return opConfObj
543 547
544 548 return None
545 549
546 550 def getOpObjfromParamValue(self, value=None):
547 551
548 552 for opConfObj in self.opConfObjList:
549 553 if opConfObj.getParameterObjfromValue(parameterValue=value) != value:
550 554 continue
551 555 return opConfObj
552 556 return None
553 557
554 558 def getProcUnitObj(self):
555 559
556 560 return self.procUnitObj
557 561
558 562 def setup(self, id, name, datatype, inputId, parentId=None):
559 563
560 564 # Compatible with old signal chain version
561 565 if datatype == None and name == None:
562 566 raise ValueError, 'datatype or name should be defined'
563 567
564 568 if name == None:
565 569 if 'Proc' in datatype:
566 570 name = datatype
567 571 else:
568 572 name = '%sProc' % (datatype)
569 573
570 574 if datatype == None:
571 575 datatype = name.replace('Proc', '')
572 576
573 577 self.id = str(id)
574 578 self.name = name
575 579 self.datatype = datatype
576 580 self.inputId = inputId
577 581 self.parentId = parentId
578 582
579 583 self.opConfObjList = []
580 584
581 585 self.addOperation(name='run', optype='self')
582 586
583 587 def removeOperations(self):
584 588
585 589 for obj in self.opConfObjList:
586 590 del obj
587 591
588 592 self.opConfObjList = []
589 593 self.addOperation(name='run')
590 594
591 595 def addParameter(self, **kwargs):
592 596 '''
593 597 Add parameters to 'run' operation
594 598 '''
595 599 opObj = self.opConfObjList[0]
596 600
597 601 opObj.addParameter(**kwargs)
598 602
599 603 return opObj
600 604
601 605 def addOperation(self, name, optype='self'):
602 606
603 607 id = self.__getNewId()
604 608 priority = self.__getPriority()
605 609
606 610 opConfObj = OperationConf()
607 611 opConfObj.setup(id, name=name, priority=priority, type=optype)
608 612
609 613 self.opConfObjList.append(opConfObj)
610 614
611 615 return opConfObj
612 616
613 617 def makeXml(self, projectElement):
614 618
615 619 procUnitElement = SubElement(projectElement, self.ELEMENTNAME)
616 620 procUnitElement.set('id', str(self.id))
617 621 procUnitElement.set('name', self.name)
618 622 procUnitElement.set('datatype', self.datatype)
619 623 procUnitElement.set('inputId', str(self.inputId))
620 624
621 625 for opConfObj in self.opConfObjList:
622 626 opConfObj.makeXml(procUnitElement)
623 627
624 628 def readXml(self, upElement):
625 629
626 630 self.id = upElement.get('id')
627 631 self.name = upElement.get('name')
628 632 self.datatype = upElement.get('datatype')
629 633 self.inputId = upElement.get('inputId')
630 634
631 635 if self.ELEMENTNAME == 'ReadUnit':
632 636 self.datatype = self.datatype.replace('Reader', '')
633 637
634 638 if self.ELEMENTNAME == 'ProcUnit':
635 639 self.datatype = self.datatype.replace('Proc', '')
636 640
637 641 if self.inputId == 'None':
638 642 self.inputId = '0'
639 643
640 644 self.opConfObjList = []
641 645
642 646 opElementList = upElement.iter(OperationConf().getElementName())
643 647
644 648 for opElement in opElementList:
645 649 opConfObj = OperationConf()
646 650 opConfObj.readXml(opElement)
647 651 self.opConfObjList.append(opConfObj)
648 652
649 653 def printattr(self):
650 654
651 655 print '%s[%s]: name = %s, datatype = %s, inputId = %s' % (self.ELEMENTNAME,
652 656 self.id,
653 657 self.name,
654 658 self.datatype,
655 659 self.inputId)
656 660
657 661 for opConfObj in self.opConfObjList:
658 662 opConfObj.printattr()
659 663
660 664 def getKwargs(self):
661 665
662 666 opObj = self.opConfObjList[0]
663 667 kwargs = opObj.getKwargs()
664 668
665 669 return kwargs
666 670
667 671 def createObjects(self, plotter_queue=None):
668 672
669 673 className = eval(self.name)
670 674 kwargs = self.getKwargs()
671 675 procUnitObj = className(**kwargs)
672 676
673 677 for opConfObj in self.opConfObjList:
674 678
675 679 if opConfObj.type == 'self' and self.name == 'run':
676 680 continue
677 681 elif opConfObj.type == 'self':
678 682 procUnitObj.addOperationKwargs(
679 683 opConfObj.id, **opConfObj.getKwargs())
680 684 continue
681 685
682 686 opObj = opConfObj.createObject(plotter_queue)
683 687
684 688 self.opObjDict[opConfObj.id] = opObj
685 689
686 690 procUnitObj.addOperation(opObj, opConfObj.id)
687 691
688 692 self.procUnitObj = procUnitObj
689 693
690 694 return procUnitObj
691 695
692 696 def run(self):
693 697
694 698 is_ok = False
695 699
696 700 for opConfObj in self.opConfObjList:
697 701
698 702 kwargs = {}
699 703 for parmConfObj in opConfObj.getParameterObjList():
700 704 if opConfObj.name == 'run' and parmConfObj.name == 'datatype':
701 705 continue
702 706
703 707 kwargs[parmConfObj.name] = parmConfObj.getValue()
704 708
705 709 sts = self.procUnitObj.call(opType=opConfObj.type,
706 710 opName=opConfObj.name,
707 711 opId=opConfObj.id)
708 712
709 713 is_ok = is_ok or sts
710 714
711 715 return is_ok
712 716
713 717 def close(self):
714 718
715 719 for opConfObj in self.opConfObjList:
716 720 if opConfObj.type == 'self':
717 721 continue
718 722
719 723 opObj = self.procUnitObj.getOperationObj(opConfObj.id)
720 724 opObj.close()
721 725
722 726 self.procUnitObj.close()
723 727
724 728 return
725 729
726 730
727 731 class ReadUnitConf(ProcUnitConf):
728 732
729 733 path = None
730 734 startDate = None
731 735 endDate = None
732 736 startTime = None
733 737 endTime = None
734 738
735 739 ELEMENTNAME = 'ReadUnit'
736 740
737 741 def __init__(self):
738 742
739 743 self.id = None
740 744 self.datatype = None
741 745 self.name = None
742 746 self.inputId = None
743 747
744 748 self.parentId = None
745 749
746 750 self.opConfObjList = []
747 751 self.opObjList = []
748 752
749 753 def getElementName(self):
750 754
751 755 return self.ELEMENTNAME
752 756
753 757 def setup(self, id, name, datatype, path='', startDate='', endDate='',
754 758 startTime='', endTime='', parentId=None, server=None, **kwargs):
755 759
756 760 # Compatible with old signal chain version
757 761 if datatype == None and name == None:
758 762 raise ValueError, 'datatype or name should be defined'
759 763 if name == None:
760 764 if 'Reader' in datatype:
761 765 name = datatype
762 766 datatype = name.replace('Reader','')
763 767 else:
764 768 name = '{}Reader'.format(datatype)
765 769 if datatype == None:
766 770 if 'Reader' in name:
767 771 datatype = name.replace('Reader','')
768 772 else:
769 773 datatype = name
770 774 name = '{}Reader'.format(name)
771 775
772 776 self.id = id
773 777 self.name = name
774 778 self.datatype = datatype
775 779 if path != '':
776 780 self.path = os.path.abspath(path)
777 781 self.startDate = startDate
778 782 self.endDate = endDate
779 783 self.startTime = startTime
780 784 self.endTime = endTime
781 785 self.inputId = '0'
782 786 self.parentId = parentId
783 787 self.server = server
784 788 self.addRunOperation(**kwargs)
785 789
786 790 def update(self, **kwargs):
787 791
788 792 if 'datatype' in kwargs:
789 793 datatype = kwargs.pop('datatype')
790 794 if 'Reader' in datatype:
791 795 self.name = datatype
792 796 else:
793 797 self.name = '%sReader' % (datatype)
794 798 self.datatype = self.name.replace('Reader', '')
795 799
796 800 attrs = ('path', 'startDate', 'endDate',
797 801 'startTime', 'endTime', 'parentId')
798 802
799 803 for attr in attrs:
800 804 if attr in kwargs:
801 805 setattr(self, attr, kwargs.pop(attr))
802 806
803 807 self.inputId = '0'
804 808 self.updateRunOperation(**kwargs)
805 809
806 810 def removeOperations(self):
807 811
808 812 for obj in self.opConfObjList:
809 813 del obj
810 814
811 815 self.opConfObjList = []
812 816
813 817 def addRunOperation(self, **kwargs):
814 818
815 819 opObj = self.addOperation(name='run', optype='self')
816 820
817 821 if self.server is None:
818 822 opObj.addParameter(
819 823 name='datatype', value=self.datatype, format='str')
820 824 opObj.addParameter(name='path', value=self.path, format='str')
821 825 opObj.addParameter(
822 826 name='startDate', value=self.startDate, format='date')
823 827 opObj.addParameter(
824 828 name='endDate', value=self.endDate, format='date')
825 829 opObj.addParameter(
826 830 name='startTime', value=self.startTime, format='time')
827 831 opObj.addParameter(
828 832 name='endTime', value=self.endTime, format='time')
829 833
830 834 for key, value in kwargs.items():
831 835 opObj.addParameter(name=key, value=value,
832 836 format=type(value).__name__)
833 837 else:
834 838 opObj.addParameter(name='server', value=self.server, format='str')
835 839
836 840 return opObj
837 841
838 842 def updateRunOperation(self, **kwargs):
839 843
840 844 opObj = self.getOperationObj(name='run')
841 845 opObj.removeParameters()
842 846
843 847 opObj.addParameter(name='datatype', value=self.datatype, format='str')
844 848 opObj.addParameter(name='path', value=self.path, format='str')
845 849 opObj.addParameter(
846 850 name='startDate', value=self.startDate, format='date')
847 851 opObj.addParameter(name='endDate', value=self.endDate, format='date')
848 852 opObj.addParameter(
849 853 name='startTime', value=self.startTime, format='time')
850 854 opObj.addParameter(name='endTime', value=self.endTime, format='time')
851 855
852 856 for key, value in kwargs.items():
853 857 opObj.addParameter(name=key, value=value,
854 858 format=type(value).__name__)
855 859
856 860 return opObj
857 861
858 862 def readXml(self, upElement):
859 863
860 864 self.id = upElement.get('id')
861 865 self.name = upElement.get('name')
862 866 self.datatype = upElement.get('datatype')
863 867 self.inputId = upElement.get('inputId')
864 868
865 869 if self.ELEMENTNAME == 'ReadUnit':
866 870 self.datatype = self.datatype.replace('Reader', '')
867 871
868 872 if self.inputId == 'None':
869 873 self.inputId = '0'
870 874
871 875 self.opConfObjList = []
872 876
873 877 opElementList = upElement.iter(OperationConf().getElementName())
874 878
875 879 for opElement in opElementList:
876 880 opConfObj = OperationConf()
877 881 opConfObj.readXml(opElement)
878 882 self.opConfObjList.append(opConfObj)
879 883
880 884 if opConfObj.name == 'run':
881 885 self.path = opConfObj.getParameterValue('path')
882 886 self.startDate = opConfObj.getParameterValue('startDate')
883 887 self.endDate = opConfObj.getParameterValue('endDate')
884 888 self.startTime = opConfObj.getParameterValue('startTime')
885 889 self.endTime = opConfObj.getParameterValue('endTime')
886 890
887 891
888 892 class Project(Process):
889 893
890 894 id = None
891 895 # name = None
892 896 description = None
893 897 filename = None
894 898
895 899 procUnitConfObjDict = None
896 900
897 901 ELEMENTNAME = 'Project'
898 902
899 903 plotterQueue = None
900 904
901 905 def __init__(self, plotter_queue=None):
902 906
903 907 Process.__init__(self)
904 908 self.id = None
905 909 # self.name = None
906 910 self.description = None
907 911
908 912 self.plotterQueue = plotter_queue
909 913
910 914 self.procUnitConfObjDict = {}
911 915
912 916 def __getNewId(self):
913 917
914 918 idList = self.procUnitConfObjDict.keys()
915 919
916 920 id = int(self.id) * 10
917 921
918 922 while True:
919 923 id += 1
920 924
921 925 if str(id) in idList:
922 926 continue
923 927
924 928 break
925 929
926 930 return str(id)
927 931
928 932 def getElementName(self):
929 933
930 934 return self.ELEMENTNAME
931 935
932 936 def getId(self):
933 937
934 938 return self.id
935 939
936 940 def updateId(self, new_id):
937 941
938 942 self.id = str(new_id)
939 943
940 944 keyList = self.procUnitConfObjDict.keys()
941 945 keyList.sort()
942 946
943 947 n = 1
944 948 newProcUnitConfObjDict = {}
945 949
946 950 for procKey in keyList:
947 951
948 952 procUnitConfObj = self.procUnitConfObjDict[procKey]
949 953 idProcUnit = str(int(self.id) * 10 + n)
950 954 procUnitConfObj.updateId(idProcUnit, parentId=self.id)
951 955
952 956 newProcUnitConfObjDict[idProcUnit] = procUnitConfObj
953 957 n += 1
954 958
955 959 self.procUnitConfObjDict = newProcUnitConfObjDict
956 960
957 961 def setup(self, id, name='', description=''):
958 962
959 963 print
960 964 print '*' * 60
961 965 print ' Starting SIGNAL CHAIN PROCESSING v%s ' % schainpy.__version__
962 966 print '*' * 60
963 967 print
964 968 self.id = str(id)
965 969 self.description = description
966 970
967 971 def update(self, name, description):
968 972
969 973 self.description = description
970 974
971 975 def clone(self):
972 976
973 977 p = Project()
974 978 p.procUnitConfObjDict = self.procUnitConfObjDict
975 979 return p
976 980
977 981 def addReadUnit(self, id=None, datatype=None, name=None, **kwargs):
978 982
979 983 if id is None:
980 984 idReadUnit = self.__getNewId()
981 985 else:
982 986 idReadUnit = str(id)
983 987
984 988 readUnitConfObj = ReadUnitConf()
985 989 readUnitConfObj.setup(idReadUnit, name, datatype,
986 990 parentId=self.id, **kwargs)
987 991
988 992 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
989 993
990 994 return readUnitConfObj
991 995
992 996 def addProcUnit(self, inputId='0', datatype=None, name=None):
993 997
994 998 idProcUnit = self.__getNewId()
995 999
996 1000 procUnitConfObj = ProcUnitConf()
997 1001 procUnitConfObj.setup(idProcUnit, name, datatype,
998 1002 inputId, parentId=self.id)
999 1003
1000 1004 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
1001 1005
1002 1006 return procUnitConfObj
1003 1007
1004 1008 def removeProcUnit(self, id):
1005 1009
1006 1010 if id in self.procUnitConfObjDict.keys():
1007 1011 self.procUnitConfObjDict.pop(id)
1008 1012
1009 1013 def getReadUnitId(self):
1010 1014
1011 1015 readUnitConfObj = self.getReadUnitObj()
1012 1016
1013 1017 return readUnitConfObj.id
1014 1018
1015 1019 def getReadUnitObj(self):
1016 1020
1017 1021 for obj in self.procUnitConfObjDict.values():
1018 1022 if obj.getElementName() == 'ReadUnit':
1019 1023 return obj
1020 1024
1021 1025 return None
1022 1026
1023 1027 def getProcUnitObj(self, id=None, name=None):
1024 1028
1025 1029 if id != None:
1026 1030 return self.procUnitConfObjDict[id]
1027 1031
1028 1032 if name != None:
1029 1033 return self.getProcUnitObjByName(name)
1030 1034
1031 1035 return None
1032 1036
1033 1037 def getProcUnitObjByName(self, name):
1034 1038
1035 1039 for obj in self.procUnitConfObjDict.values():
1036 1040 if obj.name == name:
1037 1041 return obj
1038 1042
1039 1043 return None
1040 1044
1041 1045 def procUnitItems(self):
1042 1046
1043 1047 return self.procUnitConfObjDict.items()
1044 1048
1045 1049 def makeXml(self):
1046 1050
1047 1051 projectElement = Element('Project')
1048 1052 projectElement.set('id', str(self.id))
1049 1053 projectElement.set('name', self.name)
1050 1054 projectElement.set('description', self.description)
1051 1055
1052 1056 for procUnitConfObj in self.procUnitConfObjDict.values():
1053 1057 procUnitConfObj.makeXml(projectElement)
1054 1058
1055 1059 self.projectElement = projectElement
1056 1060
1057 1061 def writeXml(self, filename=None):
1058 1062
1059 1063 if filename == None:
1060 1064 if self.filename:
1061 1065 filename = self.filename
1062 1066 else:
1063 1067 filename = 'schain.xml'
1064 1068
1065 1069 if not filename:
1066 1070 print 'filename has not been defined. Use setFilename(filename) for do it.'
1067 1071 return 0
1068 1072
1069 1073 abs_file = os.path.abspath(filename)
1070 1074
1071 1075 if not os.access(os.path.dirname(abs_file), os.W_OK):
1072 1076 print 'No write permission on %s' % os.path.dirname(abs_file)
1073 1077 return 0
1074 1078
1075 1079 if os.path.isfile(abs_file) and not(os.access(abs_file, os.W_OK)):
1076 1080 print 'File %s already exists and it could not be overwriten' % abs_file
1077 1081 return 0
1078 1082
1079 1083 self.makeXml()
1080 1084
1081 1085 ElementTree(self.projectElement).write(abs_file, method='xml')
1082 1086
1083 1087 self.filename = abs_file
1084 1088
1085 1089 return 1
1086 1090
1087 1091 def readXml(self, filename=None):
1088 1092
1089 1093 if not filename:
1090 1094 print 'filename is not defined'
1091 1095 return 0
1092 1096
1093 1097 abs_file = os.path.abspath(filename)
1094 1098
1095 1099 if not os.path.isfile(abs_file):
1096 1100 print '%s file does not exist' % abs_file
1097 1101 return 0
1098 1102
1099 1103 self.projectElement = None
1100 1104 self.procUnitConfObjDict = {}
1101 1105
1102 1106 try:
1103 1107 self.projectElement = ElementTree().parse(abs_file)
1104 1108 except:
1105 1109 print 'Error reading %s, verify file format' % filename
1106 1110 return 0
1107 1111
1108 1112 self.project = self.projectElement.tag
1109 1113
1110 1114 self.id = self.projectElement.get('id')
1111 1115 self.name = self.projectElement.get('name')
1112 1116 self.description = self.projectElement.get('description')
1113 1117
1114 1118 readUnitElementList = self.projectElement.iter(
1115 1119 ReadUnitConf().getElementName())
1116 1120
1117 1121 for readUnitElement in readUnitElementList:
1118 1122 readUnitConfObj = ReadUnitConf()
1119 1123 readUnitConfObj.readXml(readUnitElement)
1120 1124
1121 1125 if readUnitConfObj.parentId == None:
1122 1126 readUnitConfObj.parentId = self.id
1123 1127
1124 1128 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
1125 1129
1126 1130 procUnitElementList = self.projectElement.iter(
1127 1131 ProcUnitConf().getElementName())
1128 1132
1129 1133 for procUnitElement in procUnitElementList:
1130 1134 procUnitConfObj = ProcUnitConf()
1131 1135 procUnitConfObj.readXml(procUnitElement)
1132 1136
1133 1137 if procUnitConfObj.parentId == None:
1134 1138 procUnitConfObj.parentId = self.id
1135 1139
1136 1140 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
1137 1141
1138 1142 self.filename = abs_file
1139 1143
1140 1144 return 1
1141 1145
1142 1146 def printattr(self):
1143 1147
1144 1148 print 'Project[%s]: name = %s, description = %s' % (self.id,
1145 1149 self.name,
1146 1150 self.description)
1147 1151
1148 1152 for procUnitConfObj in self.procUnitConfObjDict.values():
1149 1153 procUnitConfObj.printattr()
1150 1154
1151 1155 def createObjects(self):
1152 1156
1153 1157 for procUnitConfObj in self.procUnitConfObjDict.values():
1154 1158 procUnitConfObj.createObjects(self.plotterQueue)
1155 1159
1156 1160 def __connect(self, objIN, thisObj):
1157 1161
1158 1162 thisObj.setInput(objIN.getOutputObj())
1159 1163
1160 1164 def connectObjects(self):
1161 1165
1162 1166 for thisPUConfObj in self.procUnitConfObjDict.values():
1163 1167
1164 1168 inputId = thisPUConfObj.getInputId()
1165 1169
1166 1170 if int(inputId) == 0:
1167 1171 continue
1168 1172
1169 1173 # Get input object
1170 1174 puConfINObj = self.procUnitConfObjDict[inputId]
1171 1175 puObjIN = puConfINObj.getProcUnitObj()
1172 1176
1173 1177 # Get current object
1174 1178 thisPUObj = thisPUConfObj.getProcUnitObj()
1175 1179
1176 1180 self.__connect(puObjIN, thisPUObj)
1177 1181
1178 1182 def __handleError(self, procUnitConfObj, send_email=False):
1179 1183
1180 1184 import socket
1181 1185
1182 1186 err = traceback.format_exception(sys.exc_info()[0],
1183 1187 sys.exc_info()[1],
1184 1188 sys.exc_info()[2])
1185 1189
1186 1190 print '***** Error occurred in %s *****' % (procUnitConfObj.name)
1187 1191 print '***** %s' % err[-1]
1188 1192
1189 1193 message = ''.join(err)
1190 1194
1191 1195 sys.stderr.write(message)
1192 1196
1193 1197 if not send_email:
1194 1198 return
1195 1199
1196 1200 subject = 'SChain v%s: Error running %s\n' % (
1197 1201 schainpy.__version__, procUnitConfObj.name)
1198 1202
1199 1203 subtitle = '%s: %s\n' % (
1200 1204 procUnitConfObj.getElementName(), procUnitConfObj.name)
1201 1205 subtitle += 'Hostname: %s\n' % socket.gethostbyname(
1202 1206 socket.gethostname())
1203 1207 subtitle += 'Working directory: %s\n' % os.path.abspath('./')
1204 1208 subtitle += 'Configuration file: %s\n' % self.filename
1205 1209 subtitle += 'Time: %s\n' % str(datetime.datetime.now())
1206 1210
1207 1211 readUnitConfObj = self.getReadUnitObj()
1208 1212 if readUnitConfObj:
1209 1213 subtitle += '\nInput parameters:\n'
1210 1214 subtitle += '[Data path = %s]\n' % readUnitConfObj.path
1211 1215 subtitle += '[Data type = %s]\n' % readUnitConfObj.datatype
1212 1216 subtitle += '[Start date = %s]\n' % readUnitConfObj.startDate
1213 1217 subtitle += '[End date = %s]\n' % readUnitConfObj.endDate
1214 1218 subtitle += '[Start time = %s]\n' % readUnitConfObj.startTime
1215 1219 subtitle += '[End time = %s]\n' % readUnitConfObj.endTime
1216 1220
1217 1221 adminObj = schainpy.admin.SchainNotify()
1218 1222 adminObj.sendAlert(message=message,
1219 1223 subject=subject,
1220 1224 subtitle=subtitle,
1221 1225 filename=self.filename)
1222 1226
1223 1227 def isPaused(self):
1224 1228 return 0
1225 1229
1226 1230 def isStopped(self):
1227 1231 return 0
1228 1232
1229 1233 def runController(self):
1230 1234 '''
1231 1235 returns 0 when this process has been stopped, 1 otherwise
1232 1236 '''
1233 1237
1234 1238 if self.isPaused():
1235 1239 print 'Process suspended'
1236 1240
1237 1241 while True:
1238 1242 time.sleep(0.1)
1239 1243
1240 1244 if not self.isPaused():
1241 1245 break
1242 1246
1243 1247 if self.isStopped():
1244 1248 break
1245 1249
1246 1250 print 'Process reinitialized'
1247 1251
1248 1252 if self.isStopped():
1249 1253 print 'Process stopped'
1250 1254 return 0
1251 1255
1252 1256 return 1
1253 1257
1254 1258 def setFilename(self, filename):
1255 1259
1256 1260 self.filename = filename
1257 1261
1258 1262 def setPlotterQueue(self, plotter_queue):
1259 1263
1260 1264 raise NotImplementedError, 'Use schainpy.controller_api.ControllerThread instead Project class'
1261 1265
1262 1266 def getPlotterQueue(self):
1263 1267
1264 1268 raise NotImplementedError, 'Use schainpy.controller_api.ControllerThread instead Project class'
1265 1269
1266 1270 def useExternalPlotter(self):
1267 1271
1268 1272 raise NotImplementedError, 'Use schainpy.controller_api.ControllerThread instead Project class'
1269 1273
1270 1274 def run(self):
1271 1275
1272 1276 log.success('Starting {}'.format(self.name))
1273
1277 self.start_time = time.time()
1274 1278 self.createObjects()
1275 1279 self.connectObjects()
1276 1280
1277 1281 keyList = self.procUnitConfObjDict.keys()
1278 1282 keyList.sort()
1279 1283
1280 1284 while(True):
1281 1285
1282 1286 is_ok = False
1283 1287
1284 1288 for procKey in keyList:
1285 1289
1286 1290 procUnitConfObj = self.procUnitConfObjDict[procKey]
1287 1291
1288 1292 try:
1289 1293 sts = procUnitConfObj.run()
1290 1294 is_ok = is_ok or sts
1291 1295 except KeyboardInterrupt:
1292 1296 is_ok = False
1293 1297 break
1294 1298 except ValueError, e:
1295 1299 time.sleep(0.5)
1296 1300 self.__handleError(procUnitConfObj, send_email=True)
1297 1301 is_ok = False
1298 1302 break
1299 1303 except:
1300 1304 time.sleep(0.5)
1301 1305 self.__handleError(procUnitConfObj)
1302 1306 is_ok = False
1303 1307 break
1304 1308
1305 1309 # If every process unit finished so end process
1306 1310 if not(is_ok):
1307 1311 break
1308 1312
1309 1313 if not self.runController():
1310 1314 break
1311 1315
1312 1316 # Closing every process
1313 1317 for procKey in keyList:
1314 1318 procUnitConfObj = self.procUnitConfObjDict[procKey]
1315 1319 procUnitConfObj.close()
1316 1320
1317 log.success('{} finished'.format(self.name))
1321 log.success('{} finished (time: {}s)'.format(
1322 self.name,
1323 time.time()-self.start_time))
@@ -1,876 +1,876
1 1 '''
2 2
3 3 $Author: murco $
4 4 $Id: JROHeaderIO.py 151 2012-10-31 19:00:51Z murco $
5 5 '''
6 6 import sys
7 7 import numpy
8 8 import copy
9 9 import datetime
10 10 import inspect
11 11
12 12 SPEED_OF_LIGHT = 299792458
13 13 SPEED_OF_LIGHT = 3e8
14 14
15 15 BASIC_STRUCTURE = numpy.dtype([
16 16 ('nSize','<u4'),
17 17 ('nVersion','<u2'),
18 18 ('nDataBlockId','<u4'),
19 19 ('nUtime','<u4'),
20 20 ('nMilsec','<u2'),
21 21 ('nTimezone','<i2'),
22 22 ('nDstflag','<i2'),
23 23 ('nErrorCount','<u4')
24 24 ])
25 25
26 26 SYSTEM_STRUCTURE = numpy.dtype([
27 27 ('nSize','<u4'),
28 28 ('nNumSamples','<u4'),
29 29 ('nNumProfiles','<u4'),
30 30 ('nNumChannels','<u4'),
31 31 ('nADCResolution','<u4'),
32 32 ('nPCDIOBusWidth','<u4'),
33 33 ])
34 34
35 35 RADAR_STRUCTURE = numpy.dtype([
36 36 ('nSize','<u4'),
37 37 ('nExpType','<u4'),
38 38 ('nNTx','<u4'),
39 39 ('fIpp','<f4'),
40 40 ('fTxA','<f4'),
41 41 ('fTxB','<f4'),
42 42 ('nNumWindows','<u4'),
43 43 ('nNumTaus','<u4'),
44 44 ('nCodeType','<u4'),
45 45 ('nLine6Function','<u4'),
46 46 ('nLine5Function','<u4'),
47 47 ('fClock','<f4'),
48 48 ('nPrePulseBefore','<u4'),
49 49 ('nPrePulseAfter','<u4'),
50 50 ('sRangeIPP','<a20'),
51 51 ('sRangeTxA','<a20'),
52 52 ('sRangeTxB','<a20'),
53 53 ])
54 54
55 55 SAMPLING_STRUCTURE = numpy.dtype([('h0','<f4'),('dh','<f4'),('nsa','<u4')])
56 56
57 57
58 58 PROCESSING_STRUCTURE = numpy.dtype([
59 59 ('nSize','<u4'),
60 60 ('nDataType','<u4'),
61 61 ('nSizeOfDataBlock','<u4'),
62 62 ('nProfilesperBlock','<u4'),
63 63 ('nDataBlocksperFile','<u4'),
64 64 ('nNumWindows','<u4'),
65 65 ('nProcessFlags','<u4'),
66 66 ('nCoherentIntegrations','<u4'),
67 67 ('nIncoherentIntegrations','<u4'),
68 68 ('nTotalSpectra','<u4')
69 69 ])
70 70
71 71 class Header(object):
72 72
73 73 def __init__(self):
74 74 raise NotImplementedError
75 75
76 76 def copy(self):
77 77 return copy.deepcopy(self)
78 78
79 79 def read(self):
80 80
81 81 raise NotImplementedError
82 82
83 83 def write(self):
84 84
85 85 raise NotImplementedError
86 86
87 87 def getAllowedArgs(self):
88 88 args = inspect.getargspec(self.__init__).args
89 89 try:
90 90 args.remove('self')
91 91 except:
92 92 pass
93 93 return args
94 94
95 95 def getAsDict(self):
96 96 args = self.getAllowedArgs()
97 97 asDict = {}
98 98 for x in args:
99 99 asDict[x] = self[x]
100 100 return asDict
101 101
102 102 def __getitem__(self, name):
103 103 return getattr(self, name)
104 104
105 105 def printInfo(self):
106 106
107 107 message = "#"*50 + "\n"
108 108 message += self.__class__.__name__.upper() + "\n"
109 109 message += "#"*50 + "\n"
110 110
111 111 keyList = self.__dict__.keys()
112 112 keyList.sort()
113 113
114 114 for key in keyList:
115 115 message += "%s = %s" %(key, self.__dict__[key]) + "\n"
116 116
117 117 if "size" not in keyList:
118 118 attr = getattr(self, "size")
119 119
120 120 if attr:
121 121 message += "%s = %s" %("size", attr) + "\n"
122 122
123 123 print message
124 124
125 125 class BasicHeader(Header):
126 126
127 127 size = None
128 128 version = None
129 129 dataBlock = None
130 130 utc = None
131 131 ltc = None
132 132 miliSecond = None
133 133 timeZone = None
134 134 dstFlag = None
135 135 errorCount = None
136 136 datatime = None
137 137 structure = BASIC_STRUCTURE
138 138 __LOCALTIME = None
139 139
140 140 def __init__(self, useLocalTime=True):
141 141
142 142 self.size = 24
143 143 self.version = 0
144 144 self.dataBlock = 0
145 145 self.utc = 0
146 146 self.miliSecond = 0
147 147 self.timeZone = 0
148 148 self.dstFlag = 0
149 149 self.errorCount = 0
150 150
151 151 self.useLocalTime = useLocalTime
152 152
153 153 def read(self, fp):
154 154
155 155 self.length = 0
156 156 try:
157 157 if hasattr(fp, 'read'):
158 158 header = numpy.fromfile(fp, BASIC_STRUCTURE,1)
159 159 else:
160 160 header = numpy.fromstring(fp, BASIC_STRUCTURE,1)
161 161 except Exception, e:
162 162 print "BasicHeader: "
163 163 print e
164 164 return 0
165 165
166 166 self.size = int(header['nSize'][0])
167 167 self.version = int(header['nVersion'][0])
168 168 self.dataBlock = int(header['nDataBlockId'][0])
169 169 self.utc = int(header['nUtime'][0])
170 170 self.miliSecond = int(header['nMilsec'][0])
171 171 self.timeZone = int(header['nTimezone'][0])
172 172 self.dstFlag = int(header['nDstflag'][0])
173 173 self.errorCount = int(header['nErrorCount'][0])
174 174
175 175 if self.size < 24:
176 176 return 0
177 177
178 178 self.length = header.nbytes
179 179 return 1
180 180
181 181 def write(self, fp):
182 182
183 183 headerTuple = (self.size,self.version,self.dataBlock,self.utc,self.miliSecond,self.timeZone,self.dstFlag,self.errorCount)
184 184 header = numpy.array(headerTuple, BASIC_STRUCTURE)
185 185 header.tofile(fp)
186 186
187 187 return 1
188 188
189 189 def get_ltc(self):
190 190
191 191 return self.utc - self.timeZone*60
192 192
193 193 def set_ltc(self, value):
194 194
195 195 self.utc = value + self.timeZone*60
196 196
197 197 def get_datatime(self):
198 198
199 199 return datetime.datetime.utcfromtimestamp(self.ltc)
200 200
201 201 ltc = property(get_ltc, set_ltc)
202 202 datatime = property(get_datatime)
203 203
204 204 class SystemHeader(Header):
205 205
206 206 size = None
207 207 nSamples = None
208 208 nProfiles = None
209 209 nChannels = None
210 210 adcResolution = None
211 211 pciDioBusWidth = None
212 212 structure = SYSTEM_STRUCTURE
213 213
214 214 def __init__(self, nSamples=0, nProfiles=0, nChannels=0, adcResolution=14, pciDioBusWidth=0):
215 215
216 216 self.size = 24
217 217 self.nSamples = nSamples
218 218 self.nProfiles = nProfiles
219 219 self.nChannels = nChannels
220 220 self.adcResolution = adcResolution
221 221 self.pciDioBusWidth = pciDioBusWidth
222 222
223 223 def read(self, fp):
224 224 self.length = 0
225 225 try:
226 226 startFp = fp.tell()
227 227 except Exception, e:
228 228 startFp = None
229 229 pass
230 230
231 231 try:
232 232 if hasattr(fp, 'read'):
233 233 header = numpy.fromfile(fp, SYSTEM_STRUCTURE,1)
234 234 else:
235 235 header = numpy.fromstring(fp, SYSTEM_STRUCTURE,1)
236 236 except Exception, e:
237 237 print "System Header: " + str(e)
238 238 return 0
239 239
240 240 self.size = header['nSize'][0]
241 241 self.nSamples = header['nNumSamples'][0]
242 242 self.nProfiles = header['nNumProfiles'][0]
243 243 self.nChannels = header['nNumChannels'][0]
244 244 self.adcResolution = header['nADCResolution'][0]
245 245 self.pciDioBusWidth = header['nPCDIOBusWidth'][0]
246 246
247 247
248 248 if startFp is not None:
249 249 endFp = self.size + startFp
250 250
251 251 if fp.tell() > endFp:
252 252 sys.stderr.write("Warning %s: Size value read from System Header is lower than it has to be\n" %fp.name)
253 253 return 0
254 254
255 255 if fp.tell() < endFp:
256 256 sys.stderr.write("Warning %s: Size value read from System Header size is greater than it has to be\n" %fp.name)
257 257 return 0
258 258
259 259 self.length = header.nbytes
260 260 return 1
261 261
262 262 def write(self, fp):
263 263
264 264 headerTuple = (self.size,self.nSamples,self.nProfiles,self.nChannels,self.adcResolution,self.pciDioBusWidth)
265 265 header = numpy.array(headerTuple,SYSTEM_STRUCTURE)
266 266 header.tofile(fp)
267 267
268 268 return 1
269 269
270 270 class RadarControllerHeader(Header):
271 271
272 272 expType = None
273 273 nTx = None
274 274 ipp = None
275 275 txA = None
276 276 txB = None
277 277 nWindows = None
278 278 numTaus = None
279 279 codeType = None
280 280 line6Function = None
281 281 line5Function = None
282 282 fClock = None
283 283 prePulseBefore = None
284 284 prePulseAfter = None
285 285 rangeIpp = None
286 286 rangeTxA = None
287 287 rangeTxB = None
288 288 structure = RADAR_STRUCTURE
289 289 __size = None
290 290
291 291 def __init__(self, expType=2, nTx=1,
292 292 ipp=None, txA=0, txB=0,
293 293 nWindows=None, nHeights=None, firstHeight=None, deltaHeight=None,
294 294 numTaus=0, line6Function=0, line5Function=0, fClock=None,
295 295 prePulseBefore=0, prePulseAfter=0,
296 296 codeType=0, nCode=0, nBaud=0, code=None,
297 297 flip1=0, flip2=0):
298 298
299 299 # self.size = 116
300 300 self.expType = expType
301 301 self.nTx = nTx
302 302 self.ipp = ipp
303 303 self.txA = txA
304 304 self.txB = txB
305 305 self.rangeIpp = ipp
306 306 self.rangeTxA = txA
307 307 self.rangeTxB = txB
308 308
309 309 self.nWindows = nWindows
310 310 self.numTaus = numTaus
311 311 self.codeType = codeType
312 312 self.line6Function = line6Function
313 313 self.line5Function = line5Function
314 314 self.fClock = fClock
315 315 self.prePulseBefore = prePulseBefore
316 316 self.prePulseAfter = prePulseAfter
317 317
318 318 self.nHeights = nHeights
319 319 self.firstHeight = firstHeight
320 320 self.deltaHeight = deltaHeight
321 321 self.samplesWin = nHeights
322 322
323 323 self.nCode = nCode
324 324 self.nBaud = nBaud
325 325 self.code = code
326 326 self.flip1 = flip1
327 327 self.flip2 = flip2
328 328
329 329 self.code_size = int(numpy.ceil(self.nBaud/32.))*self.nCode*4
330 330 # self.dynamic = numpy.array([],numpy.dtype('byte'))
331 331
332 332 if self.fClock is None and self.deltaHeight is not None:
333 333 self.fClock = 0.15/(deltaHeight*1e-6) #0.15Km / (height * 1u)
334 334
335 335 def read(self, fp):
336 336 self.length = 0
337 337 try:
338 338 startFp = fp.tell()
339 339 except Exception, e:
340 340 startFp = None
341 341 pass
342 342
343 343 try:
344 344 if hasattr(fp, 'read'):
345 345 header = numpy.fromfile(fp, RADAR_STRUCTURE,1)
346 346 else:
347 347 header = numpy.fromstring(fp, RADAR_STRUCTURE,1)
348 348 self.length += header.nbytes
349 349 except Exception, e:
350 350 print "RadarControllerHeader: " + str(e)
351 351 return 0
352 352
353 353 size = int(header['nSize'][0])
354 354 self.expType = int(header['nExpType'][0])
355 355 self.nTx = int(header['nNTx'][0])
356 356 self.ipp = float(header['fIpp'][0])
357 357 self.txA = float(header['fTxA'][0])
358 358 self.txB = float(header['fTxB'][0])
359 359 self.nWindows = int(header['nNumWindows'][0])
360 360 self.numTaus = int(header['nNumTaus'][0])
361 361 self.codeType = int(header['nCodeType'][0])
362 362 self.line6Function = int(header['nLine6Function'][0])
363 363 self.line5Function = int(header['nLine5Function'][0])
364 364 self.fClock = float(header['fClock'][0])
365 365 self.prePulseBefore = int(header['nPrePulseBefore'][0])
366 366 self.prePulseAfter = int(header['nPrePulseAfter'][0])
367 367 self.rangeIpp = header['sRangeIPP'][0]
368 368 self.rangeTxA = header['sRangeTxA'][0]
369 369 self.rangeTxB = header['sRangeTxB'][0]
370 370
371 371 try:
372 372 if hasattr(fp, 'read'):
373 373 samplingWindow = numpy.fromfile(fp, SAMPLING_STRUCTURE, self.nWindows)
374 374 else:
375 375 samplingWindow = numpy.fromstring(fp[self.length:], SAMPLING_STRUCTURE, self.nWindows)
376 376 self.length += samplingWindow.nbytes
377 377 except Exception, e:
378 378 print "RadarControllerHeader: " + str(e)
379 379 return 0
380 380 self.nHeights = int(numpy.sum(samplingWindow['nsa']))
381 381 self.firstHeight = samplingWindow['h0']
382 382 self.deltaHeight = samplingWindow['dh']
383 383 self.samplesWin = samplingWindow['nsa']
384 384
385 385
386 386
387 387 try:
388 388 if hasattr(fp, 'read'):
389 389 self.Taus = numpy.fromfile(fp, '<f4', self.numTaus)
390 390 else:
391 391 self.Taus = numpy.fromstring(fp[self.length:], '<f4', self.numTaus)
392 392 self.length += self.Taus.nbytes
393 393 except Exception, e:
394 394 print "RadarControllerHeader: " + str(e)
395 395 return 0
396 396
397 397
398 398
399 399 self.code_size = 0
400 400 if self.codeType != 0:
401 401
402 402 try:
403 403 if hasattr(fp, 'read'):
404 404 self.nCode = numpy.fromfile(fp, '<u4', 1)[0]
405 405 self.length += self.nCode.nbytes
406 406 self.nBaud = numpy.fromfile(fp, '<u4', 1)[0]
407 407 self.length += self.nBaud.nbytes
408 408 else:
409 409 self.nCode = numpy.fromstring(fp[self.length:], '<u4', 1)[0]
410 410 self.length += self.nCode.nbytes
411 411 self.nBaud = numpy.fromstring(fp[self.length:], '<u4', 1)[0]
412 412 self.length += self.nBaud.nbytes
413 413 except Exception, e:
414 414 print "RadarControllerHeader: " + str(e)
415 415 return 0
416 416 code = numpy.empty([self.nCode,self.nBaud],dtype='i1')
417 417
418 418 for ic in range(self.nCode):
419 419 try:
420 420 if hasattr(fp, 'read'):
421 421 temp = numpy.fromfile(fp,'u4', int(numpy.ceil(self.nBaud/32.)))
422 422 else:
423 423 temp = numpy.fromstring(fp,'u4', int(numpy.ceil(self.nBaud/32.)))
424 424 self.length += temp.nbytes
425 425 except Exception, e:
426 426 print "RadarControllerHeader: " + str(e)
427 427 return 0
428 428
429 429 for ib in range(self.nBaud-1,-1,-1):
430 430 code[ic,ib] = temp[ib/32]%2
431 431 temp[ib/32] = temp[ib/32]/2
432 432
433 433 self.code = 2.0*code - 1.0
434 434 self.code_size = int(numpy.ceil(self.nBaud/32.))*self.nCode*4
435 435
436 436 # if self.line5Function == RCfunction.FLIP:
437 437 # self.flip1 = numpy.fromfile(fp,'<u4',1)
438 438 #
439 439 # if self.line6Function == RCfunction.FLIP:
440 440 # self.flip2 = numpy.fromfile(fp,'<u4',1)
441 441 if startFp is not None:
442 442 endFp = size + startFp
443 443
444 444 if fp.tell() != endFp:
445 445 # fp.seek(endFp)
446 446 print "%s: Radar Controller Header size is not consistent: from data [%d] != from header field [%d]" %(fp.name, fp.tell()-startFp, size)
447 447 # return 0
448 448
449 449 if fp.tell() > endFp:
450 450 sys.stderr.write("Warning %s: Size value read from Radar Controller header is lower than it has to be\n" %fp.name)
451 451 # return 0
452 452
453 453 if fp.tell() < endFp:
454 454 sys.stderr.write("Warning %s: Size value read from Radar Controller header is greater than it has to be\n" %fp.name)
455 455
456 456
457 457 return 1
458 458
459 459 def write(self, fp):
460 460
461 461 headerTuple = (self.size,
462 462 self.expType,
463 463 self.nTx,
464 464 self.ipp,
465 465 self.txA,
466 466 self.txB,
467 467 self.nWindows,
468 468 self.numTaus,
469 469 self.codeType,
470 470 self.line6Function,
471 471 self.line5Function,
472 472 self.fClock,
473 473 self.prePulseBefore,
474 474 self.prePulseAfter,
475 475 self.rangeIpp,
476 476 self.rangeTxA,
477 477 self.rangeTxB)
478 478
479 479 header = numpy.array(headerTuple,RADAR_STRUCTURE)
480 480 header.tofile(fp)
481 481
482 482 sampleWindowTuple = (self.firstHeight,self.deltaHeight,self.samplesWin)
483 483 samplingWindow = numpy.array(sampleWindowTuple,SAMPLING_STRUCTURE)
484 484 samplingWindow.tofile(fp)
485 485
486 486 if self.numTaus > 0:
487 487 self.Taus.tofile(fp)
488 488
489 489 if self.codeType !=0:
490 490 nCode = numpy.array(self.nCode, '<u4')
491 491 nCode.tofile(fp)
492 492 nBaud = numpy.array(self.nBaud, '<u4')
493 493 nBaud.tofile(fp)
494 494 code1 = (self.code + 1.0)/2.
495 495
496 496 for ic in range(self.nCode):
497 tempx = numpy.zeros(numpy.ceil(self.nBaud/32.))
497 tempx = numpy.zeros(int(numpy.ceil(self.nBaud/32.)))
498 498 start = 0
499 499 end = 32
500 500 for i in range(len(tempx)):
501 501 code_selected = code1[ic,start:end]
502 502 for j in range(len(code_selected)-1,-1,-1):
503 503 if code_selected[j] == 1:
504 504 tempx[i] = tempx[i] + 2**(len(code_selected)-1-j)
505 505 start = start + 32
506 506 end = end + 32
507 507
508 508 tempx = tempx.astype('u4')
509 509 tempx.tofile(fp)
510 510
511 511 # if self.line5Function == RCfunction.FLIP:
512 512 # self.flip1.tofile(fp)
513 513 #
514 514 # if self.line6Function == RCfunction.FLIP:
515 515 # self.flip2.tofile(fp)
516 516
517 517 return 1
518 518
519 519 def get_ippSeconds(self):
520 520 '''
521 521 '''
522 522 ippSeconds = 2.0 * 1000 * self.ipp / SPEED_OF_LIGHT
523 523
524 524 return ippSeconds
525 525
526 526 def set_ippSeconds(self, ippSeconds):
527 527 '''
528 528 '''
529 529
530 530 self.ipp = ippSeconds * SPEED_OF_LIGHT / (2.0*1000)
531 531
532 532 return
533 533
534 534 def get_size(self):
535 535
536 536 self.__size = 116 + 12*self.nWindows + 4*self.numTaus
537 537
538 538 if self.codeType != 0:
539 539 self.__size += 4 + 4 + 4*self.nCode*numpy.ceil(self.nBaud/32.)
540 540
541 541 return self.__size
542 542
543 543 def set_size(self, value):
544 544
545 545 raise IOError, "size is a property and it cannot be set, just read"
546 546
547 547 return
548 548
549 549 ippSeconds = property(get_ippSeconds, set_ippSeconds)
550 550 size = property(get_size, set_size)
551 551
552 552 class ProcessingHeader(Header):
553 553
554 554 # size = None
555 555 dtype = None
556 556 blockSize = None
557 557 profilesPerBlock = None
558 558 dataBlocksPerFile = None
559 559 nWindows = None
560 560 processFlags = None
561 561 nCohInt = None
562 562 nIncohInt = None
563 563 totalSpectra = None
564 564 structure = PROCESSING_STRUCTURE
565 565 flag_dc = None
566 566 flag_cspc = None
567 567
568 568 def __init__(self, dtype=0, blockSize=0, profilesPerBlock=0, dataBlocksPerFile=0, nWindows=0,processFlags=0, nCohInt=0,
569 569 nIncohInt=0, totalSpectra=0, nHeights=0, firstHeight=0, deltaHeight=0, samplesWin=0, spectraComb=0, nCode=0,
570 570 code=0, nBaud=None, shif_fft=False, flag_dc=False, flag_cspc=False, flag_decode=False, flag_deflip=False
571 571 ):
572 572
573 573 # self.size = 0
574 574 self.dtype = dtype
575 575 self.blockSize = blockSize
576 576 self.profilesPerBlock = 0
577 577 self.dataBlocksPerFile = 0
578 578 self.nWindows = 0
579 579 self.processFlags = 0
580 580 self.nCohInt = 0
581 581 self.nIncohInt = 0
582 582 self.totalSpectra = 0
583 583
584 584 self.nHeights = 0
585 585 self.firstHeight = 0
586 586 self.deltaHeight = 0
587 587 self.samplesWin = 0
588 588 self.spectraComb = 0
589 589 self.nCode = None
590 590 self.code = None
591 591 self.nBaud = None
592 592
593 593 self.shif_fft = False
594 594 self.flag_dc = False
595 595 self.flag_cspc = False
596 596 self.flag_decode = False
597 597 self.flag_deflip = False
598 598 self.length = 0
599 599
600 600 def read(self, fp):
601 601 self.length = 0
602 602 try:
603 603 startFp = fp.tell()
604 604 except Exception, e:
605 605 startFp = None
606 606 pass
607 607
608 608 try:
609 609 if hasattr(fp, 'read'):
610 610 header = numpy.fromfile(fp, PROCESSING_STRUCTURE, 1)
611 611 else:
612 612 header = numpy.fromstring(fp, PROCESSING_STRUCTURE, 1)
613 613 self.length += header.nbytes
614 614 except Exception, e:
615 615 print "ProcessingHeader: " + str(e)
616 616 return 0
617 617
618 618 size = int(header['nSize'][0])
619 619 self.dtype = int(header['nDataType'][0])
620 620 self.blockSize = int(header['nSizeOfDataBlock'][0])
621 621 self.profilesPerBlock = int(header['nProfilesperBlock'][0])
622 622 self.dataBlocksPerFile = int(header['nDataBlocksperFile'][0])
623 623 self.nWindows = int(header['nNumWindows'][0])
624 624 self.processFlags = header['nProcessFlags']
625 625 self.nCohInt = int(header['nCoherentIntegrations'][0])
626 626 self.nIncohInt = int(header['nIncoherentIntegrations'][0])
627 627 self.totalSpectra = int(header['nTotalSpectra'][0])
628 628
629 629 try:
630 630 if hasattr(fp, 'read'):
631 631 samplingWindow = numpy.fromfile(fp, SAMPLING_STRUCTURE, self.nWindows)
632 632 else:
633 633 samplingWindow = numpy.fromstring(fp[self.length:], SAMPLING_STRUCTURE, self.nWindows)
634 634 self.length += samplingWindow.nbytes
635 635 except Exception, e:
636 636 print "ProcessingHeader: " + str(e)
637 637 return 0
638 638
639 639 self.nHeights = int(numpy.sum(samplingWindow['nsa']))
640 640 self.firstHeight = float(samplingWindow['h0'][0])
641 641 self.deltaHeight = float(samplingWindow['dh'][0])
642 642 self.samplesWin = samplingWindow['nsa'][0]
643 643
644 644
645 645 try:
646 646 if hasattr(fp, 'read'):
647 647 self.spectraComb = numpy.fromfile(fp, 'u1', 2*self.totalSpectra)
648 648 else:
649 649 self.spectraComb = numpy.fromstring(fp[self.length:], 'u1', 2*self.totalSpectra)
650 650 self.length += self.spectraComb.nbytes
651 651 except Exception, e:
652 652 print "ProcessingHeader: " + str(e)
653 653 return 0
654 654
655 655 if ((self.processFlags & PROCFLAG.DEFINE_PROCESS_CODE) == PROCFLAG.DEFINE_PROCESS_CODE):
656 656 self.nCode = int(numpy.fromfile(fp,'<u4',1))
657 657 self.nBaud = int(numpy.fromfile(fp,'<u4',1))
658 658 self.code = numpy.fromfile(fp,'<f4',self.nCode*self.nBaud).reshape(self.nCode,self.nBaud)
659 659
660 660 if ((self.processFlags & PROCFLAG.EXP_NAME_ESP) == PROCFLAG.EXP_NAME_ESP):
661 661 exp_name_len = int(numpy.fromfile(fp,'<u4',1))
662 662 exp_name = numpy.fromfile(fp,'u1',exp_name_len+1)
663 663
664 664 if ((self.processFlags & PROCFLAG.SHIFT_FFT_DATA) == PROCFLAG.SHIFT_FFT_DATA):
665 665 self.shif_fft = True
666 666 else:
667 667 self.shif_fft = False
668 668
669 669 if ((self.processFlags & PROCFLAG.SAVE_CHANNELS_DC) == PROCFLAG.SAVE_CHANNELS_DC):
670 670 self.flag_dc = True
671 671 else:
672 672 self.flag_dc = False
673 673
674 674 if ((self.processFlags & PROCFLAG.DECODE_DATA) == PROCFLAG.DECODE_DATA):
675 675 self.flag_decode = True
676 676 else:
677 677 self.flag_decode = False
678 678
679 679 if ((self.processFlags & PROCFLAG.DEFLIP_DATA) == PROCFLAG.DEFLIP_DATA):
680 680 self.flag_deflip = True
681 681 else:
682 682 self.flag_deflip = False
683 683
684 684 nChannels = 0
685 685 nPairs = 0
686 686 pairList = []
687 687
688 688 for i in range( 0, self.totalSpectra*2, 2 ):
689 689 if self.spectraComb[i] == self.spectraComb[i+1]:
690 690 nChannels = nChannels + 1 #par de canales iguales
691 691 else:
692 692 nPairs = nPairs + 1 #par de canales diferentes
693 693 pairList.append( (self.spectraComb[i], self.spectraComb[i+1]) )
694 694
695 695 self.flag_cspc = False
696 696 if nPairs > 0:
697 697 self.flag_cspc = True
698 698
699 699
700 700
701 701 if startFp is not None:
702 702 endFp = size + startFp
703 703 if fp.tell() > endFp:
704 704 sys.stderr.write("Warning: Processing header size is lower than it has to be")
705 705 return 0
706 706
707 707 if fp.tell() < endFp:
708 708 sys.stderr.write("Warning: Processing header size is greater than it is considered")
709 709
710 710 return 1
711 711
712 712 def write(self, fp):
713 713 #Clear DEFINE_PROCESS_CODE
714 714 self.processFlags = self.processFlags & (~PROCFLAG.DEFINE_PROCESS_CODE)
715 715
716 716 headerTuple = (self.size,
717 717 self.dtype,
718 718 self.blockSize,
719 719 self.profilesPerBlock,
720 720 self.dataBlocksPerFile,
721 721 self.nWindows,
722 722 self.processFlags,
723 723 self.nCohInt,
724 724 self.nIncohInt,
725 725 self.totalSpectra)
726 726
727 727 header = numpy.array(headerTuple,PROCESSING_STRUCTURE)
728 728 header.tofile(fp)
729 729
730 730 if self.nWindows != 0:
731 731 sampleWindowTuple = (self.firstHeight,self.deltaHeight,self.samplesWin)
732 732 samplingWindow = numpy.array(sampleWindowTuple,SAMPLING_STRUCTURE)
733 733 samplingWindow.tofile(fp)
734 734
735 735 if self.totalSpectra != 0:
736 736 # spectraComb = numpy.array([],numpy.dtype('u1'))
737 737 spectraComb = self.spectraComb
738 738 spectraComb.tofile(fp)
739 739
740 740 # if self.processFlags & PROCFLAG.DEFINE_PROCESS_CODE == PROCFLAG.DEFINE_PROCESS_CODE:
741 741 # nCode = numpy.array([self.nCode], numpy.dtype('u4')) #Probar con un dato que almacene codigo, hasta el momento no se hizo la prueba
742 742 # nCode.tofile(fp)
743 743 #
744 744 # nBaud = numpy.array([self.nBaud], numpy.dtype('u4'))
745 745 # nBaud.tofile(fp)
746 746 #
747 747 # code = self.code.reshape(self.nCode*self.nBaud)
748 748 # code = code.astype(numpy.dtype('<f4'))
749 749 # code.tofile(fp)
750 750
751 751 return 1
752 752
753 753 def get_size(self):
754 754
755 755 self.__size = 40 + 12*self.nWindows + 2*self.totalSpectra
756 756
757 757 # if self.processFlags & PROCFLAG.DEFINE_PROCESS_CODE == PROCFLAG.DEFINE_PROCESS_CODE:
758 758 # self.__size += 4 + 4 + 4*self.nCode*numpy.ceil(self.nBaud/32.)
759 759 # self.__size += 4 + 4 + 4 * self.nCode * self.nBaud
760 760
761 761 return self.__size
762 762
763 763 def set_size(self, value):
764 764
765 765 raise IOError, "size is a property and it cannot be set, just read"
766 766
767 767 return
768 768
769 769 size = property(get_size, set_size)
770 770
771 771 class RCfunction:
772 772 NONE=0
773 773 FLIP=1
774 774 CODE=2
775 775 SAMPLING=3
776 776 LIN6DIV256=4
777 777 SYNCHRO=5
778 778
779 779 class nCodeType:
780 780 NONE=0
781 781 USERDEFINE=1
782 782 BARKER2=2
783 783 BARKER3=3
784 784 BARKER4=4
785 785 BARKER5=5
786 786 BARKER7=6
787 787 BARKER11=7
788 788 BARKER13=8
789 789 AC128=9
790 790 COMPLEMENTARYCODE2=10
791 791 COMPLEMENTARYCODE4=11
792 792 COMPLEMENTARYCODE8=12
793 793 COMPLEMENTARYCODE16=13
794 794 COMPLEMENTARYCODE32=14
795 795 COMPLEMENTARYCODE64=15
796 796 COMPLEMENTARYCODE128=16
797 797 CODE_BINARY28=17
798 798
799 799 class PROCFLAG:
800 800
801 801 COHERENT_INTEGRATION = numpy.uint32(0x00000001)
802 802 DECODE_DATA = numpy.uint32(0x00000002)
803 803 SPECTRA_CALC = numpy.uint32(0x00000004)
804 804 INCOHERENT_INTEGRATION = numpy.uint32(0x00000008)
805 805 POST_COHERENT_INTEGRATION = numpy.uint32(0x00000010)
806 806 SHIFT_FFT_DATA = numpy.uint32(0x00000020)
807 807
808 808 DATATYPE_CHAR = numpy.uint32(0x00000040)
809 809 DATATYPE_SHORT = numpy.uint32(0x00000080)
810 810 DATATYPE_LONG = numpy.uint32(0x00000100)
811 811 DATATYPE_INT64 = numpy.uint32(0x00000200)
812 812 DATATYPE_FLOAT = numpy.uint32(0x00000400)
813 813 DATATYPE_DOUBLE = numpy.uint32(0x00000800)
814 814
815 815 DATAARRANGE_CONTIGUOUS_CH = numpy.uint32(0x00001000)
816 816 DATAARRANGE_CONTIGUOUS_H = numpy.uint32(0x00002000)
817 817 DATAARRANGE_CONTIGUOUS_P = numpy.uint32(0x00004000)
818 818
819 819 SAVE_CHANNELS_DC = numpy.uint32(0x00008000)
820 820 DEFLIP_DATA = numpy.uint32(0x00010000)
821 821 DEFINE_PROCESS_CODE = numpy.uint32(0x00020000)
822 822
823 823 ACQ_SYS_NATALIA = numpy.uint32(0x00040000)
824 824 ACQ_SYS_ECHOTEK = numpy.uint32(0x00080000)
825 825 ACQ_SYS_ADRXD = numpy.uint32(0x000C0000)
826 826 ACQ_SYS_JULIA = numpy.uint32(0x00100000)
827 827 ACQ_SYS_XXXXXX = numpy.uint32(0x00140000)
828 828
829 829 EXP_NAME_ESP = numpy.uint32(0x00200000)
830 830 CHANNEL_NAMES_ESP = numpy.uint32(0x00400000)
831 831
832 832 OPERATION_MASK = numpy.uint32(0x0000003F)
833 833 DATATYPE_MASK = numpy.uint32(0x00000FC0)
834 834 DATAARRANGE_MASK = numpy.uint32(0x00007000)
835 835 ACQ_SYS_MASK = numpy.uint32(0x001C0000)
836 836
837 837 dtype0 = numpy.dtype([('real','<i1'),('imag','<i1')])
838 838 dtype1 = numpy.dtype([('real','<i2'),('imag','<i2')])
839 839 dtype2 = numpy.dtype([('real','<i4'),('imag','<i4')])
840 840 dtype3 = numpy.dtype([('real','<i8'),('imag','<i8')])
841 841 dtype4 = numpy.dtype([('real','<f4'),('imag','<f4')])
842 842 dtype5 = numpy.dtype([('real','<f8'),('imag','<f8')])
843 843
844 844 NUMPY_DTYPE_LIST = [dtype0, dtype1, dtype2, dtype3, dtype4, dtype5]
845 845
846 846 PROCFLAG_DTYPE_LIST = [PROCFLAG.DATATYPE_CHAR,
847 847 PROCFLAG.DATATYPE_SHORT,
848 848 PROCFLAG.DATATYPE_LONG,
849 849 PROCFLAG.DATATYPE_INT64,
850 850 PROCFLAG.DATATYPE_FLOAT,
851 851 PROCFLAG.DATATYPE_DOUBLE]
852 852
853 853 DTYPE_WIDTH = [1, 2, 4, 8, 4, 8]
854 854
855 855 def get_dtype_index(numpy_dtype):
856 856
857 857 index = None
858 858
859 859 for i in range(len(NUMPY_DTYPE_LIST)):
860 860 if numpy_dtype == NUMPY_DTYPE_LIST[i]:
861 861 index = i
862 862 break
863 863
864 864 return index
865 865
866 866 def get_numpy_dtype(index):
867 867
868 868 return NUMPY_DTYPE_LIST[index]
869 869
870 870 def get_procflag_dtype(index):
871 871
872 872 return PROCFLAG_DTYPE_LIST[index]
873 873
874 874 def get_dtype_width(index):
875 875
876 876 return DTYPE_WIDTH[index] No newline at end of file
@@ -1,1833 +1,1824
1 1 '''
2 2 Created on Jul 2, 2014
3 3
4 4 @author: roj-idl71
5 5 '''
6 6 import os
7 7 import sys
8 8 import glob
9 9 import time
10 10 import numpy
11 11 import fnmatch
12 12 import inspect
13 13 import time
14 14 import datetime
15 15 import traceback
16 16 import zmq
17 17
18 18 try:
19 19 from gevent import sleep
20 20 except:
21 21 from time import sleep
22 22
23 23 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
24 24 from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width
25 from schainpy.utils import log
25 26
26 27 LOCALTIME = True
27 28
28 29
29 30 def isNumber(cad):
30 31 """
31 32 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
32 33
33 34 Excepciones:
34 35 Si un determinado string no puede ser convertido a numero
35 36 Input:
36 37 str, string al cual se le analiza para determinar si convertible a un numero o no
37 38
38 39 Return:
39 40 True : si el string es uno numerico
40 41 False : no es un string numerico
41 42 """
42 43 try:
43 44 float(cad)
44 45 return True
45 46 except:
46 47 return False
47 48
48 49
49 50 def isFileInEpoch(filename, startUTSeconds, endUTSeconds):
50 51 """
51 52 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
52 53
53 54 Inputs:
54 55 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
55 56
56 57 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
57 58 segundos contados desde 01/01/1970.
58 59 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
59 60 segundos contados desde 01/01/1970.
60 61
61 62 Return:
62 63 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
63 64 fecha especificado, de lo contrario retorna False.
64 65
65 66 Excepciones:
66 67 Si el archivo no existe o no puede ser abierto
67 68 Si la cabecera no puede ser leida.
68 69
69 70 """
70 71 basicHeaderObj = BasicHeader(LOCALTIME)
71 72
72 73 try:
73 74 fp = open(filename, 'rb')
74 75 except IOError:
75 76 print "The file %s can't be opened" % (filename)
76 77 return 0
77 78
78 79 sts = basicHeaderObj.read(fp)
79 80 fp.close()
80 81
81 82 if not(sts):
82 83 print "Skipping the file %s because it has not a valid header" % (filename)
83 84 return 0
84 85
85 86 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
86 87 return 0
87 88
88 89 return 1
89 90
90 91
91 92 def isTimeInRange(thisTime, startTime, endTime):
92 93 if endTime >= startTime:
93 94 if (thisTime < startTime) or (thisTime > endTime):
94 95 return 0
95 96 return 1
96 97 else:
97 98 if (thisTime < startTime) and (thisTime > endTime):
98 99 return 0
99 100 return 1
100 101
101 102
102 103 def isFileInTimeRange(filename, startDate, endDate, startTime, endTime):
103 104 """
104 105 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
105 106
106 107 Inputs:
107 108 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
108 109
109 110 startDate : fecha inicial del rango seleccionado en formato datetime.date
110 111
111 112 endDate : fecha final del rango seleccionado en formato datetime.date
112 113
113 114 startTime : tiempo inicial del rango seleccionado en formato datetime.time
114 115
115 116 endTime : tiempo final del rango seleccionado en formato datetime.time
116 117
117 118 Return:
118 119 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
119 120 fecha especificado, de lo contrario retorna False.
120 121
121 122 Excepciones:
122 123 Si el archivo no existe o no puede ser abierto
123 124 Si la cabecera no puede ser leida.
124 125
125 126 """
126 127
127 128 try:
128 129 fp = open(filename, 'rb')
129 130 except IOError:
130 131 print "The file %s can't be opened" % (filename)
131 132 return None
132 133
133 134 firstBasicHeaderObj = BasicHeader(LOCALTIME)
134 135 systemHeaderObj = SystemHeader()
135 136 radarControllerHeaderObj = RadarControllerHeader()
136 137 processingHeaderObj = ProcessingHeader()
137 138
138 139 lastBasicHeaderObj = BasicHeader(LOCALTIME)
139 140
140 141 sts = firstBasicHeaderObj.read(fp)
141 142
142 143 if not(sts):
143 144 print "[Reading] Skipping the file %s because it has not a valid header" % (filename)
144 145 return None
145 146
146 147 if not systemHeaderObj.read(fp):
147 148 return None
148 149
149 150 if not radarControllerHeaderObj.read(fp):
150 151 return None
151 152
152 153 if not processingHeaderObj.read(fp):
153 154 return None
154 155
155 156 filesize = os.path.getsize(filename)
156 157
157 158 offset = processingHeaderObj.blockSize + 24 # header size
158 159
159 160 if filesize <= offset:
160 161 print "[Reading] %s: This file has not enough data" % filename
161 162 return None
162 163
163 164 fp.seek(-offset, 2)
164 165
165 166 sts = lastBasicHeaderObj.read(fp)
166 167
167 168 fp.close()
168 169
169 170 thisDatetime = lastBasicHeaderObj.datatime
170 171 thisTime_last_block = thisDatetime.time()
171 172
172 173 thisDatetime = firstBasicHeaderObj.datatime
173 174 thisDate = thisDatetime.date()
174 175 thisTime_first_block = thisDatetime.time()
175 176
176 177 # General case
177 178 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
178 179 #-----------o----------------------------o-----------
179 180 # startTime endTime
180 181
181 182 if endTime >= startTime:
182 183 if (thisTime_last_block < startTime) or (thisTime_first_block > endTime):
183 184 return None
184 185
185 186 return thisDatetime
186 187
187 188 # If endTime < startTime then endTime belongs to the next day
188 189
189 190 #<<<<<<<<<<<o o>>>>>>>>>>>
190 191 #-----------o----------------------------o-----------
191 192 # endTime startTime
192 193
193 194 if (thisDate == startDate) and (thisTime_last_block < startTime):
194 195 return None
195 196
196 197 if (thisDate == endDate) and (thisTime_first_block > endTime):
197 198 return None
198 199
199 200 if (thisTime_last_block < startTime) and (thisTime_first_block > endTime):
200 201 return None
201 202
202 203 return thisDatetime
203 204
204 205
205 206 def isFolderInDateRange(folder, startDate=None, endDate=None):
206 207 """
207 208 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
208 209
209 210 Inputs:
210 211 folder : nombre completo del directorio.
211 212 Su formato deberia ser "/path_root/?YYYYDDD"
212 213
213 214 siendo:
214 215 YYYY : Anio (ejemplo 2015)
215 216 DDD : Dia del anio (ejemplo 305)
216 217
217 218 startDate : fecha inicial del rango seleccionado en formato datetime.date
218 219
219 220 endDate : fecha final del rango seleccionado en formato datetime.date
220 221
221 222 Return:
222 223 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
223 224 fecha especificado, de lo contrario retorna False.
224 225 Excepciones:
225 226 Si el directorio no tiene el formato adecuado
226 227 """
227 228
228 229 basename = os.path.basename(folder)
229 230
230 231 if not isRadarFolder(basename):
231 232 print "The folder %s has not the rigth format" % folder
232 233 return 0
233 234
234 235 if startDate and endDate:
235 236 thisDate = getDateFromRadarFolder(basename)
236 237
237 238 if thisDate < startDate:
238 239 return 0
239 240
240 241 if thisDate > endDate:
241 242 return 0
242 243
243 244 return 1
244 245
245 246
246 247 def isFileInDateRange(filename, startDate=None, endDate=None):
247 248 """
248 249 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
249 250
250 251 Inputs:
251 252 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
252 253
253 254 Su formato deberia ser "?YYYYDDDsss"
254 255
255 256 siendo:
256 257 YYYY : Anio (ejemplo 2015)
257 258 DDD : Dia del anio (ejemplo 305)
258 259 sss : set
259 260
260 261 startDate : fecha inicial del rango seleccionado en formato datetime.date
261 262
262 263 endDate : fecha final del rango seleccionado en formato datetime.date
263 264
264 265 Return:
265 266 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
266 267 fecha especificado, de lo contrario retorna False.
267 268 Excepciones:
268 269 Si el archivo no tiene el formato adecuado
269 270 """
270 271
271 272 basename = os.path.basename(filename)
272 273
273 274 if not isRadarFile(basename):
274 275 print "The filename %s has not the rigth format" % filename
275 276 return 0
276 277
277 278 if startDate and endDate:
278 279 thisDate = getDateFromRadarFile(basename)
279 280
280 281 if thisDate < startDate:
281 282 return 0
282 283
283 284 if thisDate > endDate:
284 285 return 0
285 286
286 287 return 1
287 288
288 289
289 290 def getFileFromSet(path, ext, set):
290 291 validFilelist = []
291 292 fileList = os.listdir(path)
292 293
293 294 # 0 1234 567 89A BCDE
294 295 # H YYYY DDD SSS .ext
295 296
296 297 for thisFile in fileList:
297 298 try:
298 299 year = int(thisFile[1:5])
299 300 doy = int(thisFile[5:8])
300 301 except:
301 302 continue
302 303
303 304 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
304 305 continue
305 306
306 307 validFilelist.append(thisFile)
307 308
308 309 myfile = fnmatch.filter(
309 310 validFilelist, '*%4.4d%3.3d%3.3d*' % (year, doy, set))
310 311
311 312 if len(myfile) != 0:
312 313 return myfile[0]
313 314 else:
314 315 filename = '*%4.4d%3.3d%3.3d%s' % (year, doy, set, ext.lower())
315 316 print 'the filename %s does not exist' % filename
316 317 print '...going to the last file: '
317 318
318 319 if validFilelist:
319 320 validFilelist = sorted(validFilelist, key=str.lower)
320 321 return validFilelist[-1]
321 322
322 323 return None
323 324
324 325
325 326 def getlastFileFromPath(path, ext):
326 327 """
327 328 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
328 329 al final de la depuracion devuelve el ultimo file de la lista que quedo.
329 330
330 331 Input:
331 332 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
332 333 ext : extension de los files contenidos en una carpeta
333 334
334 335 Return:
335 336 El ultimo file de una determinada carpeta, no se considera el path.
336 337 """
337 338 validFilelist = []
338 339 fileList = os.listdir(path)
339 340
340 341 # 0 1234 567 89A BCDE
341 342 # H YYYY DDD SSS .ext
342 343
343 344 for thisFile in fileList:
344 345
345 346 year = thisFile[1:5]
346 347 if not isNumber(year):
347 348 continue
348 349
349 350 doy = thisFile[5:8]
350 351 if not isNumber(doy):
351 352 continue
352 353
353 354 year = int(year)
354 355 doy = int(doy)
355 356
356 357 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
357 358 continue
358 359
359 360 validFilelist.append(thisFile)
360 361
361 362 if validFilelist:
362 363 validFilelist = sorted(validFilelist, key=str.lower)
363 364 return validFilelist[-1]
364 365
365 366 return None
366 367
367 368
368 369 def checkForRealPath(path, foldercounter, year, doy, set, ext):
369 370 """
370 371 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
371 372 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
372 373 el path exacto de un determinado file.
373 374
374 375 Example :
375 376 nombre correcto del file es .../.../D2009307/P2009307367.ext
376 377
377 378 Entonces la funcion prueba con las siguientes combinaciones
378 379 .../.../y2009307367.ext
379 380 .../.../Y2009307367.ext
380 381 .../.../x2009307/y2009307367.ext
381 382 .../.../x2009307/Y2009307367.ext
382 383 .../.../X2009307/y2009307367.ext
383 384 .../.../X2009307/Y2009307367.ext
384 385 siendo para este caso, la ultima combinacion de letras, identica al file buscado
385 386
386 387 Return:
387 388 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
388 389 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
389 390 para el filename
390 391 """
391 392 fullfilename = None
392 393 find_flag = False
393 394 filename = None
394 395
395 396 prefixDirList = [None, 'd', 'D']
396 397 if ext.lower() == ".r": # voltage
397 398 prefixFileList = ['d', 'D']
398 399 elif ext.lower() == ".pdata": # spectra
399 400 prefixFileList = ['p', 'P']
400 401 else:
401 402 return None, filename
402 403
403 404 # barrido por las combinaciones posibles
404 405 for prefixDir in prefixDirList:
405 406 thispath = path
406 407 if prefixDir != None:
407 408 # formo el nombre del directorio xYYYYDDD (x=d o x=D)
408 409 if foldercounter == 0:
409 410 thispath = os.path.join(path, "%s%04d%03d" %
410 411 (prefixDir, year, doy))
411 412 else:
412 413 thispath = os.path.join(path, "%s%04d%03d_%02d" % (
413 414 prefixDir, year, doy, foldercounter))
414 415 for prefixFile in prefixFileList: # barrido por las dos combinaciones posibles de "D"
415 416 # formo el nombre del file xYYYYDDDSSS.ext
416 417 filename = "%s%04d%03d%03d%s" % (prefixFile, year, doy, set, ext)
417 418 fullfilename = os.path.join(
418 419 thispath, filename) # formo el path completo
419 420
420 421 if os.path.exists(fullfilename): # verifico que exista
421 422 find_flag = True
422 423 break
423 424 if find_flag:
424 425 break
425 426
426 427 if not(find_flag):
427 428 return None, filename
428 429
429 430 return fullfilename, filename
430 431
431 432
432 433 def isRadarFolder(folder):
433 434 try:
434 435 year = int(folder[1:5])
435 436 doy = int(folder[5:8])
436 437 except:
437 438 return 0
438 439
439 440 return 1
440 441
441 442
442 443 def isRadarFile(file):
443 444 try:
444 445 year = int(file[1:5])
445 446 doy = int(file[5:8])
446 447 set = int(file[8:11])
447 448 except:
448 449 return 0
449 450
450 451 return 1
451 452
452 453
453 454 def getDateFromRadarFile(file):
454 455 try:
455 456 year = int(file[1:5])
456 457 doy = int(file[5:8])
457 458 set = int(file[8:11])
458 459 except:
459 460 return None
460 461
461 462 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
462 463 return thisDate
463 464
464 465
465 466 def getDateFromRadarFolder(folder):
466 467 try:
467 468 year = int(folder[1:5])
468 469 doy = int(folder[5:8])
469 470 except:
470 471 return None
471 472
472 473 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
473 474 return thisDate
474 475
475 476
476 477 class JRODataIO:
477 478
478 479 c = 3E8
479 480
480 481 isConfig = False
481 482
482 483 basicHeaderObj = None
483 484
484 485 systemHeaderObj = None
485 486
486 487 radarControllerHeaderObj = None
487 488
488 489 processingHeaderObj = None
489 490
490 491 dtype = None
491 492
492 493 pathList = []
493 494
494 495 filenameList = []
495 496
496 497 filename = None
497 498
498 499 ext = None
499 500
500 501 flagIsNewFile = 1
501 502
502 503 flagDiscontinuousBlock = 0
503 504
504 505 flagIsNewBlock = 0
505 506
506 507 fp = None
507 508
508 509 firstHeaderSize = 0
509 510
510 511 basicHeaderSize = 24
511 512
512 513 versionFile = 1103
513 514
514 515 fileSize = None
515 516
516 517 # ippSeconds = None
517 518
518 519 fileSizeByHeader = None
519 520
520 521 fileIndex = None
521 522
522 523 profileIndex = None
523 524
524 525 blockIndex = None
525 526
526 527 nTotalBlocks = None
527 528
528 529 maxTimeStep = 30
529 530
530 531 lastUTTime = None
531 532
532 533 datablock = None
533 534
534 535 dataOut = None
535 536
536 537 blocksize = None
537 538
538 539 getByBlock = False
539 540
540 541 def __init__(self):
541 542
542 543 raise NotImplementedError
543 544
544 545 def run(self):
545 546
546 547 raise NotImplementedError
547 548
548 549 def getDtypeWidth(self):
549 550
550 551 dtype_index = get_dtype_index(self.dtype)
551 552 dtype_width = get_dtype_width(dtype_index)
552 553
553 554 return dtype_width
554 555
555 556 def getAllowedArgs(self):
556 557 if hasattr(self, '__attrs__'):
557 558 return self.__attrs__
558 559 else:
559 560 return inspect.getargspec(self.run).args
560 561
561 562
562 563 class JRODataReader(JRODataIO):
563 564
564 565 online = 0
565 566
566 567 realtime = 0
567 568
568 569 nReadBlocks = 0
569 570
570 571 delay = 10 # number of seconds waiting a new file
571 572
572 573 nTries = 3 # quantity tries
573 574
574 575 nFiles = 3 # number of files for searching
575 576
576 577 path = None
577 578
578 579 foldercounter = 0
579 580
580 581 flagNoMoreFiles = 0
581 582
582 583 datetimeList = []
583 584
584 585 __isFirstTimeOnline = 1
585 586
586 587 __printInfo = True
587 588
588 589 profileIndex = None
589 590
590 591 nTxs = 1
591 592
592 593 txIndex = None
593 594
594 595 # Added--------------------
595 596
596 597 selBlocksize = None
597 598
598 599 selBlocktime = None
599 600
600 601 def __init__(self):
601 602 """
602 603 This class is used to find data files
603 604
604 605 Example:
605 606 reader = JRODataReader()
606 607 fileList = reader.findDataFiles()
607 608
608 609 """
609 610 pass
610 611
611 612 def createObjByDefault(self):
612 613 """
613 614
614 615 """
615 616 raise NotImplementedError
616 617
617 618 def getBlockDimension(self):
618 619
619 620 raise NotImplementedError
620 621
621 622 def searchFilesOffLine(self,
622 623 path,
623 624 startDate=None,
624 625 endDate=None,
625 626 startTime=datetime.time(0, 0, 0),
626 627 endTime=datetime.time(23, 59, 59),
627 628 set=None,
628 629 expLabel='',
629 630 ext='.r',
630 631 cursor=None,
631 632 skip=None,
632 633 walk=True):
633 634
634 635 self.filenameList = []
635 636 self.datetimeList = []
636 637
637 638 pathList = []
638 639
639 640 dateList, pathList = self.findDatafiles(
640 641 path, startDate, endDate, expLabel, ext, walk, include_path=True)
641 642
642 643 if dateList == []:
643 644 return [], []
644 645
645 646 if len(dateList) > 1:
646 647 print "[Reading] Data found for date range [%s - %s]: total days = %d" % (startDate, endDate, len(dateList))
647 648 else:
648 649 print "[Reading] Data found for date range [%s - %s]: date = %s" % (startDate, endDate, dateList[0])
649 650
650 651 filenameList = []
651 652 datetimeList = []
652 653
653 654 for thisPath in pathList:
654 655
655 656 fileList = glob.glob1(thisPath, "*%s" % ext)
656 657 fileList.sort()
657 658
658 skippedFileList = []
659
660 if cursor is not None and skip is not None:
661
662 if skip == 0:
663 skippedFileList = []
664 else:
665 skippedFileList = fileList[cursor *
666 skip: cursor * skip + skip]
667
668 else:
669 skippedFileList = fileList
670
671 for file in skippedFileList:
659 for file in fileList:
672 660
673 661 filename = os.path.join(thisPath, file)
674 662
675 663 if not isFileInDateRange(filename, startDate, endDate):
676 664 continue
677 665
678 666 thisDatetime = isFileInTimeRange(
679 667 filename, startDate, endDate, startTime, endTime)
680 668
681 669 if not(thisDatetime):
682 670 continue
683 671
684 672 filenameList.append(filename)
685 673 datetimeList.append(thisDatetime)
686 674
675 if cursor is not None and skip is not None:
676 filenameList = filenameList[cursor * skip:cursor * skip + skip]
677 datetimeList = datetimeList[cursor * skip:cursor * skip + skip]
678
687 679 if not(filenameList):
688 680 print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" % (startTime, endTime, ext, path)
689 681 return [], []
690 682
691 683 print "[Reading] %d file(s) was(were) found in time range: %s - %s" % (len(filenameList), startTime, endTime)
692 print
693 684
694 685 # for i in range(len(filenameList)):
695 686 # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
696 687
697 688 self.filenameList = filenameList
698 689 self.datetimeList = datetimeList
699 690
700 691 return pathList, filenameList
701 692
702 693 def __searchFilesOnLine(self, path, expLabel="", ext=None, walk=True, set=None):
703 694 """
704 695 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
705 696 devuelve el archivo encontrado ademas de otros datos.
706 697
707 698 Input:
708 699 path : carpeta donde estan contenidos los files que contiene data
709 700
710 701 expLabel : Nombre del subexperimento (subfolder)
711 702
712 703 ext : extension de los files
713 704
714 705 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
715 706
716 707 Return:
717 708 directory : eL directorio donde esta el file encontrado
718 709 filename : el ultimo file de una determinada carpeta
719 710 year : el anho
720 711 doy : el numero de dia del anho
721 712 set : el set del archivo
722 713
723 714
724 715 """
725 716 if not os.path.isdir(path):
726 717 return None, None, None, None, None, None
727 718
728 719 dirList = []
729 720
730 721 if not walk:
731 722 fullpath = path
732 723 foldercounter = 0
733 724 else:
734 725 # Filtra solo los directorios
735 726 for thisPath in os.listdir(path):
736 727 if not os.path.isdir(os.path.join(path, thisPath)):
737 728 continue
738 729 if not isRadarFolder(thisPath):
739 730 continue
740 731
741 732 dirList.append(thisPath)
742 733
743 734 if not(dirList):
744 735 return None, None, None, None, None, None
745 736
746 737 dirList = sorted(dirList, key=str.lower)
747 738
748 739 doypath = dirList[-1]
749 740 foldercounter = int(doypath.split('_')[1]) if len(
750 741 doypath.split('_')) > 1 else 0
751 742 fullpath = os.path.join(path, doypath, expLabel)
752 743
753 744 print "[Reading] %s folder was found: " % (fullpath)
754 745
755 746 if set == None:
756 747 filename = getlastFileFromPath(fullpath, ext)
757 748 else:
758 749 filename = getFileFromSet(fullpath, ext, set)
759 750
760 751 if not(filename):
761 752 return None, None, None, None, None, None
762 753
763 754 print "[Reading] %s file was found" % (filename)
764 755
765 756 if not(self.__verifyFile(os.path.join(fullpath, filename))):
766 757 return None, None, None, None, None, None
767 758
768 759 year = int(filename[1:5])
769 760 doy = int(filename[5:8])
770 761 set = int(filename[8:11])
771 762
772 763 return fullpath, foldercounter, filename, year, doy, set
773 764
774 765 def __setNextFileOffline(self):
775 766
776 767 idFile = self.fileIndex
777 768
778 769 while (True):
779 770 idFile += 1
780 771 if not(idFile < len(self.filenameList)):
781 772 self.flagNoMoreFiles = 1
782 773 # print "[Reading] No more Files"
783 774 return 0
784 775
785 776 filename = self.filenameList[idFile]
786 777
787 778 if not(self.__verifyFile(filename)):
788 779 continue
789 780
790 781 fileSize = os.path.getsize(filename)
791 782 fp = open(filename, 'rb')
792 783 break
793 784
794 785 self.flagIsNewFile = 1
795 786 self.fileIndex = idFile
796 787 self.filename = filename
797 788 self.fileSize = fileSize
798 789 self.fp = fp
799 790
800 791 # print "[Reading] Setting the file: %s"%self.filename
801 792
802 793 return 1
803 794
804 795 def __setNextFileOnline(self):
805 796 """
806 797 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
807 798 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
808 799 siguientes.
809 800
810 801 Affected:
811 802 self.flagIsNewFile
812 803 self.filename
813 804 self.fileSize
814 805 self.fp
815 806 self.set
816 807 self.flagNoMoreFiles
817 808
818 809 Return:
819 810 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
820 811 1 : si el file fue abierto con exito y esta listo a ser leido
821 812
822 813 Excepciones:
823 814 Si un determinado file no puede ser abierto
824 815 """
825 816 nFiles = 0
826 817 fileOk_flag = False
827 818 firstTime_flag = True
828 819
829 820 self.set += 1
830 821
831 822 if self.set > 999:
832 823 self.set = 0
833 824 self.foldercounter += 1
834 825
835 826 # busca el 1er file disponible
836 827 fullfilename, filename = checkForRealPath(
837 828 self.path, self.foldercounter, self.year, self.doy, self.set, self.ext)
838 829 if fullfilename:
839 830 if self.__verifyFile(fullfilename, False):
840 831 fileOk_flag = True
841 832
842 833 # si no encuentra un file entonces espera y vuelve a buscar
843 834 if not(fileOk_flag):
844 835 # busco en los siguientes self.nFiles+1 files posibles
845 836 for nFiles in range(self.nFiles + 1):
846 837
847 838 if firstTime_flag: # si es la 1era vez entonces hace el for self.nTries veces
848 839 tries = self.nTries
849 840 else:
850 841 tries = 1 # si no es la 1era vez entonces solo lo hace una vez
851 842
852 843 for nTries in range(tries):
853 844 if firstTime_flag:
854 845 print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % (self.delay, filename, nTries + 1)
855 846 sleep(self.delay)
856 847 else:
857 848 print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
858 849
859 850 fullfilename, filename = checkForRealPath(
860 851 self.path, self.foldercounter, self.year, self.doy, self.set, self.ext)
861 852 if fullfilename:
862 853 if self.__verifyFile(fullfilename):
863 854 fileOk_flag = True
864 855 break
865 856
866 857 if fileOk_flag:
867 858 break
868 859
869 860 firstTime_flag = False
870 861
871 862 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
872 863 self.set += 1
873 864
874 865 # si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
875 866 if nFiles == (self.nFiles - 1):
876 867 self.set = 0
877 868 self.doy += 1
878 869 self.foldercounter = 0
879 870
880 871 if fileOk_flag:
881 872 self.fileSize = os.path.getsize(fullfilename)
882 873 self.filename = fullfilename
883 874 self.flagIsNewFile = 1
884 875 if self.fp != None:
885 876 self.fp.close()
886 877 self.fp = open(fullfilename, 'rb')
887 878 self.flagNoMoreFiles = 0
888 879 # print '[Reading] Setting the file: %s' % fullfilename
889 880 else:
890 881 self.fileSize = 0
891 882 self.filename = None
892 883 self.flagIsNewFile = 0
893 884 self.fp = None
894 885 self.flagNoMoreFiles = 1
895 886 # print '[Reading] No more files to read'
896 887
897 888 return fileOk_flag
898 889
899 890 def setNextFile(self):
900 891 if self.fp != None:
901 892 self.fp.close()
902 893
903 894 if self.online:
904 895 newFile = self.__setNextFileOnline()
905 896 else:
906 897 newFile = self.__setNextFileOffline()
907 898
908 899 if not(newFile):
909 900 print '[Reading] No more files to read'
910 901 return 0
911 902
912 903 if self.verbose:
913 904 print '[Reading] Setting the file: %s' % self.filename
914 905
915 906 self.__readFirstHeader()
916 907 self.nReadBlocks = 0
917 908 return 1
918 909
919 910 def __waitNewBlock(self):
920 911 """
921 912 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
922 913
923 914 Si el modo de lectura es OffLine siempre retorn 0
924 915 """
925 916 if not self.online:
926 917 return 0
927 918
928 919 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
929 920 return 0
930 921
931 922 currentPointer = self.fp.tell()
932 923
933 924 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
934 925
935 926 for nTries in range(self.nTries):
936 927
937 928 self.fp.close()
938 929 self.fp = open(self.filename, 'rb')
939 930 self.fp.seek(currentPointer)
940 931
941 932 self.fileSize = os.path.getsize(self.filename)
942 933 currentSize = self.fileSize - currentPointer
943 934
944 935 if (currentSize >= neededSize):
945 936 self.basicHeaderObj.read(self.fp)
946 937 return 1
947 938
948 939 if self.fileSize == self.fileSizeByHeader:
949 940 # self.flagEoF = True
950 941 return 0
951 942
952 943 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1)
953 944 sleep(self.delay)
954 945
955 946 return 0
956 947
957 948 def waitDataBlock(self, pointer_location):
958 949
959 950 currentPointer = pointer_location
960 951
961 952 neededSize = self.processingHeaderObj.blockSize # + self.basicHeaderSize
962 953
963 954 for nTries in range(self.nTries):
964 955 self.fp.close()
965 956 self.fp = open(self.filename, 'rb')
966 957 self.fp.seek(currentPointer)
967 958
968 959 self.fileSize = os.path.getsize(self.filename)
969 960 currentSize = self.fileSize - currentPointer
970 961
971 962 if (currentSize >= neededSize):
972 963 return 1
973 964
974 965 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1)
975 966 sleep(self.delay)
976 967
977 968 return 0
978 969
979 970 def __jumpToLastBlock(self):
980 971
981 972 if not(self.__isFirstTimeOnline):
982 973 return
983 974
984 975 csize = self.fileSize - self.fp.tell()
985 976 blocksize = self.processingHeaderObj.blockSize
986 977
987 978 # salta el primer bloque de datos
988 979 if csize > self.processingHeaderObj.blockSize:
989 980 self.fp.seek(self.fp.tell() + blocksize)
990 981 else:
991 982 return
992 983
993 984 csize = self.fileSize - self.fp.tell()
994 985 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
995 986 while True:
996 987
997 988 if self.fp.tell() < self.fileSize:
998 989 self.fp.seek(self.fp.tell() + neededsize)
999 990 else:
1000 991 self.fp.seek(self.fp.tell() - neededsize)
1001 992 break
1002 993
1003 994 # csize = self.fileSize - self.fp.tell()
1004 995 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1005 996 # factor = int(csize/neededsize)
1006 997 # if factor > 0:
1007 998 # self.fp.seek(self.fp.tell() + factor*neededsize)
1008 999
1009 1000 self.flagIsNewFile = 0
1010 1001 self.__isFirstTimeOnline = 0
1011 1002
1012 1003 def __setNewBlock(self):
1013 1004 # if self.server is None:
1014 1005 if self.fp == None:
1015 1006 return 0
1016 1007
1017 1008 # if self.online:
1018 1009 # self.__jumpToLastBlock()
1019 1010
1020 1011 if self.flagIsNewFile:
1021 1012 self.lastUTTime = self.basicHeaderObj.utc
1022 1013 return 1
1023 1014
1024 1015 if self.realtime:
1025 1016 self.flagDiscontinuousBlock = 1
1026 1017 if not(self.setNextFile()):
1027 1018 return 0
1028 1019 else:
1029 1020 return 1
1030 1021 # if self.server is None:
1031 1022 currentSize = self.fileSize - self.fp.tell()
1032 1023 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1033 1024 if (currentSize >= neededSize):
1034 1025 self.basicHeaderObj.read(self.fp)
1035 1026 self.lastUTTime = self.basicHeaderObj.utc
1036 1027 return 1
1037 1028 # else:
1038 1029 # self.basicHeaderObj.read(self.zHeader)
1039 1030 # self.lastUTTime = self.basicHeaderObj.utc
1040 1031 # return 1
1041 1032 if self.__waitNewBlock():
1042 1033 self.lastUTTime = self.basicHeaderObj.utc
1043 1034 return 1
1044 1035 # if self.server is None:
1045 1036 if not(self.setNextFile()):
1046 1037 return 0
1047 1038
1048 1039 deltaTime = self.basicHeaderObj.utc - self.lastUTTime
1049 1040 self.lastUTTime = self.basicHeaderObj.utc
1050 1041
1051 1042 self.flagDiscontinuousBlock = 0
1052 1043
1053 1044 if deltaTime > self.maxTimeStep:
1054 1045 self.flagDiscontinuousBlock = 1
1055 1046
1056 1047 return 1
1057 1048
1058 1049 def readNextBlock(self):
1059 1050
1060 1051 # Skip block out of startTime and endTime
1061 1052 while True:
1062 1053 if not(self.__setNewBlock()):
1063 1054 return 0
1064 1055
1065 1056 if not(self.readBlock()):
1066 1057 return 0
1067 1058
1068 1059 self.getBasicHeader()
1069 1060 if (self.dataOut.datatime < datetime.datetime.combine(self.startDate, self.startTime)) or (self.dataOut.datatime > datetime.datetime.combine(self.endDate, self.endTime)):
1070 1061 print "[Reading] Block No. %d/%d -> %s [Skipping]" % (self.nReadBlocks,
1071 1062 self.processingHeaderObj.dataBlocksPerFile,
1072 1063 self.dataOut.datatime.ctime())
1073 1064 continue
1074 1065
1075 1066 break
1076 1067
1077 1068 if self.verbose:
1078 1069 print "[Reading] Block No. %d/%d -> %s" % (self.nReadBlocks,
1079 1070 self.processingHeaderObj.dataBlocksPerFile,
1080 1071 self.dataOut.datatime.ctime())
1081 1072 return 1
1082 1073
1083 1074 def __readFirstHeader(self):
1084 1075
1085 1076 self.basicHeaderObj.read(self.fp)
1086 1077 self.systemHeaderObj.read(self.fp)
1087 1078 self.radarControllerHeaderObj.read(self.fp)
1088 1079 self.processingHeaderObj.read(self.fp)
1089 1080
1090 1081 self.firstHeaderSize = self.basicHeaderObj.size
1091 1082
1092 1083 datatype = int(numpy.log2((self.processingHeaderObj.processFlags &
1093 1084 PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR))
1094 1085 if datatype == 0:
1095 1086 datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
1096 1087 elif datatype == 1:
1097 1088 datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
1098 1089 elif datatype == 2:
1099 1090 datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
1100 1091 elif datatype == 3:
1101 1092 datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
1102 1093 elif datatype == 4:
1103 1094 datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
1104 1095 elif datatype == 5:
1105 1096 datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
1106 1097 else:
1107 1098 raise ValueError, 'Data type was not defined'
1108 1099
1109 1100 self.dtype = datatype_str
1110 1101 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
1111 1102 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \
1112 1103 self.firstHeaderSize + self.basicHeaderSize * \
1113 1104 (self.processingHeaderObj.dataBlocksPerFile - 1)
1114 1105 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
1115 1106 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
1116 1107 self.getBlockDimension()
1117 1108
1118 1109 def __verifyFile(self, filename, msgFlag=True):
1119 1110
1120 1111 msg = None
1121 1112
1122 1113 try:
1123 1114 fp = open(filename, 'rb')
1124 1115 except IOError:
1125 1116
1126 1117 if msgFlag:
1127 1118 print "[Reading] File %s can't be opened" % (filename)
1128 1119
1129 1120 return False
1130 1121
1131 1122 currentPosition = fp.tell()
1132 1123 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
1133 1124
1134 1125 if neededSize == 0:
1135 1126 basicHeaderObj = BasicHeader(LOCALTIME)
1136 1127 systemHeaderObj = SystemHeader()
1137 1128 radarControllerHeaderObj = RadarControllerHeader()
1138 1129 processingHeaderObj = ProcessingHeader()
1139 1130
1140 1131 if not(basicHeaderObj.read(fp)):
1141 1132 fp.close()
1142 1133 return False
1143 1134
1144 1135 if not(systemHeaderObj.read(fp)):
1145 1136 fp.close()
1146 1137 return False
1147 1138
1148 1139 if not(radarControllerHeaderObj.read(fp)):
1149 1140 fp.close()
1150 1141 return False
1151 1142
1152 1143 if not(processingHeaderObj.read(fp)):
1153 1144 fp.close()
1154 1145 return False
1155 1146
1156 1147 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
1157 1148 else:
1158 1149 msg = "[Reading] Skipping the file %s due to it hasn't enough data" % filename
1159 1150
1160 1151 fp.close()
1161 1152
1162 1153 fileSize = os.path.getsize(filename)
1163 1154 currentSize = fileSize - currentPosition
1164 1155
1165 1156 if currentSize < neededSize:
1166 1157 if msgFlag and (msg != None):
1167 1158 print msg
1168 1159 return False
1169 1160
1170 1161 return True
1171 1162
1172 1163 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1173 1164
1174 1165 path_empty = True
1175 1166
1176 1167 dateList = []
1177 1168 pathList = []
1178 1169
1179 1170 multi_path = path.split(',')
1180 1171
1181 1172 if not walk:
1182 1173
1183 1174 for single_path in multi_path:
1184 1175
1185 1176 if not os.path.isdir(single_path):
1186 1177 continue
1187 1178
1188 1179 fileList = glob.glob1(single_path, "*" + ext)
1189 1180
1190 1181 if not fileList:
1191 1182 continue
1192 1183
1193 1184 path_empty = False
1194 1185
1195 1186 fileList.sort()
1196 1187
1197 1188 for thisFile in fileList:
1198 1189
1199 1190 if not os.path.isfile(os.path.join(single_path, thisFile)):
1200 1191 continue
1201 1192
1202 1193 if not isRadarFile(thisFile):
1203 1194 continue
1204 1195
1205 1196 if not isFileInDateRange(thisFile, startDate, endDate):
1206 1197 continue
1207 1198
1208 1199 thisDate = getDateFromRadarFile(thisFile)
1209 1200
1210 1201 if thisDate in dateList:
1211 1202 continue
1212 1203
1213 1204 dateList.append(thisDate)
1214 1205 pathList.append(single_path)
1215 1206
1216 1207 else:
1217 1208 for single_path in multi_path:
1218 1209
1219 1210 if not os.path.isdir(single_path):
1220 1211 continue
1221 1212
1222 1213 dirList = []
1223 1214
1224 1215 for thisPath in os.listdir(single_path):
1225 1216
1226 1217 if not os.path.isdir(os.path.join(single_path, thisPath)):
1227 1218 continue
1228 1219
1229 1220 if not isRadarFolder(thisPath):
1230 1221 continue
1231 1222
1232 1223 if not isFolderInDateRange(thisPath, startDate, endDate):
1233 1224 continue
1234 1225
1235 1226 dirList.append(thisPath)
1236 1227
1237 1228 if not dirList:
1238 1229 continue
1239 1230
1240 1231 dirList.sort()
1241 1232
1242 1233 for thisDir in dirList:
1243 1234
1244 1235 datapath = os.path.join(single_path, thisDir, expLabel)
1245 1236 fileList = glob.glob1(datapath, "*" + ext)
1246 1237
1247 1238 if not fileList:
1248 1239 continue
1249 1240
1250 1241 path_empty = False
1251 1242
1252 1243 thisDate = getDateFromRadarFolder(thisDir)
1253 1244
1254 1245 pathList.append(datapath)
1255 1246 dateList.append(thisDate)
1256 1247
1257 1248 dateList.sort()
1258 1249
1259 1250 if walk:
1260 1251 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1261 1252 else:
1262 1253 pattern_path = multi_path[0]
1263 1254
1264 1255 if path_empty:
1265 1256 print "[Reading] No *%s files in %s for %s to %s" % (ext, pattern_path, startDate, endDate)
1266 1257 else:
1267 1258 if not dateList:
1268 1259 print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" % (startDate, endDate, ext, path)
1269 1260
1270 1261 if include_path:
1271 1262 return dateList, pathList
1272 1263
1273 1264 return dateList
1274 1265
1275 1266 def setup(self,
1276 1267 path=None,
1277 1268 startDate=None,
1278 1269 endDate=None,
1279 1270 startTime=datetime.time(0, 0, 0),
1280 1271 endTime=datetime.time(23, 59, 59),
1281 1272 set=None,
1282 1273 expLabel="",
1283 1274 ext=None,
1284 1275 online=False,
1285 1276 delay=60,
1286 1277 walk=True,
1287 1278 getblock=False,
1288 1279 nTxs=1,
1289 1280 realtime=False,
1290 1281 blocksize=None,
1291 1282 blocktime=None,
1292 1283 skip=None,
1293 1284 cursor=None,
1294 1285 warnings=True,
1295 1286 verbose=True,
1296 1287 server=None,
1297 1288 format=None,
1298 1289 oneDDict=None,
1299 1290 twoDDict=None,
1300 1291 ind2DList=None):
1301 1292 if server is not None:
1302 1293 if 'tcp://' in server:
1303 1294 address = server
1304 1295 else:
1305 1296 address = 'ipc:///tmp/%s' % server
1306 1297 self.server = address
1307 1298 self.context = zmq.Context()
1308 1299 self.receiver = self.context.socket(zmq.PULL)
1309 1300 self.receiver.connect(self.server)
1310 1301 time.sleep(0.5)
1311 1302 print '[Starting] ReceiverData from {}'.format(self.server)
1312 1303 else:
1313 1304 self.server = None
1314 1305 if path == None:
1315 1306 raise ValueError, "[Reading] The path is not valid"
1316 1307
1317 1308 if ext == None:
1318 1309 ext = self.ext
1319 1310
1320 1311 if online:
1321 1312 print "[Reading] Searching files in online mode..."
1322 1313
1323 1314 for nTries in range(self.nTries):
1324 1315 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(
1325 1316 path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1326 1317
1327 1318 if fullpath:
1328 1319 break
1329 1320
1330 1321 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries + 1)
1331 1322 sleep(self.delay)
1332 1323
1333 1324 if not(fullpath):
1334 1325 print "[Reading] There 'isn't any valid file in %s" % path
1335 1326 return
1336 1327
1337 1328 self.year = year
1338 1329 self.doy = doy
1339 1330 self.set = set - 1
1340 1331 self.path = path
1341 1332 self.foldercounter = foldercounter
1342 1333 last_set = None
1343 1334 else:
1344 1335 print "[Reading] Searching files in offline mode ..."
1345 1336 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1346 1337 startTime=startTime, endTime=endTime,
1347 1338 set=set, expLabel=expLabel, ext=ext,
1348 1339 walk=walk, cursor=cursor,
1349 1340 skip=skip)
1350 1341
1351 1342 if not(pathList):
1352 1343 self.fileIndex = -1
1353 1344 self.pathList = []
1354 1345 self.filenameList = []
1355 1346 return
1356 1347
1357 1348 self.fileIndex = -1
1358 1349 self.pathList = pathList
1359 1350 self.filenameList = filenameList
1360 1351 file_name = os.path.basename(filenameList[-1])
1361 1352 basename, ext = os.path.splitext(file_name)
1362 1353 last_set = int(basename[-3:])
1363 1354
1364 1355 self.online = online
1365 1356 self.realtime = realtime
1366 1357 self.delay = delay
1367 1358 ext = ext.lower()
1368 1359 self.ext = ext
1369 1360 self.getByBlock = getblock
1370 1361 self.nTxs = nTxs
1371 1362 self.startTime = startTime
1372 1363 self.endTime = endTime
1373 1364 self.endDate = endDate
1374 1365 self.startDate = startDate
1375 1366 # Added-----------------
1376 1367 self.selBlocksize = blocksize
1377 1368 self.selBlocktime = blocktime
1378 1369
1379 1370 # Verbose-----------
1380 1371 self.verbose = verbose
1381 1372 self.warnings = warnings
1382 1373
1383 1374 if not(self.setNextFile()):
1384 1375 if (startDate != None) and (endDate != None):
1385 1376 print "[Reading] No files in range: %s - %s" % (datetime.datetime.combine(startDate, startTime).ctime(), datetime.datetime.combine(endDate, endTime).ctime())
1386 1377 elif startDate != None:
1387 1378 print "[Reading] No files in range: %s" % (datetime.datetime.combine(startDate, startTime).ctime())
1388 1379 else:
1389 1380 print "[Reading] No files"
1390 1381
1391 1382 self.fileIndex = -1
1392 1383 self.pathList = []
1393 1384 self.filenameList = []
1394 1385 return
1395 1386
1396 1387 # self.getBasicHeader()
1397 1388
1398 1389 if last_set != None:
1399 1390 self.dataOut.last_block = last_set * \
1400 1391 self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1401 1392 return
1402 1393
1403 1394 def getBasicHeader(self):
1404 1395
1405 1396 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond / \
1406 1397 1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1407 1398
1408 1399 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1409 1400
1410 1401 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1411 1402
1412 1403 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1413 1404
1414 1405 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1415 1406
1416 1407 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1417 1408
1418 1409 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
1419 1410
1420 1411 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1421 1412
1422 1413 def getFirstHeader(self):
1423 1414
1424 1415 raise NotImplementedError
1425 1416
1426 1417 def getData(self):
1427 1418
1428 1419 raise NotImplementedError
1429 1420
1430 1421 def hasNotDataInBuffer(self):
1431 1422
1432 1423 raise NotImplementedError
1433 1424
1434 1425 def readBlock(self):
1435 1426
1436 1427 raise NotImplementedError
1437 1428
1438 1429 def isEndProcess(self):
1439 1430
1440 1431 return self.flagNoMoreFiles
1441 1432
1442 1433 def printReadBlocks(self):
1443 1434
1444 1435 print "[Reading] Number of read blocks per file %04d" % self.nReadBlocks
1445 1436
1446 1437 def printTotalBlocks(self):
1447 1438
1448 1439 print "[Reading] Number of read blocks %04d" % self.nTotalBlocks
1449 1440
1450 1441 def printNumberOfBlock(self):
1451 1442 'SPAM!'
1452 1443
1453 1444 # if self.flagIsNewBlock:
1454 1445 # print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1455 1446 # self.processingHeaderObj.dataBlocksPerFile,
1456 1447 # self.dataOut.datatime.ctime())
1457 1448
1458 1449 def printInfo(self):
1459 1450
1460 1451 if self.__printInfo == False:
1461 1452 return
1462 1453
1463 1454 self.basicHeaderObj.printInfo()
1464 1455 self.systemHeaderObj.printInfo()
1465 1456 self.radarControllerHeaderObj.printInfo()
1466 1457 self.processingHeaderObj.printInfo()
1467 1458
1468 1459 self.__printInfo = False
1469 1460
1470 1461 def run(self,
1471 1462 path=None,
1472 1463 startDate=None,
1473 1464 endDate=None,
1474 1465 startTime=datetime.time(0, 0, 0),
1475 1466 endTime=datetime.time(23, 59, 59),
1476 1467 set=None,
1477 1468 expLabel="",
1478 1469 ext=None,
1479 1470 online=False,
1480 1471 delay=60,
1481 1472 walk=True,
1482 1473 getblock=False,
1483 1474 nTxs=1,
1484 1475 realtime=False,
1485 1476 blocksize=None,
1486 1477 blocktime=None,
1487 1478 skip=None,
1488 1479 cursor=None,
1489 1480 warnings=True,
1490 1481 server=None,
1491 1482 verbose=True,
1492 1483 format=None,
1493 1484 oneDDict=None,
1494 1485 twoDDict=None,
1495 1486 ind2DList=None, **kwargs):
1496 1487
1497 1488 if not(self.isConfig):
1498 1489 self.setup(path=path,
1499 1490 startDate=startDate,
1500 1491 endDate=endDate,
1501 1492 startTime=startTime,
1502 1493 endTime=endTime,
1503 1494 set=set,
1504 1495 expLabel=expLabel,
1505 1496 ext=ext,
1506 1497 online=online,
1507 1498 delay=delay,
1508 1499 walk=walk,
1509 1500 getblock=getblock,
1510 1501 nTxs=nTxs,
1511 1502 realtime=realtime,
1512 1503 blocksize=blocksize,
1513 1504 blocktime=blocktime,
1514 1505 skip=skip,
1515 1506 cursor=cursor,
1516 1507 warnings=warnings,
1517 1508 server=server,
1518 1509 verbose=verbose,
1519 1510 format=format,
1520 1511 oneDDict=oneDDict,
1521 1512 twoDDict=twoDDict,
1522 1513 ind2DList=ind2DList)
1523 1514 self.isConfig = True
1524 1515 if server is None:
1525 1516 self.getData()
1526 1517 else:
1527 1518 self.getFromServer()
1528 1519
1529 1520
1530 1521 class JRODataWriter(JRODataIO):
1531 1522
1532 1523 """
1533 1524 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1534 1525 de los datos siempre se realiza por bloques.
1535 1526 """
1536 1527
1537 1528 blockIndex = 0
1538 1529
1539 1530 path = None
1540 1531
1541 1532 setFile = None
1542 1533
1543 1534 profilesPerBlock = None
1544 1535
1545 1536 blocksPerFile = None
1546 1537
1547 1538 nWriteBlocks = 0
1548 1539
1549 1540 fileDate = None
1550 1541
1551 1542 def __init__(self, dataOut=None):
1552 1543 raise NotImplementedError
1553 1544
1554 1545 def hasAllDataInBuffer(self):
1555 1546 raise NotImplementedError
1556 1547
1557 1548 def setBlockDimension(self):
1558 1549 raise NotImplementedError
1559 1550
1560 1551 def writeBlock(self):
1561 1552 raise NotImplementedError
1562 1553
1563 1554 def putData(self):
1564 1555 raise NotImplementedError
1565 1556
1566 1557 def getProcessFlags(self):
1567 1558
1568 1559 processFlags = 0
1569 1560
1570 1561 dtype_index = get_dtype_index(self.dtype)
1571 1562 procflag_dtype = get_procflag_dtype(dtype_index)
1572 1563
1573 1564 processFlags += procflag_dtype
1574 1565
1575 1566 if self.dataOut.flagDecodeData:
1576 1567 processFlags += PROCFLAG.DECODE_DATA
1577 1568
1578 1569 if self.dataOut.flagDeflipData:
1579 1570 processFlags += PROCFLAG.DEFLIP_DATA
1580 1571
1581 1572 if self.dataOut.code is not None:
1582 1573 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1583 1574
1584 1575 if self.dataOut.nCohInt > 1:
1585 1576 processFlags += PROCFLAG.COHERENT_INTEGRATION
1586 1577
1587 1578 if self.dataOut.type == "Spectra":
1588 1579 if self.dataOut.nIncohInt > 1:
1589 1580 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1590 1581
1591 1582 if self.dataOut.data_dc is not None:
1592 1583 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1593 1584
1594 1585 if self.dataOut.flagShiftFFT:
1595 1586 processFlags += PROCFLAG.SHIFT_FFT_DATA
1596 1587
1597 1588 return processFlags
1598 1589
1599 1590 def setBasicHeader(self):
1600 1591
1601 1592 self.basicHeaderObj.size = self.basicHeaderSize # bytes
1602 1593 self.basicHeaderObj.version = self.versionFile
1603 1594 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1604 1595
1605 1596 utc = numpy.floor(self.dataOut.utctime)
1606 1597 milisecond = (self.dataOut.utctime - utc) * 1000.0
1607 1598
1608 1599 self.basicHeaderObj.utc = utc
1609 1600 self.basicHeaderObj.miliSecond = milisecond
1610 1601 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1611 1602 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1612 1603 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1613 1604
1614 1605 def setFirstHeader(self):
1615 1606 """
1616 1607 Obtiene una copia del First Header
1617 1608
1618 1609 Affected:
1619 1610
1620 1611 self.basicHeaderObj
1621 1612 self.systemHeaderObj
1622 1613 self.radarControllerHeaderObj
1623 1614 self.processingHeaderObj self.
1624 1615
1625 1616 Return:
1626 1617 None
1627 1618 """
1628 1619
1629 1620 raise NotImplementedError
1630 1621
1631 1622 def __writeFirstHeader(self):
1632 1623 """
1633 1624 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1634 1625
1635 1626 Affected:
1636 1627 __dataType
1637 1628
1638 1629 Return:
1639 1630 None
1640 1631 """
1641 1632
1642 1633 # CALCULAR PARAMETROS
1643 1634
1644 1635 sizeLongHeader = self.systemHeaderObj.size + \
1645 1636 self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1646 1637 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1647 1638
1648 1639 self.basicHeaderObj.write(self.fp)
1649 1640 self.systemHeaderObj.write(self.fp)
1650 1641 self.radarControllerHeaderObj.write(self.fp)
1651 1642 self.processingHeaderObj.write(self.fp)
1652 1643
1653 1644 def __setNewBlock(self):
1654 1645 """
1655 1646 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1656 1647
1657 1648 Return:
1658 1649 0 : si no pudo escribir nada
1659 1650 1 : Si escribio el Basic el First Header
1660 1651 """
1661 1652 if self.fp == None:
1662 1653 self.setNextFile()
1663 1654
1664 1655 if self.flagIsNewFile:
1665 1656 return 1
1666 1657
1667 1658 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1668 1659 self.basicHeaderObj.write(self.fp)
1669 1660 return 1
1670 1661
1671 1662 if not(self.setNextFile()):
1672 1663 return 0
1673 1664
1674 1665 return 1
1675 1666
1676 1667 def writeNextBlock(self):
1677 1668 """
1678 1669 Selecciona el bloque siguiente de datos y los escribe en un file
1679 1670
1680 1671 Return:
1681 1672 0 : Si no hizo pudo escribir el bloque de datos
1682 1673 1 : Si no pudo escribir el bloque de datos
1683 1674 """
1684 1675 if not(self.__setNewBlock()):
1685 1676 return 0
1686 1677
1687 1678 self.writeBlock()
1688 1679
1689 1680 print "[Writing] Block No. %d/%d" % (self.blockIndex,
1690 1681 self.processingHeaderObj.dataBlocksPerFile)
1691 1682
1692 1683 return 1
1693 1684
1694 1685 def setNextFile(self):
1695 1686 """
1696 1687 Determina el siguiente file que sera escrito
1697 1688
1698 1689 Affected:
1699 1690 self.filename
1700 1691 self.subfolder
1701 1692 self.fp
1702 1693 self.setFile
1703 1694 self.flagIsNewFile
1704 1695
1705 1696 Return:
1706 1697 0 : Si el archivo no puede ser escrito
1707 1698 1 : Si el archivo esta listo para ser escrito
1708 1699 """
1709 1700 ext = self.ext
1710 1701 path = self.path
1711 1702
1712 1703 if self.fp != None:
1713 1704 self.fp.close()
1714 1705
1715 1706 timeTuple = time.localtime(self.dataOut.utctime)
1716 1707 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year, timeTuple.tm_yday)
1717 1708
1718 1709 fullpath = os.path.join(path, subfolder)
1719 1710 setFile = self.setFile
1720 1711
1721 1712 if not(os.path.exists(fullpath)):
1722 1713 os.mkdir(fullpath)
1723 1714 setFile = -1 # inicializo mi contador de seteo
1724 1715 else:
1725 1716 filesList = os.listdir(fullpath)
1726 1717 if len(filesList) > 0:
1727 1718 filesList = sorted(filesList, key=str.lower)
1728 1719 filen = filesList[-1]
1729 1720 # el filename debera tener el siguiente formato
1730 1721 # 0 1234 567 89A BCDE (hex)
1731 1722 # x YYYY DDD SSS .ext
1732 1723 if isNumber(filen[8:11]):
1733 1724 # inicializo mi contador de seteo al seteo del ultimo file
1734 1725 setFile = int(filen[8:11])
1735 1726 else:
1736 1727 setFile = -1
1737 1728 else:
1738 1729 setFile = -1 # inicializo mi contador de seteo
1739 1730
1740 1731 setFile += 1
1741 1732
1742 1733 # If this is a new day it resets some values
1743 1734 if self.dataOut.datatime.date() > self.fileDate:
1744 1735 setFile = 0
1745 1736 self.nTotalBlocks = 0
1746 1737
1747 filen = '%s%4.4d%3.3d%3.3d%s' % (
1738 filen = '{}{:04d}{:03d}{:03d}{}'.format(
1748 1739 self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext)
1749 1740
1750 1741 filename = os.path.join(path, subfolder, filen)
1751 1742
1752 1743 fp = open(filename, 'wb')
1753 1744
1754 1745 self.blockIndex = 0
1755 1746
1756 1747 # guardando atributos
1757 1748 self.filename = filename
1758 1749 self.subfolder = subfolder
1759 1750 self.fp = fp
1760 1751 self.setFile = setFile
1761 1752 self.flagIsNewFile = 1
1762 1753 self.fileDate = self.dataOut.datatime.date()
1763 1754
1764 1755 self.setFirstHeader()
1765 1756
1766 1757 print '[Writing] Opening file: %s' % self.filename
1767 1758
1768 1759 self.__writeFirstHeader()
1769 1760
1770 1761 return 1
1771 1762
1772 1763 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1773 1764 """
1774 1765 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1775 1766
1776 1767 Inputs:
1777 1768 path : directory where data will be saved
1778 1769 profilesPerBlock : number of profiles per block
1779 1770 set : initial file set
1780 1771 datatype : An integer number that defines data type:
1781 1772 0 : int8 (1 byte)
1782 1773 1 : int16 (2 bytes)
1783 1774 2 : int32 (4 bytes)
1784 1775 3 : int64 (8 bytes)
1785 1776 4 : float32 (4 bytes)
1786 1777 5 : double64 (8 bytes)
1787 1778
1788 1779 Return:
1789 1780 0 : Si no realizo un buen seteo
1790 1781 1 : Si realizo un buen seteo
1791 1782 """
1792 1783
1793 1784 if ext == None:
1794 1785 ext = self.ext
1795 1786
1796 1787 self.ext = ext.lower()
1797 1788
1798 1789 self.path = path
1799 1790
1800 1791 if set is None:
1801 1792 self.setFile = -1
1802 1793 else:
1803 1794 self.setFile = set - 1
1804 1795
1805 1796 self.blocksPerFile = blocksPerFile
1806 1797
1807 1798 self.profilesPerBlock = profilesPerBlock
1808 1799
1809 1800 self.dataOut = dataOut
1810 1801 self.fileDate = self.dataOut.datatime.date()
1811 1802 # By default
1812 1803 self.dtype = self.dataOut.dtype
1813 1804
1814 1805 if datatype is not None:
1815 1806 self.dtype = get_numpy_dtype(datatype)
1816 1807
1817 1808 if not(self.setNextFile()):
1818 1809 print "[Writing] There isn't a next file"
1819 1810 return 0
1820 1811
1821 1812 self.setBlockDimension()
1822 1813
1823 1814 return 1
1824 1815
1825 1816 def run(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1826 1817
1827 1818 if not(self.isConfig):
1828 1819
1829 1820 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock,
1830 1821 set=set, ext=ext, datatype=datatype, **kwargs)
1831 1822 self.isConfig = True
1832 1823
1833 1824 self.putData()
@@ -1,69 +1,69
1 1 '''
2 2 Created on Jul 16, 2014
3 3
4 4 @author: Miguel Urco
5 5 '''
6 6
7 7 import os
8 8 from setuptools import setup, Extension
9 9 from setuptools.command.build_ext import build_ext as _build_ext
10 10 from schainpy import __version__
11 11
12 12 class build_ext(_build_ext):
13 13 def finalize_options(self):
14 14 _build_ext.finalize_options(self)
15 15 # Prevent numpy from thinking it is still in its setup process:
16 16 __builtins__.__NUMPY_SETUP__ = False
17 17 import numpy
18 18 self.include_dirs.append(numpy.get_include())
19 19
20 20 setup(name="schainpy",
21 21 version=__version__,
22 22 description="Python tools to read, write and process Jicamarca data",
23 23 author="Miguel Urco",
24 24 author_email="miguel.urco@jro.igp.gob.pe",
25 25 url="http://jro.igp.gob.pe",
26 26 packages={'schainpy',
27 27 'schainpy.model',
28 28 'schainpy.model.data',
29 29 'schainpy.model.graphics',
30 30 'schainpy.model.io',
31 31 'schainpy.model.proc',
32 32 'schainpy.model.serializer',
33 33 'schainpy.model.utils',
34 34 'schainpy.utils',
35 35 'schainpy.gui',
36 36 'schainpy.gui.figures',
37 37 'schainpy.gui.viewcontroller',
38 38 'schainpy.gui.viewer',
39 39 'schainpy.gui.viewer.windows'},
40 40 ext_package='schainpy',
41 41 py_modules=[''],
42 42 package_data={'': ['schain.conf.template'],
43 43 'schainpy.gui.figures': ['*.png', '*.jpg'],
44 44 },
45 45 include_package_data=False,
46 46 scripts=['schainpy/gui/schainGUI'],
47 47 ext_modules=[
48 48 Extension("cSchain", ["schainpy/model/proc/extensions.c"]
49 49 )],
50 50 entry_points={
51 51 'console_scripts': [
52 52 'schain = schaincli.cli:main',
53 53 ],
54 54 },
55 55 cmdclass={'build_ext': build_ext},
56 56 setup_requires=["numpy >= 1.11.2"],
57 57 install_requires=[
58 58 "scipy >= 0.14.0",
59 59 "h5py >= 2.2.1",
60 "matplotlib >= 1.4.2",
60 "matplotlib >= 2.0.0",
61 61 "pyfits >= 3.4",
62 62 "paramiko >= 2.1.2",
63 63 "paho-mqtt >= 1.2",
64 64 "zmq",
65 65 "fuzzywuzzy",
66 66 "click",
67 67 "python-Levenshtein"
68 68 ],
69 69 )
General Comments 0
You need to be logged in to leave comments. Login now