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