##// END OF EJS Templates
fixing merge
Juan C. Espinoza -
r938:9e80eea2eb45 merge
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,1228 +1,1228
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 if hasattr(self, 'timeInterval1'):
1219 if hasattr(self, 'timeInterval1'):
1220 return self.timeInterval1
1220 return self.timeInterval1
1221 else:
1221 else:
1222 return self.paramInterval
1222 return self.paramInterval
1223
1223
1224 def getNoise(self):
1224 def getNoise(self):
1225
1225
1226 return self.spc_noise
1226 return self.spc_noise
1227
1227
1228 timeInterval = property(getTimeInterval)
1228 timeInterval = property(getTimeInterval)
@@ -1,756 +1,773
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 self.figure.show()
96 self.figure.show()
96
97
97 self.plot()
98 self.plot()
98 plt.tight_layout()
99 plt.tight_layout()
99 self.figure.canvas.manager.set_window_title('{} {} - {}'.format(self.title, self.CODE.upper(),
100 self.figure.canvas.manager.set_window_title('{} {} - {}'.format(self.title, self.CODE.upper(),
100 datetime.datetime.fromtimestamp(self.max_time).strftime('%Y/%m/%d')))
101 datetime.datetime.fromtimestamp(self.max_time).strftime('%Y/%m/%d')))
101
102
102 if self.save:
103 if self.save:
103 figname = os.path.join(self.save, '{}_{}.png'.format(self.CODE,
104 figname = os.path.join(self.save, '{}_{}.png'.format(self.CODE,
104 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
105 datetime.datetime.fromtimestamp(self.saveTime).strftime('%y%m%d_%H%M%S')))
105 print 'Saving figure: {}'.format(figname)
106 print 'Saving figure: {}'.format(figname)
106 self.figure.savefig(figname)
107 self.figure.savefig(figname)
107
108
108 self.figure.canvas.draw()
109 self.figure.canvas.draw()
109
110
110 def plot(self):
111 def plot(self):
111
112
112 print 'plotting...{}'.format(self.CODE.upper())
113 print 'plotting...{}'.format(self.CODE.upper())
113 return
114 return
114
115
115 def run(self):
116 def run(self):
116
117
117 print '[Starting] {}'.format(self.name)
118 print '[Starting] {}'.format(self.name)
118
119
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)
124
123 if 'server' in self.kwargs['parent']:
125 if 'server' in self.kwargs['parent']:
124 receiver.connect('ipc:///tmp/{}.plots'.format(self.kwargs['parent']['server']))
126 receiver.connect('ipc:///tmp/{}.plots'.format(self.kwargs['parent']['server']))
125 else:
127 else:
126 receiver.connect("ipc:///tmp/zmq.plots")
128 receiver.connect("ipc:///tmp/zmq.plots")
127
129
130 seconds_passed = 0
131
128 while True:
132 while True:
129 try:
133 try:
130 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)
134 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)#flags=zmq.NOBLOCK
135 self.started = self.data['STARTED']
131 self.dataOut = self.data['dataOut']
136 self.dataOut = self.data['dataOut']
137
138 if (len(self.times) < len(self.data['times']) and not self.started and self.data['ENDED']):
139 continue
140
132 self.times = self.data['times']
141 self.times = self.data['times']
133 self.times.sort()
142 self.times.sort()
134 self.throttle_value = self.data['throttle']
143 self.throttle_value = self.data['throttle']
135 self.min_time = self.times[0]
144 self.min_time = self.times[0]
136 self.max_time = self.times[-1]
145 self.max_time = self.times[-1]
137
146
138 if self.isConfig is False:
147 if self.isConfig is False:
148 print 'setting up'
139 self.setup()
149 self.setup()
140 self.isConfig = True
150 self.isConfig = True
141 self.__plot()
151 self.__plot()
142
152
143 if self.data['ENDED'] is True:
153 if self.data['ENDED'] is True:
154 print '********GRAPHIC ENDED********'
155 self.ended = True
144 self.isConfig = False
156 self.isConfig = False
157 self.__plot()
158 elif seconds_passed >= self.data['throttle']:
159 print 'passed', seconds_passed
160 self.__plot()
161 seconds_passed = 0
145
162
146 except zmq.Again as e:
163 except zmq.Again as e:
147 print 'Waiting for data...'
164 print 'Waiting for data...'
148 plt.pause(self.throttle_value)
165 plt.pause(2)
166 seconds_passed += 2
149
167
150 def close(self):
168 def close(self):
151 if self.dataOut:
169 if self.dataOut:
152 self.__plot()
170 self.__plot()
153
171
154
172
155 class PlotSpectraData(PlotData):
173 class PlotSpectraData(PlotData):
156
174
157 CODE = 'spc'
175 CODE = 'spc'
158 colormap = 'jro'
176 colormap = 'jro'
159 CONFLATE = False
177 CONFLATE = False
160
178
161 def setup(self):
179 def setup(self):
162
180
163 ncolspan = 1
181 ncolspan = 1
164 colspan = 1
182 colspan = 1
165 self.ncols = int(numpy.sqrt(self.dataOut.nChannels)+0.9)
183 self.ncols = int(numpy.sqrt(self.dataOut.nChannels)+0.9)
166 self.nrows = int(self.dataOut.nChannels*1./self.ncols + 0.9)
184 self.nrows = int(self.dataOut.nChannels*1./self.ncols + 0.9)
167 self.width = 3.6*self.ncols
185 self.width = 3.6*self.ncols
168 self.height = 3.2*self.nrows
186 self.height = 3.2*self.nrows
169 if self.showprofile:
187 if self.showprofile:
170 ncolspan = 3
188 ncolspan = 3
171 colspan = 2
189 colspan = 2
172 self.width += 1.2*self.ncols
190 self.width += 1.2*self.ncols
173
191
174 self.ylabel = 'Range [Km]'
192 self.ylabel = 'Range [Km]'
175 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
193 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
176
194
177 if self.figure is None:
195 if self.figure is None:
178 self.figure = plt.figure(figsize=(self.width, self.height),
196 self.figure = plt.figure(figsize=(self.width, self.height),
179 edgecolor='k',
197 edgecolor='k',
180 facecolor='w')
198 facecolor='w')
181 else:
199 else:
182 self.figure.clf()
200 self.figure.clf()
183
201
184 n = 0
202 n = 0
185 for y in range(self.nrows):
203 for y in range(self.nrows):
186 for x in range(self.ncols):
204 for x in range(self.ncols):
187 if n >= self.dataOut.nChannels:
205 if n >= self.dataOut.nChannels:
188 break
206 break
189 ax = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan), 1, colspan)
207 ax = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan), 1, colspan)
190 if self.showprofile:
208 if self.showprofile:
191 ax.ax_profile = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan+colspan), 1, 1)
209 ax.ax_profile = plt.subplot2grid((self.nrows, self.ncols*ncolspan), (y, x*ncolspan+colspan), 1, 1)
192
210
193 ax.firsttime = True
211 ax.firsttime = True
194 self.axes.append(ax)
212 self.axes.append(ax)
195 n += 1
213 n += 1
196
214
197 def plot(self):
215 def plot(self):
198
216
199 if self.xaxis == "frequency":
217 if self.xaxis == "frequency":
200 x = self.dataOut.getFreqRange(1)/1000.
218 x = self.dataOut.getFreqRange(1)/1000.
201 xlabel = "Frequency (kHz)"
219 xlabel = "Frequency (kHz)"
202 elif self.xaxis == "time":
220 elif self.xaxis == "time":
203 x = self.dataOut.getAcfRange(1)
221 x = self.dataOut.getAcfRange(1)
204 xlabel = "Time (ms)"
222 xlabel = "Time (ms)"
205 else:
223 else:
206 x = self.dataOut.getVelRange(1)
224 x = self.dataOut.getVelRange(1)
207 xlabel = "Velocity (m/s)"
225 xlabel = "Velocity (m/s)"
208
226
209 y = self.dataOut.getHeiRange()
227 y = self.dataOut.getHeiRange()
210 z = self.data[self.CODE]
228 z = self.data[self.CODE]
211
229
212 for n, ax in enumerate(self.axes):
230 for n, ax in enumerate(self.axes):
213
231
214 if ax.firsttime:
232 if ax.firsttime:
215 self.xmax = self.xmax if self.xmax else np.nanmax(x)
233 self.xmax = self.xmax if self.xmax else np.nanmax(x)
216 self.xmin = self.xmin if self.xmin else -self.xmax
234 self.xmin = self.xmin if self.xmin else -self.xmax
217 self.ymin = self.ymin if self.ymin else np.nanmin(y)
235 self.ymin = self.ymin if self.ymin else np.nanmin(y)
218 self.ymax = self.ymax if self.ymax else np.nanmax(y)
236 self.ymax = self.ymax if self.ymax else np.nanmax(y)
219 self.zmin = self.zmin if self.zmin else np.nanmin(z)
237 self.zmin = self.zmin if self.zmin else np.nanmin(z)
220 self.zmax = self.zmax if self.zmax else np.nanmax(z)
238 self.zmax = self.zmax if self.zmax else np.nanmax(z)
221 ax.plot = ax.pcolormesh(x, y, z[n].T,
239 ax.plot = ax.pcolormesh(x, y, z[n].T,
222 vmin=self.zmin,
240 vmin=self.zmin,
223 vmax=self.zmax,
241 vmax=self.zmax,
224 cmap=plt.get_cmap(self.colormap)
242 cmap=plt.get_cmap(self.colormap)
225 )
243 )
226 divider = make_axes_locatable(ax)
244 divider = make_axes_locatable(ax)
227 cax = divider.new_horizontal(size='3%', pad=0.05)
245 cax = divider.new_horizontal(size='3%', pad=0.05)
228 self.figure.add_axes(cax)
246 self.figure.add_axes(cax)
229 plt.colorbar(ax.plot, cax)
247 plt.colorbar(ax.plot, cax)
230
248
231 ax.set_xlim(self.xmin, self.xmax)
249 ax.set_xlim(self.xmin, self.xmax)
232 ax.set_ylim(self.ymin, self.ymax)
250 ax.set_ylim(self.ymin, self.ymax)
233
251
234 ax.set_ylabel(self.ylabel)
252 ax.set_ylabel(self.ylabel)
235 ax.set_xlabel(xlabel)
253 ax.set_xlabel(xlabel)
236
254
237 ax.firsttime = False
255 ax.firsttime = False
238
256
239 if self.showprofile:
257 if self.showprofile:
240 ax.plot_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
258 ax.plot_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
241 ax.ax_profile.set_xlim(self.zmin, self.zmax)
259 ax.ax_profile.set_xlim(self.zmin, self.zmax)
242 ax.ax_profile.set_ylim(self.ymin, self.ymax)
260 ax.ax_profile.set_ylim(self.ymin, self.ymax)
243 ax.ax_profile.set_xlabel('dB')
261 ax.ax_profile.set_xlabel('dB')
244 ax.ax_profile.grid(b=True, axis='x')
262 ax.ax_profile.grid(b=True, axis='x')
245 ax.plot_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
263 ax.plot_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
246 color="k", linestyle="dashed", lw=2)[0]
264 color="k", linestyle="dashed", lw=2)[0]
247 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
265 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
248 else:
266 else:
249 ax.plot.set_array(z[n].T.ravel())
267 ax.plot.set_array(z[n].T.ravel())
250 if self.showprofile:
268 if self.showprofile:
251 ax.plot_profile.set_data(self.data['rti'][self.max_time][n], y)
269 ax.plot_profile.set_data(self.data['rti'][self.max_time][n], y)
252 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
270 ax.plot_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
253
271
254 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
272 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
255 size=8)
273 size=8)
256 self.saveTime = self.max_time
274 self.saveTime = self.max_time
257
275
258
276
259 class PlotCrossSpectraData(PlotData):
277 class PlotCrossSpectraData(PlotData):
260
278
261 CODE = 'cspc'
279 CODE = 'cspc'
262 zmin_coh = None
280 zmin_coh = None
263 zmax_coh = None
281 zmax_coh = None
264 zmin_phase = None
282 zmin_phase = None
265 zmax_phase = None
283 zmax_phase = None
266 CONFLATE = False
284 CONFLATE = False
267
285
268 def setup(self):
286 def setup(self):
269
287
270 ncolspan = 1
288 ncolspan = 1
271 colspan = 1
289 colspan = 1
272 self.ncols = 2
290 self.ncols = 2
273 self.nrows = self.dataOut.nPairs
291 self.nrows = self.dataOut.nPairs
274 self.width = 3.6*self.ncols
292 self.width = 3.6*self.ncols
275 self.height = 3.2*self.nrows
293 self.height = 3.2*self.nrows
276
294
277 self.ylabel = 'Range [Km]'
295 self.ylabel = 'Range [Km]'
278 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
296 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
279
297
280 if self.figure is None:
298 if self.figure is None:
281 self.figure = plt.figure(figsize=(self.width, self.height),
299 self.figure = plt.figure(figsize=(self.width, self.height),
282 edgecolor='k',
300 edgecolor='k',
283 facecolor='w')
301 facecolor='w')
284 else:
302 else:
285 self.figure.clf()
303 self.figure.clf()
286
304
287 for y in range(self.nrows):
305 for y in range(self.nrows):
288 for x in range(self.ncols):
306 for x in range(self.ncols):
289 ax = plt.subplot2grid((self.nrows, self.ncols), (y, x), 1, 1)
307 ax = plt.subplot2grid((self.nrows, self.ncols), (y, x), 1, 1)
290 ax.firsttime = True
308 ax.firsttime = True
291 self.axes.append(ax)
309 self.axes.append(ax)
292
310
293 def plot(self):
311 def plot(self):
294
312
295 if self.xaxis == "frequency":
313 if self.xaxis == "frequency":
296 x = self.dataOut.getFreqRange(1)/1000.
314 x = self.dataOut.getFreqRange(1)/1000.
297 xlabel = "Frequency (kHz)"
315 xlabel = "Frequency (kHz)"
298 elif self.xaxis == "time":
316 elif self.xaxis == "time":
299 x = self.dataOut.getAcfRange(1)
317 x = self.dataOut.getAcfRange(1)
300 xlabel = "Time (ms)"
318 xlabel = "Time (ms)"
301 else:
319 else:
302 x = self.dataOut.getVelRange(1)
320 x = self.dataOut.getVelRange(1)
303 xlabel = "Velocity (m/s)"
321 xlabel = "Velocity (m/s)"
304
322
305 y = self.dataOut.getHeiRange()
323 y = self.dataOut.getHeiRange()
306 z_coh = self.data['cspc_coh']
324 z_coh = self.data['cspc_coh']
307 z_phase = self.data['cspc_phase']
325 z_phase = self.data['cspc_phase']
308
326
309 for n in range(self.nrows):
327 for n in range(self.nrows):
310 ax = self.axes[2*n]
328 ax = self.axes[2*n]
311 ax1 = self.axes[2*n+1]
329 ax1 = self.axes[2*n+1]
312 if ax.firsttime:
330 if ax.firsttime:
313 self.xmax = self.xmax if self.xmax else np.nanmax(x)
331 self.xmax = self.xmax if self.xmax else np.nanmax(x)
314 self.xmin = self.xmin if self.xmin else -self.xmax
332 self.xmin = self.xmin if self.xmin else -self.xmax
315 self.ymin = self.ymin if self.ymin else np.nanmin(y)
333 self.ymin = self.ymin if self.ymin else np.nanmin(y)
316 self.ymax = self.ymax if self.ymax else np.nanmax(y)
334 self.ymax = self.ymax if self.ymax else np.nanmax(y)
317 self.zmin_coh = self.zmin_coh if self.zmin_coh else 0.0
335 self.zmin_coh = self.zmin_coh if self.zmin_coh else 0.0
318 self.zmax_coh = self.zmax_coh if self.zmax_coh else 1.0
336 self.zmax_coh = self.zmax_coh if self.zmax_coh else 1.0
319 self.zmin_phase = self.zmin_phase if self.zmin_phase else -180
337 self.zmin_phase = self.zmin_phase if self.zmin_phase else -180
320 self.zmax_phase = self.zmax_phase if self.zmax_phase else 180
338 self.zmax_phase = self.zmax_phase if self.zmax_phase else 180
321
339
322 ax.plot = ax.pcolormesh(x, y, z_coh[n].T,
340 ax.plot = ax.pcolormesh(x, y, z_coh[n].T,
323 vmin=self.zmin_coh,
341 vmin=self.zmin_coh,
324 vmax=self.zmax_coh,
342 vmax=self.zmax_coh,
325 cmap=plt.get_cmap(self.colormap_coh)
343 cmap=plt.get_cmap(self.colormap_coh)
326 )
344 )
327 divider = make_axes_locatable(ax)
345 divider = make_axes_locatable(ax)
328 cax = divider.new_horizontal(size='3%', pad=0.05)
346 cax = divider.new_horizontal(size='3%', pad=0.05)
329 self.figure.add_axes(cax)
347 self.figure.add_axes(cax)
330 plt.colorbar(ax.plot, cax)
348 plt.colorbar(ax.plot, cax)
331
349
332 ax.set_xlim(self.xmin, self.xmax)
350 ax.set_xlim(self.xmin, self.xmax)
333 ax.set_ylim(self.ymin, self.ymax)
351 ax.set_ylim(self.ymin, self.ymax)
334
352
335 ax.set_ylabel(self.ylabel)
353 ax.set_ylabel(self.ylabel)
336 ax.set_xlabel(xlabel)
354 ax.set_xlabel(xlabel)
337 ax.firsttime = False
355 ax.firsttime = False
338
356
339 ax1.plot = ax1.pcolormesh(x, y, z_phase[n].T,
357 ax1.plot = ax1.pcolormesh(x, y, z_phase[n].T,
340 vmin=self.zmin_phase,
358 vmin=self.zmin_phase,
341 vmax=self.zmax_phase,
359 vmax=self.zmax_phase,
342 cmap=plt.get_cmap(self.colormap_phase)
360 cmap=plt.get_cmap(self.colormap_phase)
343 )
361 )
344 divider = make_axes_locatable(ax1)
362 divider = make_axes_locatable(ax1)
345 cax = divider.new_horizontal(size='3%', pad=0.05)
363 cax = divider.new_horizontal(size='3%', pad=0.05)
346 self.figure.add_axes(cax)
364 self.figure.add_axes(cax)
347 plt.colorbar(ax1.plot, cax)
365 plt.colorbar(ax1.plot, cax)
348
366
349 ax1.set_xlim(self.xmin, self.xmax)
367 ax1.set_xlim(self.xmin, self.xmax)
350 ax1.set_ylim(self.ymin, self.ymax)
368 ax1.set_ylim(self.ymin, self.ymax)
351
369
352 ax1.set_ylabel(self.ylabel)
370 ax1.set_ylabel(self.ylabel)
353 ax1.set_xlabel(xlabel)
371 ax1.set_xlabel(xlabel)
354 ax1.firsttime = False
372 ax1.firsttime = False
355 else:
373 else:
356 ax.plot.set_array(z_coh[n].T.ravel())
374 ax.plot.set_array(z_coh[n].T.ravel())
357 ax1.plot.set_array(z_phase[n].T.ravel())
375 ax1.plot.set_array(z_phase[n].T.ravel())
358
376
359 ax.set_title('Coherence Ch{} * Ch{}'.format(self.dataOut.pairsList[n][0], self.dataOut.pairsList[n][1]), size=8)
377 ax.set_title('Coherence Ch{} * Ch{}'.format(self.dataOut.pairsList[n][0], self.dataOut.pairsList[n][1]), size=8)
360 ax1.set_title('Phase Ch{} * Ch{}'.format(self.dataOut.pairsList[n][0], self.dataOut.pairsList[n][1]), size=8)
378 ax1.set_title('Phase Ch{} * Ch{}'.format(self.dataOut.pairsList[n][0], self.dataOut.pairsList[n][1]), size=8)
361 self.saveTime = self.max_time
379 self.saveTime = self.max_time
362
380
363
381
364 class PlotSpectraMeanData(PlotSpectraData):
382 class PlotSpectraMeanData(PlotSpectraData):
365
383
366 CODE = 'spc_mean'
384 CODE = 'spc_mean'
367 colormap = 'jet'
385 colormap = 'jet'
368
386
369 def plot(self):
387 def plot(self):
370
388
371 if self.xaxis == "frequency":
389 if self.xaxis == "frequency":
372 x = self.dataOut.getFreqRange(1)/1000.
390 x = self.dataOut.getFreqRange(1)/1000.
373 xlabel = "Frequency (kHz)"
391 xlabel = "Frequency (kHz)"
374 elif self.xaxis == "time":
392 elif self.xaxis == "time":
375 x = self.dataOut.getAcfRange(1)
393 x = self.dataOut.getAcfRange(1)
376 xlabel = "Time (ms)"
394 xlabel = "Time (ms)"
377 else:
395 else:
378 x = self.dataOut.getVelRange(1)
396 x = self.dataOut.getVelRange(1)
379 xlabel = "Velocity (m/s)"
397 xlabel = "Velocity (m/s)"
380
398
381 y = self.dataOut.getHeiRange()
399 y = self.dataOut.getHeiRange()
382 z = self.data['spc']
400 z = self.data['spc']
383 mean = self.data['mean'][self.max_time]
401 mean = self.data['mean'][self.max_time]
384
402
385 for n, ax in enumerate(self.axes):
403 for n, ax in enumerate(self.axes):
386
404
387 if ax.firsttime:
405 if ax.firsttime:
388 self.xmax = self.xmax if self.xmax else np.nanmax(x)
406 self.xmax = self.xmax if self.xmax else np.nanmax(x)
389 self.xmin = self.xmin if self.xmin else -self.xmax
407 self.xmin = self.xmin if self.xmin else -self.xmax
390 self.ymin = self.ymin if self.ymin else np.nanmin(y)
408 self.ymin = self.ymin if self.ymin else np.nanmin(y)
391 self.ymax = self.ymax if self.ymax else np.nanmax(y)
409 self.ymax = self.ymax if self.ymax else np.nanmax(y)
392 self.zmin = self.zmin if self.zmin else np.nanmin(z)
410 self.zmin = self.zmin if self.zmin else np.nanmin(z)
393 self.zmax = self.zmax if self.zmax else np.nanmax(z)
411 self.zmax = self.zmax if self.zmax else np.nanmax(z)
394 ax.plt = ax.pcolormesh(x, y, z[n].T,
412 ax.plt = ax.pcolormesh(x, y, z[n].T,
395 vmin=self.zmin,
413 vmin=self.zmin,
396 vmax=self.zmax,
414 vmax=self.zmax,
397 cmap=plt.get_cmap(self.colormap)
415 cmap=plt.get_cmap(self.colormap)
398 )
416 )
399 ax.plt_dop = ax.plot(mean[n], y,
417 ax.plt_dop = ax.plot(mean[n], y,
400 color='k')[0]
418 color='k')[0]
401
419
402 divider = make_axes_locatable(ax)
420 divider = make_axes_locatable(ax)
403 cax = divider.new_horizontal(size='3%', pad=0.05)
421 cax = divider.new_horizontal(size='3%', pad=0.05)
404 self.figure.add_axes(cax)
422 self.figure.add_axes(cax)
405 plt.colorbar(ax.plt, cax)
423 plt.colorbar(ax.plt, cax)
406
424
407 ax.set_xlim(self.xmin, self.xmax)
425 ax.set_xlim(self.xmin, self.xmax)
408 ax.set_ylim(self.ymin, self.ymax)
426 ax.set_ylim(self.ymin, self.ymax)
409
427
410 ax.set_ylabel(self.ylabel)
428 ax.set_ylabel(self.ylabel)
411 ax.set_xlabel(xlabel)
429 ax.set_xlabel(xlabel)
412
430
413 ax.firsttime = False
431 ax.firsttime = False
414
432
415 if self.showprofile:
433 if self.showprofile:
416 ax.plt_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
434 ax.plt_profile= ax.ax_profile.plot(self.data['rti'][self.max_time][n], y)[0]
417 ax.ax_profile.set_xlim(self.zmin, self.zmax)
435 ax.ax_profile.set_xlim(self.zmin, self.zmax)
418 ax.ax_profile.set_ylim(self.ymin, self.ymax)
436 ax.ax_profile.set_ylim(self.ymin, self.ymax)
419 ax.ax_profile.set_xlabel('dB')
437 ax.ax_profile.set_xlabel('dB')
420 ax.ax_profile.grid(b=True, axis='x')
438 ax.ax_profile.grid(b=True, axis='x')
421 ax.plt_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
439 ax.plt_noise = ax.ax_profile.plot(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y,
422 color="k", linestyle="dashed", lw=2)[0]
440 color="k", linestyle="dashed", lw=2)[0]
423 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
441 [tick.set_visible(False) for tick in ax.ax_profile.get_yticklabels()]
424 else:
442 else:
425 ax.plt.set_array(z[n].T.ravel())
443 ax.plt.set_array(z[n].T.ravel())
426 ax.plt_dop.set_data(mean[n], y)
444 ax.plt_dop.set_data(mean[n], y)
427 if self.showprofile:
445 if self.showprofile:
428 ax.plt_profile.set_data(self.data['rti'][self.max_time][n], y)
446 ax.plt_profile.set_data(self.data['rti'][self.max_time][n], y)
429 ax.plt_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
447 ax.plt_noise.set_data(numpy.repeat(self.data['noise'][self.max_time][n], len(y)), y)
430
448
431 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
449 ax.set_title('{} - Noise: {:.2f} dB'.format(self.titles[n], self.data['noise'][self.max_time][n]),
432 size=8)
450 size=8)
433 self.saveTime = self.max_time
451 self.saveTime = self.max_time
434
452
435
453
436 class PlotRTIData(PlotData):
454 class PlotRTIData(PlotData):
437
455
438 CODE = 'rti'
456 CODE = 'rti'
439 colormap = 'jro'
457 colormap = 'jro'
440
458
441 def setup(self):
459 def setup(self):
442 self.ncols = 1
460 self.ncols = 1
443 self.nrows = self.dataOut.nChannels
461 self.nrows = self.dataOut.nChannels
444 self.width = 10
462 self.width = 10
445 self.height = 2.2*self.nrows if self.nrows<6 else 12
463 self.height = 2.2*self.nrows if self.nrows<6 else 12
446 if self.nrows==1:
464 if self.nrows==1:
447 self.height += 1
465 self.height += 1
448 self.ylabel = 'Range [Km]'
466 self.ylabel = 'Range [Km]'
449 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
467 self.titles = ['Channel {}'.format(x) for x in self.dataOut.channelList]
450
468
451 if self.figure is None:
469 if self.figure is None:
452 self.figure = plt.figure(figsize=(self.width, self.height),
470 self.figure = plt.figure(figsize=(self.width, self.height),
453 edgecolor='k',
471 edgecolor='k',
454 facecolor='w')
472 facecolor='w')
455 else:
473 else:
456 self.figure.clf()
474 self.figure.clf()
457 self.axes = []
475 self.axes = []
458
476
459 for n in range(self.nrows):
477 for n in range(self.nrows):
460 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
478 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
461 ax.firsttime = True
479 ax.firsttime = True
462 self.axes.append(ax)
480 self.axes.append(ax)
463
481
464 def plot(self):
482 def plot(self):
465
483
466 self.x = np.array(self.times)
484 self.x = np.array(self.times)
467 self.y = self.dataOut.getHeiRange()
485 self.y = self.dataOut.getHeiRange()
468 self.z = []
486 self.z = []
469
487
470 for ch in range(self.nrows):
488 for ch in range(self.nrows):
471 self.z.append([self.data[self.CODE][t][ch] for t in self.times])
489 self.z.append([self.data[self.CODE][t][ch] for t in self.times])
472
490
473 self.z = np.array(self.z)
491 self.z = np.array(self.z)
474 for n, ax in enumerate(self.axes):
492 for n, ax in enumerate(self.axes):
475
476 x, y, z = self.fill_gaps(*self.decimate())
493 x, y, z = self.fill_gaps(*self.decimate())
477 xmin = self.min_time
494 xmin = self.min_time
478 xmax = xmin+self.xrange*60*60
495 xmax = xmin+self.xrange*60*60
496 self.zmin = self.zmin if self.zmin else np.min(self.z)
497 self.zmax = self.zmax if self.zmax else np.max(self.z)
479 if ax.firsttime:
498 if ax.firsttime:
480 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
499 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
481 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
500 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
482 self.zmin = self.zmin if self.zmin else np.nanmin(self.z)
483 self.zmax = self.zmax if self.zmax else np.nanmax(self.z)
484 plot = ax.pcolormesh(x, y, z[n].T,
501 plot = ax.pcolormesh(x, y, z[n].T,
485 vmin=self.zmin,
502 vmin=self.zmin,
486 vmax=self.zmax,
503 vmax=self.zmax,
487 cmap=plt.get_cmap(self.colormap)
504 cmap=plt.get_cmap(self.colormap)
488 )
505 )
489 divider = make_axes_locatable(ax)
506 divider = make_axes_locatable(ax)
490 cax = divider.new_horizontal(size='2%', pad=0.05)
507 cax = divider.new_horizontal(size='2%', pad=0.05)
491 self.figure.add_axes(cax)
508 self.figure.add_axes(cax)
492 plt.colorbar(plot, cax)
509 plt.colorbar(plot, cax)
493 ax.set_ylim(self.ymin, self.ymax)
510 ax.set_ylim(self.ymin, self.ymax)
494
511
495 ax.xaxis.set_major_formatter(FuncFormatter(func))
512 ax.xaxis.set_major_formatter(FuncFormatter(func))
496 ax.xaxis.set_major_locator(LinearLocator(6))
513 ax.xaxis.set_major_locator(LinearLocator(6))
497
514
498 ax.set_ylabel(self.ylabel)
515 ax.set_ylabel(self.ylabel)
499
516
500 # if self.xmin is None:
517 # if self.xmin is None:
501 # xmin = self.min_time
518 # xmin = self.min_time
502 # else:
519 # else:
503 # xmin = (datetime.datetime.combine(self.dataOut.datatime.date(),
520 # xmin = (datetime.datetime.combine(self.dataOut.datatime.date(),
504 # datetime.time(self.xmin, 0, 0))-d1970).total_seconds()
521 # datetime.time(self.xmin, 0, 0))-d1970).total_seconds()
505
522
506 ax.set_xlim(xmin, xmax)
523 ax.set_xlim(xmin, xmax)
507 ax.firsttime = False
524 ax.firsttime = False
508 else:
525 else:
509 ax.collections.remove(ax.collections[0])
526 ax.collections.remove(ax.collections[0])
510 ax.set_xlim(xmin, xmax)
527 ax.set_xlim(xmin, xmax)
511 plot = ax.pcolormesh(x, y, z[n].T,
528 plot = ax.pcolormesh(x, y, z[n].T,
512 vmin=self.zmin,
529 vmin=self.zmin,
513 vmax=self.zmax,
530 vmax=self.zmax,
514 cmap=plt.get_cmap(self.colormap)
531 cmap=plt.get_cmap(self.colormap)
515 )
532 )
516 ax.set_title('{} {}'.format(self.titles[n],
533 ax.set_title('{} {}'.format(self.titles[n],
517 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
534 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
518 size=8)
535 size=8)
519
536
520 self.saveTime = self.min_time
537 self.saveTime = self.min_time
521
538
522
539
523 class PlotCOHData(PlotRTIData):
540 class PlotCOHData(PlotRTIData):
524
541
525 CODE = 'coh'
542 CODE = 'coh'
526
543
527 def setup(self):
544 def setup(self):
528
545
529 self.ncols = 1
546 self.ncols = 1
530 self.nrows = self.dataOut.nPairs
547 self.nrows = self.dataOut.nPairs
531 self.width = 10
548 self.width = 10
532 self.height = 2.2*self.nrows if self.nrows<6 else 12
549 self.height = 2.2*self.nrows if self.nrows<6 else 12
533 if self.nrows==1:
550 if self.nrows==1:
534 self.height += 1
551 self.height += 1
535 self.ylabel = 'Range [Km]'
552 self.ylabel = 'Range [Km]'
536 self.titles = ['{} Ch{} * Ch{}'.format(self.CODE.upper(), x[0], x[1]) for x in self.dataOut.pairsList]
553 self.titles = ['{} Ch{} * Ch{}'.format(self.CODE.upper(), x[0], x[1]) for x in self.dataOut.pairsList]
537
554
538 if self.figure is None:
555 if self.figure is None:
539 self.figure = plt.figure(figsize=(self.width, self.height),
556 self.figure = plt.figure(figsize=(self.width, self.height),
540 edgecolor='k',
557 edgecolor='k',
541 facecolor='w')
558 facecolor='w')
542 else:
559 else:
543 self.figure.clf()
560 self.figure.clf()
544 self.axes = []
561 self.axes = []
545
562
546 for n in range(self.nrows):
563 for n in range(self.nrows):
547 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
564 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
548 ax.firsttime = True
565 ax.firsttime = True
549 self.axes.append(ax)
566 self.axes.append(ax)
550
567
551
568
552 class PlotNoiseData(PlotData):
569 class PlotNoiseData(PlotData):
553 CODE = 'noise'
570 CODE = 'noise'
554
571
555 def setup(self):
572 def setup(self):
556
573
557 self.ncols = 1
574 self.ncols = 1
558 self.nrows = 1
575 self.nrows = 1
559 self.width = 10
576 self.width = 10
560 self.height = 3.2
577 self.height = 3.2
561 self.ylabel = 'Intensity [dB]'
578 self.ylabel = 'Intensity [dB]'
562 self.titles = ['Noise']
579 self.titles = ['Noise']
563
580
564 if self.figure is None:
581 if self.figure is None:
565 self.figure = plt.figure(figsize=(self.width, self.height),
582 self.figure = plt.figure(figsize=(self.width, self.height),
566 edgecolor='k',
583 edgecolor='k',
567 facecolor='w')
584 facecolor='w')
568 else:
585 else:
569 self.figure.clf()
586 self.figure.clf()
570 self.axes = []
587 self.axes = []
571
588
572 self.ax = self.figure.add_subplot(self.nrows, self.ncols, 1)
589 self.ax = self.figure.add_subplot(self.nrows, self.ncols, 1)
573 self.ax.firsttime = True
590 self.ax.firsttime = True
574
591
575 def plot(self):
592 def plot(self):
576
593
577 x = self.times
594 x = self.times
578 xmin = self.min_time
595 xmin = self.min_time
579 xmax = xmin+self.xrange*60*60
596 xmax = xmin+self.xrange*60*60
580 if self.ax.firsttime:
597 if self.ax.firsttime:
581 for ch in self.dataOut.channelList:
598 for ch in self.dataOut.channelList:
582 y = [self.data[self.CODE][t][ch] for t in self.times]
599 y = [self.data[self.CODE][t][ch] for t in self.times]
583 self.ax.plot(x, y, lw=1, label='Ch{}'.format(ch))
600 self.ax.plot(x, y, lw=1, label='Ch{}'.format(ch))
584 self.ax.firsttime = False
601 self.ax.firsttime = False
585 self.ax.xaxis.set_major_formatter(FuncFormatter(func))
602 self.ax.xaxis.set_major_formatter(FuncFormatter(func))
586 self.ax.xaxis.set_major_locator(LinearLocator(6))
603 self.ax.xaxis.set_major_locator(LinearLocator(6))
587 self.ax.set_ylabel(self.ylabel)
604 self.ax.set_ylabel(self.ylabel)
588 plt.legend()
605 plt.legend()
589 else:
606 else:
590 for ch in self.dataOut.channelList:
607 for ch in self.dataOut.channelList:
591 y = [self.data[self.CODE][t][ch] for t in self.times]
608 y = [self.data[self.CODE][t][ch] for t in self.times]
592 self.ax.lines[ch].set_data(x, y)
609 self.ax.lines[ch].set_data(x, y)
593
610
594 self.ax.set_xlim(xmin, xmax)
611 self.ax.set_xlim(xmin, xmax)
595 self.ax.set_ylim(min(y)-5, max(y)+5)
612 self.ax.set_ylim(min(y)-5, max(y)+5)
596 self.saveTime = self.min_time
613 self.saveTime = self.min_time
597
614
598
615
599 class PlotWindProfilerData(PlotRTIData):
616 class PlotWindProfilerData(PlotRTIData):
600
617
601 CODE = 'wind'
618 CODE = 'wind'
602 colormap = 'seismic'
619 colormap = 'seismic'
603
620
604 def setup(self):
621 def setup(self):
605 self.ncols = 1
622 self.ncols = 1
606 self.nrows = self.dataOut.data_output.shape[0]
623 self.nrows = self.dataOut.data_output.shape[0]
607 self.width = 10
624 self.width = 10
608 self.height = 2.2*self.nrows
625 self.height = 2.2*self.nrows
609 self.ylabel = 'Height [Km]'
626 self.ylabel = 'Height [Km]'
610 self.titles = ['Zonal Wind' ,'Meridional Wind', 'Vertical Wind']
627 self.titles = ['Zonal Wind' ,'Meridional Wind', 'Vertical Wind']
611 self.clabels = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
628 self.clabels = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
612 self.windFactor = [1, 1, 100]
629 self.windFactor = [1, 1, 100]
613
630
614 if self.figure is None:
631 if self.figure is None:
615 self.figure = plt.figure(figsize=(self.width, self.height),
632 self.figure = plt.figure(figsize=(self.width, self.height),
616 edgecolor='k',
633 edgecolor='k',
617 facecolor='w')
634 facecolor='w')
618 else:
635 else:
619 self.figure.clf()
636 self.figure.clf()
620 self.axes = []
637 self.axes = []
621
638
622 for n in range(self.nrows):
639 for n in range(self.nrows):
623 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
640 ax = self.figure.add_subplot(self.nrows, self.ncols, n+1)
624 ax.firsttime = True
641 ax.firsttime = True
625 self.axes.append(ax)
642 self.axes.append(ax)
626
643
627 def plot(self):
644 def plot(self):
628
645
629 self.x = np.array(self.times)
646 self.x = np.array(self.times)
630 self.y = self.dataOut.heightList
647 self.y = self.dataOut.heightList
631 self.z = []
648 self.z = []
632
649
633 for ch in range(self.nrows):
650 for ch in range(self.nrows):
634 self.z.append([self.data['output'][t][ch] for t in self.times])
651 self.z.append([self.data['output'][t][ch] for t in self.times])
635
652
636 self.z = np.array(self.z)
653 self.z = np.array(self.z)
637 self.z = numpy.ma.masked_invalid(self.z)
654 self.z = numpy.ma.masked_invalid(self.z)
638
655
639 cmap=plt.get_cmap(self.colormap)
656 cmap=plt.get_cmap(self.colormap)
640 cmap.set_bad('black', 1.)
657 cmap.set_bad('black', 1.)
641
658
642 for n, ax in enumerate(self.axes):
659 for n, ax in enumerate(self.axes):
643 x, y, z = self.fill_gaps(*self.decimate())
660 x, y, z = self.fill_gaps(*self.decimate())
644 xmin = self.min_time
661 xmin = self.min_time
645 xmax = xmin+self.xrange*60*60
662 xmax = xmin+self.xrange*60*60
646 if ax.firsttime:
663 if ax.firsttime:
647 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
664 self.ymin = self.ymin if self.ymin else np.nanmin(self.y)
648 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
665 self.ymax = self.ymax if self.ymax else np.nanmax(self.y)
649 self.zmax = self.zmax if self.zmax else numpy.nanmax(abs(self.z[:-1, :]))
666 self.zmax = self.zmax if self.zmax else numpy.nanmax(abs(self.z[:-1, :]))
650 self.zmin = self.zmin if self.zmin else -self.zmax
667 self.zmin = self.zmin if self.zmin else -self.zmax
651
668
652 plot = ax.pcolormesh(x, y, z[n].T*self.windFactor[n],
669 plot = ax.pcolormesh(x, y, z[n].T*self.windFactor[n],
653 vmin=self.zmin,
670 vmin=self.zmin,
654 vmax=self.zmax,
671 vmax=self.zmax,
655 cmap=cmap
672 cmap=cmap
656 )
673 )
657 divider = make_axes_locatable(ax)
674 divider = make_axes_locatable(ax)
658 cax = divider.new_horizontal(size='2%', pad=0.05)
675 cax = divider.new_horizontal(size='2%', pad=0.05)
659 self.figure.add_axes(cax)
676 self.figure.add_axes(cax)
660 cb = plt.colorbar(plot, cax)
677 cb = plt.colorbar(plot, cax)
661 cb.set_label(self.clabels[n])
678 cb.set_label(self.clabels[n])
662 ax.set_ylim(self.ymin, self.ymax)
679 ax.set_ylim(self.ymin, self.ymax)
663
680
664 ax.xaxis.set_major_formatter(FuncFormatter(func))
681 ax.xaxis.set_major_formatter(FuncFormatter(func))
665 ax.xaxis.set_major_locator(LinearLocator(6))
682 ax.xaxis.set_major_locator(LinearLocator(6))
666
683
667 ax.set_ylabel(self.ylabel)
684 ax.set_ylabel(self.ylabel)
668
685
669 ax.set_xlim(xmin, xmax)
686 ax.set_xlim(xmin, xmax)
670 ax.firsttime = False
687 ax.firsttime = False
671 else:
688 else:
672 ax.collections.remove(ax.collections[0])
689 ax.collections.remove(ax.collections[0])
673 ax.set_xlim(xmin, xmax)
690 ax.set_xlim(xmin, xmax)
674 plot = ax.pcolormesh(x, y, z[n].T*self.windFactor[n],
691 plot = ax.pcolormesh(x, y, z[n].T*self.windFactor[n],
675 vmin=self.zmin,
692 vmin=self.zmin,
676 vmax=self.zmax,
693 vmax=self.zmax,
677 cmap=plt.get_cmap(self.colormap)
694 cmap=plt.get_cmap(self.colormap)
678 )
695 )
679 ax.set_title('{} {}'.format(self.titles[n],
696 ax.set_title('{} {}'.format(self.titles[n],
680 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
697 datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')),
681 size=8)
698 size=8)
682
699
683 self.saveTime = self.min_time
700 self.saveTime = self.min_time
684
701
685
702
686 class PlotSNRData(PlotRTIData):
703 class PlotSNRData(PlotRTIData):
687 CODE = 'snr'
704 CODE = 'snr'
688 colormap = 'jet'
705 colormap = 'jet'
689
706
690 class PlotDOPData(PlotRTIData):
707 class PlotDOPData(PlotRTIData):
691 CODE = 'dop'
708 CODE = 'dop'
692 colormap = 'jet'
709 colormap = 'jet'
693
710
694
711
695 class PlotPHASEData(PlotCOHData):
712 class PlotPHASEData(PlotCOHData):
696 CODE = 'phase'
713 CODE = 'phase'
697 colormap = 'seismic'
714 colormap = 'seismic'
698
715
699
716
700 class PlotSkyMapData(PlotData):
717 class PlotSkyMapData(PlotData):
701
718
702 CODE = 'met'
719 CODE = 'met'
703
720
704 def setup(self):
721 def setup(self):
705
722
706 self.ncols = 1
723 self.ncols = 1
707 self.nrows = 1
724 self.nrows = 1
708 self.width = 7.2
725 self.width = 7.2
709 self.height = 7.2
726 self.height = 7.2
710
727
711 self.xlabel = 'Zonal Zenith Angle (deg)'
728 self.xlabel = 'Zonal Zenith Angle (deg)'
712 self.ylabel = 'Meridional Zenith Angle (deg)'
729 self.ylabel = 'Meridional Zenith Angle (deg)'
713
730
714 if self.figure is None:
731 if self.figure is None:
715 self.figure = plt.figure(figsize=(self.width, self.height),
732 self.figure = plt.figure(figsize=(self.width, self.height),
716 edgecolor='k',
733 edgecolor='k',
717 facecolor='w')
734 facecolor='w')
718 else:
735 else:
719 self.figure.clf()
736 self.figure.clf()
720
737
721 self.ax = plt.subplot2grid((self.nrows, self.ncols), (0, 0), 1, 1, polar=True)
738 self.ax = plt.subplot2grid((self.nrows, self.ncols), (0, 0), 1, 1, polar=True)
722 self.ax.firsttime = True
739 self.ax.firsttime = True
723
740
724
741
725 def plot(self):
742 def plot(self):
726
743
727 arrayParameters = np.concatenate([self.data['param'][t] for t in self.times])
744 arrayParameters = np.concatenate([self.data['param'][t] for t in self.times])
728 error = arrayParameters[:,-1]
745 error = arrayParameters[:,-1]
729 indValid = numpy.where(error == 0)[0]
746 indValid = numpy.where(error == 0)[0]
730 finalMeteor = arrayParameters[indValid,:]
747 finalMeteor = arrayParameters[indValid,:]
731 finalAzimuth = finalMeteor[:,3]
748 finalAzimuth = finalMeteor[:,3]
732 finalZenith = finalMeteor[:,4]
749 finalZenith = finalMeteor[:,4]
733
750
734 x = finalAzimuth*numpy.pi/180
751 x = finalAzimuth*numpy.pi/180
735 y = finalZenith
752 y = finalZenith
736
753
737 if self.ax.firsttime:
754 if self.ax.firsttime:
738 self.ax.plot = self.ax.plot(x, y, 'bo', markersize=5)[0]
755 self.ax.plot = self.ax.plot(x, y, 'bo', markersize=5)[0]
739 self.ax.set_ylim(0,90)
756 self.ax.set_ylim(0,90)
740 self.ax.set_yticks(numpy.arange(0,90,20))
757 self.ax.set_yticks(numpy.arange(0,90,20))
741 self.ax.set_xlabel(self.xlabel)
758 self.ax.set_xlabel(self.xlabel)
742 self.ax.set_ylabel(self.ylabel)
759 self.ax.set_ylabel(self.ylabel)
743 self.ax.yaxis.labelpad = 40
760 self.ax.yaxis.labelpad = 40
744 self.ax.firsttime = False
761 self.ax.firsttime = False
745 else:
762 else:
746 self.ax.plot.set_data(x, y)
763 self.ax.plot.set_data(x, y)
747
764
748
765
749 dt1 = datetime.datetime.fromtimestamp(self.min_time).strftime('%y/%m/%d %H:%M:%S')
766 dt1 = datetime.datetime.fromtimestamp(self.min_time).strftime('%y/%m/%d %H:%M:%S')
750 dt2 = datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')
767 dt2 = datetime.datetime.fromtimestamp(self.max_time).strftime('%y/%m/%d %H:%M:%S')
751 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
768 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
752 dt2,
769 dt2,
753 len(x))
770 len(x))
754 self.ax.set_title(title, size=8)
771 self.ax.set_title(title, size=8)
755
772
756 self.saveTime = self.max_time
773 self.saveTime = self.max_time
@@ -1,1946 +1,1945
1 import os
1 import os
2 import datetime
2 import datetime
3 import numpy
3 import numpy
4
4 import inspect
5 from figure import Figure, isRealtime, isTimeInHourRange
5 from figure import Figure, isRealtime, isTimeInHourRange
6 from plotting_codes import *
6 from plotting_codes import *
7
7
8
8
9 class MomentsPlot(Figure):
9 class MomentsPlot(Figure):
10
10
11 isConfig = None
11 isConfig = None
12 __nsubplots = None
12 __nsubplots = None
13
13
14 WIDTHPROF = None
14 WIDTHPROF = None
15 HEIGHTPROF = None
15 HEIGHTPROF = None
16 PREFIX = 'prm'
16 PREFIX = 'prm'
17
17
18 def __init__(self, **kwargs):
18 def __init__(self, **kwargs):
19 Figure.__init__(self, **kwargs)
19 Figure.__init__(self, **kwargs)
20 self.isConfig = False
20 self.isConfig = False
21 self.__nsubplots = 1
21 self.__nsubplots = 1
22
22
23 self.WIDTH = 280
23 self.WIDTH = 280
24 self.HEIGHT = 250
24 self.HEIGHT = 250
25 self.WIDTHPROF = 120
25 self.WIDTHPROF = 120
26 self.HEIGHTPROF = 0
26 self.HEIGHTPROF = 0
27 self.counter_imagwr = 0
27 self.counter_imagwr = 0
28
28
29 self.PLOT_CODE = MOMENTS_CODE
29 self.PLOT_CODE = MOMENTS_CODE
30
30
31 self.FTP_WEI = None
31 self.FTP_WEI = None
32 self.EXP_CODE = None
32 self.EXP_CODE = None
33 self.SUB_EXP_CODE = None
33 self.SUB_EXP_CODE = None
34 self.PLOT_POS = None
34 self.PLOT_POS = None
35
35
36 def getSubplots(self):
36 def getSubplots(self):
37
37
38 ncol = int(numpy.sqrt(self.nplots)+0.9)
38 ncol = int(numpy.sqrt(self.nplots)+0.9)
39 nrow = int(self.nplots*1./ncol + 0.9)
39 nrow = int(self.nplots*1./ncol + 0.9)
40
40
41 return nrow, ncol
41 return nrow, ncol
42
42
43 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
43 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
44
44
45 self.__showprofile = showprofile
45 self.__showprofile = showprofile
46 self.nplots = nplots
46 self.nplots = nplots
47
47
48 ncolspan = 1
48 ncolspan = 1
49 colspan = 1
49 colspan = 1
50 if showprofile:
50 if showprofile:
51 ncolspan = 3
51 ncolspan = 3
52 colspan = 2
52 colspan = 2
53 self.__nsubplots = 2
53 self.__nsubplots = 2
54
54
55 self.createFigure(id = id,
55 self.createFigure(id = id,
56 wintitle = wintitle,
56 wintitle = wintitle,
57 widthplot = self.WIDTH + self.WIDTHPROF,
57 widthplot = self.WIDTH + self.WIDTHPROF,
58 heightplot = self.HEIGHT + self.HEIGHTPROF,
58 heightplot = self.HEIGHT + self.HEIGHTPROF,
59 show=show)
59 show=show)
60
60
61 nrow, ncol = self.getSubplots()
61 nrow, ncol = self.getSubplots()
62
62
63 counter = 0
63 counter = 0
64 for y in range(nrow):
64 for y in range(nrow):
65 for x in range(ncol):
65 for x in range(ncol):
66
66
67 if counter >= self.nplots:
67 if counter >= self.nplots:
68 break
68 break
69
69
70 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
70 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
71
71
72 if showprofile:
72 if showprofile:
73 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
73 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
74
74
75 counter += 1
75 counter += 1
76
76
77 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
77 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
78 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
78 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
79 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
79 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
80 server=None, folder=None, username=None, password=None,
80 server=None, folder=None, username=None, password=None,
81 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
81 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
82
82
83 """
83 """
84
84
85 Input:
85 Input:
86 dataOut :
86 dataOut :
87 id :
87 id :
88 wintitle :
88 wintitle :
89 channelList :
89 channelList :
90 showProfile :
90 showProfile :
91 xmin : None,
91 xmin : None,
92 xmax : None,
92 xmax : None,
93 ymin : None,
93 ymin : None,
94 ymax : None,
94 ymax : None,
95 zmin : None,
95 zmin : None,
96 zmax : None
96 zmax : None
97 """
97 """
98
98
99 if dataOut.flagNoData:
99 if dataOut.flagNoData:
100 return None
100 return None
101
101
102 if realtime:
102 if realtime:
103 if not(isRealtime(utcdatatime = dataOut.utctime)):
103 if not(isRealtime(utcdatatime = dataOut.utctime)):
104 print 'Skipping this plot function'
104 print 'Skipping this plot function'
105 return
105 return
106
106
107 if channelList == None:
107 if channelList == None:
108 channelIndexList = dataOut.channelIndexList
108 channelIndexList = dataOut.channelIndexList
109 else:
109 else:
110 channelIndexList = []
110 channelIndexList = []
111 for channel in channelList:
111 for channel in channelList:
112 if channel not in dataOut.channelList:
112 if channel not in dataOut.channelList:
113 raise ValueError, "Channel %d is not in dataOut.channelList"
113 raise ValueError, "Channel %d is not in dataOut.channelList"
114 channelIndexList.append(dataOut.channelList.index(channel))
114 channelIndexList.append(dataOut.channelList.index(channel))
115
115
116 factor = dataOut.normFactor
116 factor = dataOut.normFactor
117 x = dataOut.abscissaList
117 x = dataOut.abscissaList
118 y = dataOut.heightList
118 y = dataOut.heightList
119
119
120 z = dataOut.data_pre[channelIndexList,:,:]/factor
120 z = dataOut.data_pre[channelIndexList,:,:]/factor
121 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
121 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
122 avg = numpy.average(z, axis=1)
122 avg = numpy.average(z, axis=1)
123 noise = dataOut.noise/factor
123 noise = dataOut.noise/factor
124
124
125 zdB = 10*numpy.log10(z)
125 zdB = 10*numpy.log10(z)
126 avgdB = 10*numpy.log10(avg)
126 avgdB = 10*numpy.log10(avg)
127 noisedB = 10*numpy.log10(noise)
127 noisedB = 10*numpy.log10(noise)
128
128
129 #thisDatetime = dataOut.datatime
129 #thisDatetime = dataOut.datatime
130 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
130 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
131 title = wintitle + " Parameters"
131 title = wintitle + " Parameters"
132 xlabel = "Velocity (m/s)"
132 xlabel = "Velocity (m/s)"
133 ylabel = "Range (Km)"
133 ylabel = "Range (Km)"
134
134
135 update_figfile = False
135 update_figfile = False
136
136
137 if not self.isConfig:
137 if not self.isConfig:
138
138
139 nplots = len(channelIndexList)
139 nplots = len(channelIndexList)
140
140
141 self.setup(id=id,
141 self.setup(id=id,
142 nplots=nplots,
142 nplots=nplots,
143 wintitle=wintitle,
143 wintitle=wintitle,
144 showprofile=showprofile,
144 showprofile=showprofile,
145 show=show)
145 show=show)
146
146
147 if xmin == None: xmin = numpy.nanmin(x)
147 if xmin == None: xmin = numpy.nanmin(x)
148 if xmax == None: xmax = numpy.nanmax(x)
148 if xmax == None: xmax = numpy.nanmax(x)
149 if ymin == None: ymin = numpy.nanmin(y)
149 if ymin == None: ymin = numpy.nanmin(y)
150 if ymax == None: ymax = numpy.nanmax(y)
150 if ymax == None: ymax = numpy.nanmax(y)
151 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
151 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
152 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
152 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
153
153
154 self.FTP_WEI = ftp_wei
154 self.FTP_WEI = ftp_wei
155 self.EXP_CODE = exp_code
155 self.EXP_CODE = exp_code
156 self.SUB_EXP_CODE = sub_exp_code
156 self.SUB_EXP_CODE = sub_exp_code
157 self.PLOT_POS = plot_pos
157 self.PLOT_POS = plot_pos
158
158
159 self.isConfig = True
159 self.isConfig = True
160 update_figfile = True
160 update_figfile = True
161
161
162 self.setWinTitle(title)
162 self.setWinTitle(title)
163
163
164 for i in range(self.nplots):
164 for i in range(self.nplots):
165 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
165 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
166 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i], noisedB[i], str_datetime)
166 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i], noisedB[i], str_datetime)
167 axes = self.axesList[i*self.__nsubplots]
167 axes = self.axesList[i*self.__nsubplots]
168 axes.pcolor(x, y, zdB[i,:,:],
168 axes.pcolor(x, y, zdB[i,:,:],
169 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
169 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
170 xlabel=xlabel, ylabel=ylabel, title=title,
170 xlabel=xlabel, ylabel=ylabel, title=title,
171 ticksize=9, cblabel='')
171 ticksize=9, cblabel='')
172 #Mean Line
172 #Mean Line
173 mean = dataOut.data_param[i, 1, :]
173 mean = dataOut.data_param[i, 1, :]
174 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
174 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
175
175
176 if self.__showprofile:
176 if self.__showprofile:
177 axes = self.axesList[i*self.__nsubplots +1]
177 axes = self.axesList[i*self.__nsubplots +1]
178 axes.pline(avgdB[i], y,
178 axes.pline(avgdB[i], y,
179 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
179 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
180 xlabel='dB', ylabel='', title='',
180 xlabel='dB', ylabel='', title='',
181 ytick_visible=False,
181 ytick_visible=False,
182 grid='x')
182 grid='x')
183
183
184 noiseline = numpy.repeat(noisedB[i], len(y))
184 noiseline = numpy.repeat(noisedB[i], len(y))
185 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
185 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
186
186
187 self.draw()
187 self.draw()
188
188
189 self.save(figpath=figpath,
189 self.save(figpath=figpath,
190 figfile=figfile,
190 figfile=figfile,
191 save=save,
191 save=save,
192 ftp=ftp,
192 ftp=ftp,
193 wr_period=wr_period,
193 wr_period=wr_period,
194 thisDatetime=thisDatetime)
194 thisDatetime=thisDatetime)
195
195
196
196
197
197
198 class SkyMapPlot(Figure):
198 class SkyMapPlot(Figure):
199
199
200 __isConfig = None
200 __isConfig = None
201 __nsubplots = None
201 __nsubplots = None
202
202
203 WIDTHPROF = None
203 WIDTHPROF = None
204 HEIGHTPROF = None
204 HEIGHTPROF = None
205 PREFIX = 'mmap'
205 PREFIX = 'mmap'
206
206
207 def __init__(self, **kwargs):
207 def __init__(self, **kwargs):
208 Figure.__init__(self, **kwargs)
208 Figure.__init__(self, **kwargs)
209 self.isConfig = False
209 self.isConfig = False
210 self.__nsubplots = 1
210 self.__nsubplots = 1
211
211
212 # self.WIDTH = 280
212 # self.WIDTH = 280
213 # self.HEIGHT = 250
213 # self.HEIGHT = 250
214 self.WIDTH = 600
214 self.WIDTH = 600
215 self.HEIGHT = 600
215 self.HEIGHT = 600
216 self.WIDTHPROF = 120
216 self.WIDTHPROF = 120
217 self.HEIGHTPROF = 0
217 self.HEIGHTPROF = 0
218 self.counter_imagwr = 0
218 self.counter_imagwr = 0
219
219
220 self.PLOT_CODE = MSKYMAP_CODE
220 self.PLOT_CODE = MSKYMAP_CODE
221
221
222 self.FTP_WEI = None
222 self.FTP_WEI = None
223 self.EXP_CODE = None
223 self.EXP_CODE = None
224 self.SUB_EXP_CODE = None
224 self.SUB_EXP_CODE = None
225 self.PLOT_POS = None
225 self.PLOT_POS = None
226
226
227 def getSubplots(self):
227 def getSubplots(self):
228
228
229 ncol = int(numpy.sqrt(self.nplots)+0.9)
229 ncol = int(numpy.sqrt(self.nplots)+0.9)
230 nrow = int(self.nplots*1./ncol + 0.9)
230 nrow = int(self.nplots*1./ncol + 0.9)
231
231
232 return nrow, ncol
232 return nrow, ncol
233
233
234 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
234 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
235
235
236 self.__showprofile = showprofile
236 self.__showprofile = showprofile
237 self.nplots = nplots
237 self.nplots = nplots
238
238
239 ncolspan = 1
239 ncolspan = 1
240 colspan = 1
240 colspan = 1
241
241
242 self.createFigure(id = id,
242 self.createFigure(id = id,
243 wintitle = wintitle,
243 wintitle = wintitle,
244 widthplot = self.WIDTH, #+ self.WIDTHPROF,
244 widthplot = self.WIDTH, #+ self.WIDTHPROF,
245 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
245 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
246 show=show)
246 show=show)
247
247
248 nrow, ncol = 1,1
248 nrow, ncol = 1,1
249 counter = 0
249 counter = 0
250 x = 0
250 x = 0
251 y = 0
251 y = 0
252 self.addAxes(1, 1, 0, 0, 1, 1, True)
252 self.addAxes(1, 1, 0, 0, 1, 1, True)
253
253
254 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
254 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
255 tmin=0, tmax=24, timerange=None,
255 tmin=0, tmax=24, timerange=None,
256 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
256 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
257 server=None, folder=None, username=None, password=None,
257 server=None, folder=None, username=None, password=None,
258 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
258 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
259
259
260 """
260 """
261
261
262 Input:
262 Input:
263 dataOut :
263 dataOut :
264 id :
264 id :
265 wintitle :
265 wintitle :
266 channelList :
266 channelList :
267 showProfile :
267 showProfile :
268 xmin : None,
268 xmin : None,
269 xmax : None,
269 xmax : None,
270 ymin : None,
270 ymin : None,
271 ymax : None,
271 ymax : None,
272 zmin : None,
272 zmin : None,
273 zmax : None
273 zmax : None
274 """
274 """
275
275
276 arrayParameters = dataOut.data_param
276 arrayParameters = dataOut.data_param
277 error = arrayParameters[:,-1]
277 error = arrayParameters[:,-1]
278 indValid = numpy.where(error == 0)[0]
278 indValid = numpy.where(error == 0)[0]
279 finalMeteor = arrayParameters[indValid,:]
279 finalMeteor = arrayParameters[indValid,:]
280 finalAzimuth = finalMeteor[:,3]
280 finalAzimuth = finalMeteor[:,3]
281 finalZenith = finalMeteor[:,4]
281 finalZenith = finalMeteor[:,4]
282
282
283 x = finalAzimuth*numpy.pi/180
283 x = finalAzimuth*numpy.pi/180
284 y = finalZenith
284 y = finalZenith
285 x1 = [dataOut.ltctime, dataOut.ltctime]
285 x1 = [dataOut.ltctime, dataOut.ltctime]
286
286
287 #thisDatetime = dataOut.datatime
287 #thisDatetime = dataOut.datatime
288 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
288 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
289 title = wintitle + " Parameters"
289 title = wintitle + " Parameters"
290 xlabel = "Zonal Zenith Angle (deg) "
290 xlabel = "Zonal Zenith Angle (deg) "
291 ylabel = "Meridional Zenith Angle (deg)"
291 ylabel = "Meridional Zenith Angle (deg)"
292 update_figfile = False
292 update_figfile = False
293
293
294 if not self.isConfig:
294 if not self.isConfig:
295
295
296 nplots = 1
296 nplots = 1
297
297
298 self.setup(id=id,
298 self.setup(id=id,
299 nplots=nplots,
299 nplots=nplots,
300 wintitle=wintitle,
300 wintitle=wintitle,
301 showprofile=showprofile,
301 showprofile=showprofile,
302 show=show)
302 show=show)
303
303
304 if self.xmin is None and self.xmax is None:
304 if self.xmin is None and self.xmax is None:
305 self.xmin, self.xmax = self.getTimeLim(x1, tmin, tmax, timerange)
305 self.xmin, self.xmax = self.getTimeLim(x1, tmin, tmax, timerange)
306
306
307 if timerange != None:
307 if timerange != None:
308 self.timerange = timerange
308 self.timerange = timerange
309 else:
309 else:
310 self.timerange = self.xmax - self.xmin
310 self.timerange = self.xmax - self.xmin
311
311
312 self.FTP_WEI = ftp_wei
312 self.FTP_WEI = ftp_wei
313 self.EXP_CODE = exp_code
313 self.EXP_CODE = exp_code
314 self.SUB_EXP_CODE = sub_exp_code
314 self.SUB_EXP_CODE = sub_exp_code
315 self.PLOT_POS = plot_pos
315 self.PLOT_POS = plot_pos
316 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
316 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
317 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
317 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
318 self.isConfig = True
318 self.isConfig = True
319 update_figfile = True
319 update_figfile = True
320
320
321 self.setWinTitle(title)
321 self.setWinTitle(title)
322
322
323 i = 0
323 i = 0
324 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
324 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
325
325
326 axes = self.axesList[i*self.__nsubplots]
326 axes = self.axesList[i*self.__nsubplots]
327 nevents = axes.x_buffer.shape[0] + x.shape[0]
327 nevents = axes.x_buffer.shape[0] + x.shape[0]
328 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
328 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
329 axes.polar(x, y,
329 axes.polar(x, y,
330 title=title, xlabel=xlabel, ylabel=ylabel,
330 title=title, xlabel=xlabel, ylabel=ylabel,
331 ticksize=9, cblabel='')
331 ticksize=9, cblabel='')
332
332
333 self.draw()
333 self.draw()
334
334
335 self.save(figpath=figpath,
335 self.save(figpath=figpath,
336 figfile=figfile,
336 figfile=figfile,
337 save=save,
337 save=save,
338 ftp=ftp,
338 ftp=ftp,
339 wr_period=wr_period,
339 wr_period=wr_period,
340 thisDatetime=thisDatetime,
340 thisDatetime=thisDatetime,
341 update_figfile=update_figfile)
341 update_figfile=update_figfile)
342
342
343 if dataOut.ltctime >= self.xmax:
343 if dataOut.ltctime >= self.xmax:
344 self.isConfigmagwr = wr_period
344 self.isConfigmagwr = wr_period
345 self.isConfig = False
345 self.isConfig = False
346 update_figfile = True
346 update_figfile = True
347 axes.__firsttime = True
347 axes.__firsttime = True
348 self.xmin += self.timerange
348 self.xmin += self.timerange
349 self.xmax += self.timerange
349 self.xmax += self.timerange
350
350
351
351
352
352
353
353
354 class WindProfilerPlot(Figure):
354 class WindProfilerPlot(Figure):
355
355
356 __isConfig = None
356 __isConfig = None
357 __nsubplots = None
357 __nsubplots = None
358
358
359 WIDTHPROF = None
359 WIDTHPROF = None
360 HEIGHTPROF = None
360 HEIGHTPROF = None
361 PREFIX = 'wind'
361 PREFIX = 'wind'
362
362
363 def __init__(self, **kwargs):
363 def __init__(self, **kwargs):
364 Figure.__init__(self, **kwargs)
364 Figure.__init__(self, **kwargs)
365 self.timerange = None
365 self.timerange = None
366 self.isConfig = False
366 self.isConfig = False
367 self.__nsubplots = 1
367 self.__nsubplots = 1
368
368
369 self.WIDTH = 800
369 self.WIDTH = 800
370 self.HEIGHT = 300
370 self.HEIGHT = 300
371 self.WIDTHPROF = 120
371 self.WIDTHPROF = 120
372 self.HEIGHTPROF = 0
372 self.HEIGHTPROF = 0
373 self.counter_imagwr = 0
373 self.counter_imagwr = 0
374
374
375 self.PLOT_CODE = WIND_CODE
375 self.PLOT_CODE = WIND_CODE
376
376
377 self.FTP_WEI = None
377 self.FTP_WEI = None
378 self.EXP_CODE = None
378 self.EXP_CODE = None
379 self.SUB_EXP_CODE = None
379 self.SUB_EXP_CODE = None
380 self.PLOT_POS = None
380 self.PLOT_POS = None
381 self.tmin = None
381 self.tmin = None
382 self.tmax = None
382 self.tmax = None
383
383
384 self.xmin = None
384 self.xmin = None
385 self.xmax = None
385 self.xmax = None
386
386
387 self.figfile = None
387 self.figfile = None
388
388
389 def getSubplots(self):
389 def getSubplots(self):
390
390
391 ncol = 1
391 ncol = 1
392 nrow = self.nplots
392 nrow = self.nplots
393
393
394 return nrow, ncol
394 return nrow, ncol
395
395
396 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
396 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
397
397
398 self.__showprofile = showprofile
398 self.__showprofile = showprofile
399 self.nplots = nplots
399 self.nplots = nplots
400
400
401 ncolspan = 1
401 ncolspan = 1
402 colspan = 1
402 colspan = 1
403
403
404 self.createFigure(id = id,
404 self.createFigure(id = id,
405 wintitle = wintitle,
405 wintitle = wintitle,
406 widthplot = self.WIDTH + self.WIDTHPROF,
406 widthplot = self.WIDTH + self.WIDTHPROF,
407 heightplot = self.HEIGHT + self.HEIGHTPROF,
407 heightplot = self.HEIGHT + self.HEIGHTPROF,
408 show=show)
408 show=show)
409
409
410 nrow, ncol = self.getSubplots()
410 nrow, ncol = self.getSubplots()
411
411
412 counter = 0
412 counter = 0
413 for y in range(nrow):
413 for y in range(nrow):
414 if counter >= self.nplots:
414 if counter >= self.nplots:
415 break
415 break
416
416
417 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
417 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
418 counter += 1
418 counter += 1
419
419
420 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='False',
420 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='False',
421 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
421 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
422 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
422 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
423 timerange=None, SNRthresh = None,
423 timerange=None, SNRthresh = None,
424 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
424 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
425 server=None, folder=None, username=None, password=None,
425 server=None, folder=None, username=None, password=None,
426 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
426 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
427 """
427 """
428
428
429 Input:
429 Input:
430 dataOut :
430 dataOut :
431 id :
431 id :
432 wintitle :
432 wintitle :
433 channelList :
433 channelList :
434 showProfile :
434 showProfile :
435 xmin : None,
435 xmin : None,
436 xmax : None,
436 xmax : None,
437 ymin : None,
437 ymin : None,
438 ymax : None,
438 ymax : None,
439 zmin : None,
439 zmin : None,
440 zmax : None
440 zmax : None
441 """
441 """
442
442
443 # if timerange is not None:
443 # if timerange is not None:
444 # self.timerange = timerange
444 # self.timerange = timerange
445 #
445 #
446 # tmin = None
446 # tmin = None
447 # tmax = None
447 # tmax = None
448
448
449
449
450 x = dataOut.getTimeRange1(dataOut.outputInterval)
450 x = dataOut.getTimeRange1(dataOut.outputInterval)
451 y = dataOut.heightList
451 y = dataOut.heightList
452 z = dataOut.data_output.copy()
452 z = dataOut.data_output.copy()
453 nplots = z.shape[0] #Number of wind dimensions estimated
453 nplots = z.shape[0] #Number of wind dimensions estimated
454 nplotsw = nplots
454 nplotsw = nplots
455
455
456
456
457 #If there is a SNR function defined
457 #If there is a SNR function defined
458 if dataOut.data_SNR is not None:
458 if dataOut.data_SNR is not None:
459 nplots += 1
459 nplots += 1
460 SNR = dataOut.data_SNR
460 SNR = dataOut.data_SNR
461 SNRavg = numpy.average(SNR, axis=0)
461 SNRavg = numpy.average(SNR, axis=0)
462
462
463 SNRdB = 10*numpy.log10(SNR)
463 SNRdB = 10*numpy.log10(SNR)
464 SNRavgdB = 10*numpy.log10(SNRavg)
464 SNRavgdB = 10*numpy.log10(SNRavg)
465
465
466 if SNRthresh == None: SNRthresh = -5.0
466 if SNRthresh == None: SNRthresh = -5.0
467 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
467 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
468
468
469 for i in range(nplotsw):
469 for i in range(nplotsw):
470 z[i,ind] = numpy.nan
470 z[i,ind] = numpy.nan
471
471
472 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
472 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
473 #thisDatetime = datetime.datetime.now()
473 #thisDatetime = datetime.datetime.now()
474 title = wintitle + "Wind"
474 title = wintitle + "Wind"
475 xlabel = ""
475 xlabel = ""
476 ylabel = "Height (km)"
476 ylabel = "Height (km)"
477 update_figfile = False
477 update_figfile = False
478
478
479 if not self.isConfig:
479 if not self.isConfig:
480
480
481 self.setup(id=id,
481 self.setup(id=id,
482 nplots=nplots,
482 nplots=nplots,
483 wintitle=wintitle,
483 wintitle=wintitle,
484 showprofile=showprofile,
484 showprofile=showprofile,
485 show=show)
485 show=show)
486
486
487 if timerange is not None:
487 if timerange is not None:
488 self.timerange = timerange
488 self.timerange = timerange
489
489
490 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
490 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
491
491
492 if ymin == None: ymin = numpy.nanmin(y)
492 if ymin == None: ymin = numpy.nanmin(y)
493 if ymax == None: ymax = numpy.nanmax(y)
493 if ymax == None: ymax = numpy.nanmax(y)
494
494
495 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
495 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
496 #if numpy.isnan(zmax): zmax = 50
496 #if numpy.isnan(zmax): zmax = 50
497 if zmin == None: zmin = -zmax
497 if zmin == None: zmin = -zmax
498
498
499 if nplotsw == 3:
499 if nplotsw == 3:
500 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
500 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
501 if zmin_ver == None: zmin_ver = -zmax_ver
501 if zmin_ver == None: zmin_ver = -zmax_ver
502
502
503 if dataOut.data_SNR is not None:
503 if dataOut.data_SNR is not None:
504 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
504 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
505 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
505 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
506
506
507
507
508 self.FTP_WEI = ftp_wei
508 self.FTP_WEI = ftp_wei
509 self.EXP_CODE = exp_code
509 self.EXP_CODE = exp_code
510 self.SUB_EXP_CODE = sub_exp_code
510 self.SUB_EXP_CODE = sub_exp_code
511 self.PLOT_POS = plot_pos
511 self.PLOT_POS = plot_pos
512
512
513 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
513 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
514 self.isConfig = True
514 self.isConfig = True
515 self.figfile = figfile
515 self.figfile = figfile
516 update_figfile = True
516 update_figfile = True
517
517
518 self.setWinTitle(title)
518 self.setWinTitle(title)
519
519
520 if ((self.xmax - x[1]) < (x[1]-x[0])):
520 if ((self.xmax - x[1]) < (x[1]-x[0])):
521 x[1] = self.xmax
521 x[1] = self.xmax
522
522
523 strWind = ['Zonal', 'Meridional', 'Vertical']
523 strWind = ['Zonal', 'Meridional', 'Vertical']
524 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
524 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
525 zmaxVector = [zmax, zmax, zmax_ver]
525 zmaxVector = [zmax, zmax, zmax_ver]
526 zminVector = [zmin, zmin, zmin_ver]
526 zminVector = [zmin, zmin, zmin_ver]
527 windFactor = [1,1,100]
527 windFactor = [1,1,100]
528
528
529 for i in range(nplotsw):
529 for i in range(nplotsw):
530
530
531 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
531 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
532 axes = self.axesList[i*self.__nsubplots]
532 axes = self.axesList[i*self.__nsubplots]
533
533
534 z1 = z[i,:].reshape((1,-1))*windFactor[i]
534 z1 = z[i,:].reshape((1,-1))*windFactor[i]
535 #z1=numpy.ma.masked_where(z1==0.,z1)
535 #z1=numpy.ma.masked_where(z1==0.,z1)
536
536
537 axes.pcolorbuffer(x, y, z1,
537 axes.pcolorbuffer(x, y, z1,
538 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
538 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
539 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
539 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
540 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="seismic" )
540 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="seismic" )
541
541
542 if dataOut.data_SNR is not None:
542 if dataOut.data_SNR is not None:
543 i += 1
543 i += 1
544 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
544 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
545 axes = self.axesList[i*self.__nsubplots]
545 axes = self.axesList[i*self.__nsubplots]
546 SNRavgdB = SNRavgdB.reshape((1,-1))
546 SNRavgdB = SNRavgdB.reshape((1,-1))
547 axes.pcolorbuffer(x, y, SNRavgdB,
547 axes.pcolorbuffer(x, y, SNRavgdB,
548 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
548 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
549 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
549 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
550 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
550 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
551
551
552 self.draw()
552 self.draw()
553
553
554 self.save(figpath=figpath,
554 self.save(figpath=figpath,
555 figfile=figfile,
555 figfile=figfile,
556 save=save,
556 save=save,
557 ftp=ftp,
557 ftp=ftp,
558 wr_period=wr_period,
558 wr_period=wr_period,
559 thisDatetime=thisDatetime,
559 thisDatetime=thisDatetime,
560 update_figfile=update_figfile)
560 update_figfile=update_figfile)
561
561
562 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
562 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
563 self.counter_imagwr = wr_period
563 self.counter_imagwr = wr_period
564 self.isConfig = False
564 self.isConfig = False
565 update_figfile = True
565 update_figfile = True
566
566
567
567
568 class ParametersPlot(Figure):
568 class ParametersPlot(Figure):
569
569
570 __isConfig = None
570 __isConfig = None
571 __nsubplots = None
571 __nsubplots = None
572
572
573 WIDTHPROF = None
573 WIDTHPROF = None
574 HEIGHTPROF = None
574 HEIGHTPROF = None
575 PREFIX = 'param'
575 PREFIX = 'param'
576
576
577 nplots = None
577 nplots = None
578 nchan = None
578 nchan = None
579
579
580 def __init__(self, **kwargs):
580 def __init__(self, **kwargs):
581 Figure.__init__(self, **kwargs)
581 Figure.__init__(self, **kwargs)
582 self.timerange = None
582 self.timerange = None
583 self.isConfig = False
583 self.isConfig = False
584 self.__nsubplots = 1
584 self.__nsubplots = 1
585
585
586 self.WIDTH = 800
586 self.WIDTH = 800
587 self.HEIGHT = 180
587 self.HEIGHT = 180
588 self.WIDTHPROF = 120
588 self.WIDTHPROF = 120
589 self.HEIGHTPROF = 0
589 self.HEIGHTPROF = 0
590 self.counter_imagwr = 0
590 self.counter_imagwr = 0
591
591
592 self.PLOT_CODE = RTI_CODE
592 self.PLOT_CODE = RTI_CODE
593
593
594 self.FTP_WEI = None
594 self.FTP_WEI = None
595 self.EXP_CODE = None
595 self.EXP_CODE = None
596 self.SUB_EXP_CODE = None
596 self.SUB_EXP_CODE = None
597 self.PLOT_POS = None
597 self.PLOT_POS = None
598 self.tmin = None
598 self.tmin = None
599 self.tmax = None
599 self.tmax = None
600
600
601 self.xmin = None
601 self.xmin = None
602 self.xmax = None
602 self.xmax = None
603
603
604 self.figfile = None
604 self.figfile = None
605
605
606 def getSubplots(self):
606 def getSubplots(self):
607
607
608 ncol = 1
608 ncol = 1
609 nrow = self.nplots
609 nrow = self.nplots
610
610
611 return nrow, ncol
611 return nrow, ncol
612
612
613 def setup(self, id, nplots, wintitle, show=True):
613 def setup(self, id, nplots, wintitle, show=True):
614
614
615 self.nplots = nplots
615 self.nplots = nplots
616
616
617 ncolspan = 1
617 ncolspan = 1
618 colspan = 1
618 colspan = 1
619
619
620 self.createFigure(id = id,
620 self.createFigure(id = id,
621 wintitle = wintitle,
621 wintitle = wintitle,
622 widthplot = self.WIDTH + self.WIDTHPROF,
622 widthplot = self.WIDTH + self.WIDTHPROF,
623 heightplot = self.HEIGHT + self.HEIGHTPROF,
623 heightplot = self.HEIGHT + self.HEIGHTPROF,
624 show=show)
624 show=show)
625
625
626 nrow, ncol = self.getSubplots()
626 nrow, ncol = self.getSubplots()
627
627
628 counter = 0
628 counter = 0
629 for y in range(nrow):
629 for y in range(nrow):
630 for x in range(ncol):
630 for x in range(ncol):
631
631
632 if counter >= self.nplots:
632 if counter >= self.nplots:
633 break
633 break
634
634
635 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
635 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
636
636
637 counter += 1
637 counter += 1
638
638
639 def run(self, dataOut, id, wintitle="", channelList=None, paramIndex = 0, colormap=True,
639 def run(self, dataOut, id, wintitle="", channelList=None, paramIndex = 0, colormap=True,
640 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, timerange=None,
640 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, timerange=None,
641 showSNR=False, SNRthresh = -numpy.inf, SNRmin=None, SNRmax=None,
641 showSNR=False, SNRthresh = -numpy.inf, SNRmin=None, SNRmax=None,
642 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
642 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
643 server=None, folder=None, username=None, password=None,
643 server=None, folder=None, username=None, password=None,
644 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
644 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
645
646 """
645 """
647
646
648 Input:
647 Input:
649 dataOut :
648 dataOut :
650 id :
649 id :
651 wintitle :
650 wintitle :
652 channelList :
651 channelList :
653 showProfile :
652 showProfile :
654 xmin : None,
653 xmin : None,
655 xmax : None,
654 xmax : None,
656 ymin : None,
655 ymin : None,
657 ymax : None,
656 ymax : None,
658 zmin : None,
657 zmin : None,
659 zmax : None
658 zmax : None
660 """
659 """
661
660
662 if colormap:
661 if colormap:
663 colormap="jet"
662 colormap="jet"
664 else:
663 else:
665 colormap="RdBu_r"
664 colormap="RdBu_r"
666
665
667 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
666 if not isTimeInHourRange(dataOut.datatime, xmin, xmax):
668 return
667 return
669
668
670 if channelList == None:
669 if channelList == None:
671 channelIndexList = range(dataOut.data_param.shape[0])
670 channelIndexList = range(dataOut.data_param.shape[0])
672 else:
671 else:
673 channelIndexList = []
672 channelIndexList = []
674 for channel in channelList:
673 for channel in channelList:
675 if channel not in dataOut.channelList:
674 if channel not in dataOut.channelList:
676 raise ValueError, "Channel %d is not in dataOut.channelList"
675 raise ValueError, "Channel %d is not in dataOut.channelList"
677 channelIndexList.append(dataOut.channelList.index(channel))
676 channelIndexList.append(dataOut.channelList.index(channel))
678
677
679 x = dataOut.getTimeRange1(dataOut.paramInterval)
678 x = dataOut.getTimeRange1(dataOut.paramInterval)
680 y = dataOut.getHeiRange()
679 y = dataOut.getHeiRange()
681
680
682 if dataOut.data_param.ndim == 3:
681 if dataOut.data_param.ndim == 3:
683 z = dataOut.data_param[channelIndexList,paramIndex,:]
682 z = dataOut.data_param[channelIndexList,paramIndex,:]
684 else:
683 else:
685 z = dataOut.data_param[channelIndexList,:]
684 z = dataOut.data_param[channelIndexList,:]
686
685
687 if showSNR:
686 if showSNR:
688 #SNR data
687 #SNR data
689 SNRarray = dataOut.data_SNR[channelIndexList,:]
688 SNRarray = dataOut.data_SNR[channelIndexList,:]
690 SNRdB = 10*numpy.log10(SNRarray)
689 SNRdB = 10*numpy.log10(SNRarray)
691 ind = numpy.where(SNRdB < SNRthresh)
690 ind = numpy.where(SNRdB < SNRthresh)
692 z[ind] = numpy.nan
691 z[ind] = numpy.nan
693
692
694 thisDatetime = dataOut.datatime
693 thisDatetime = dataOut.datatime
695 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
694 # thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
696 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
695 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
697 xlabel = ""
696 xlabel = ""
698 ylabel = "Range (Km)"
697 ylabel = "Range (Km)"
699
698
700 update_figfile = False
699 update_figfile = False
701
700
702 if not self.isConfig:
701 if not self.isConfig:
703
702
704 nchan = len(channelIndexList)
703 nchan = len(channelIndexList)
705 self.nchan = nchan
704 self.nchan = nchan
706 self.plotFact = 1
705 self.plotFact = 1
707 nplots = nchan
706 nplots = nchan
708
707
709 if showSNR:
708 if showSNR:
710 nplots = nchan*2
709 nplots = nchan*2
711 self.plotFact = 2
710 self.plotFact = 2
712 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
711 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
713 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
712 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
714
713
715 self.setup(id=id,
714 self.setup(id=id,
716 nplots=nplots,
715 nplots=nplots,
717 wintitle=wintitle,
716 wintitle=wintitle,
718 show=show)
717 show=show)
719
718
720 if timerange != None:
719 if timerange != None:
721 self.timerange = timerange
720 self.timerange = timerange
722
721
723 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
722 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
724
723
725 if ymin == None: ymin = numpy.nanmin(y)
724 if ymin == None: ymin = numpy.nanmin(y)
726 if ymax == None: ymax = numpy.nanmax(y)
725 if ymax == None: ymax = numpy.nanmax(y)
727 if zmin == None: zmin = numpy.nanmin(z)
726 if zmin == None: zmin = numpy.nanmin(z)
728 if zmax == None: zmax = numpy.nanmax(z)
727 if zmax == None: zmax = numpy.nanmax(z)
729
728
730 self.FTP_WEI = ftp_wei
729 self.FTP_WEI = ftp_wei
731 self.EXP_CODE = exp_code
730 self.EXP_CODE = exp_code
732 self.SUB_EXP_CODE = sub_exp_code
731 self.SUB_EXP_CODE = sub_exp_code
733 self.PLOT_POS = plot_pos
732 self.PLOT_POS = plot_pos
734
733
735 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
734 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
736 self.isConfig = True
735 self.isConfig = True
737 self.figfile = figfile
736 self.figfile = figfile
738 update_figfile = True
737 update_figfile = True
739
738
740 self.setWinTitle(title)
739 self.setWinTitle(title)
741
740
742 for i in range(self.nchan):
741 for i in range(self.nchan):
743 index = channelIndexList[i]
742 index = channelIndexList[i]
744 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
743 title = "Channel %d: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
745 axes = self.axesList[i*self.plotFact]
744 axes = self.axesList[i*self.plotFact]
746 z1 = z[i,:].reshape((1,-1))
745 z1 = z[i,:].reshape((1,-1))
747 axes.pcolorbuffer(x, y, z1,
746 axes.pcolorbuffer(x, y, z1,
748 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
747 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
749 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
748 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
750 ticksize=9, cblabel='', cbsize="1%",colormap=colormap)
749 ticksize=9, cblabel='', cbsize="1%",colormap=colormap)
751
750
752 if showSNR:
751 if showSNR:
753 title = "Channel %d SNR: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
752 title = "Channel %d SNR: %s" %(dataOut.channelList[index], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
754 axes = self.axesList[i*self.plotFact + 1]
753 axes = self.axesList[i*self.plotFact + 1]
755 SNRdB1 = SNRdB[i,:].reshape((1,-1))
754 SNRdB1 = SNRdB[i,:].reshape((1,-1))
756 axes.pcolorbuffer(x, y, SNRdB1,
755 axes.pcolorbuffer(x, y, SNRdB1,
757 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
756 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
758 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
757 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
759 ticksize=9, cblabel='', cbsize="1%",colormap='jet')
758 ticksize=9, cblabel='', cbsize="1%",colormap='jet')
760
759
761
760
762 self.draw()
761 self.draw()
763
762
764 if dataOut.ltctime >= self.xmax:
763 if dataOut.ltctime >= self.xmax:
765 self.counter_imagwr = wr_period
764 self.counter_imagwr = wr_period
766 self.isConfig = False
765 self.isConfig = False
767 update_figfile = True
766 update_figfile = True
768
767
769 self.save(figpath=figpath,
768 self.save(figpath=figpath,
770 figfile=figfile,
769 figfile=figfile,
771 save=save,
770 save=save,
772 ftp=ftp,
771 ftp=ftp,
773 wr_period=wr_period,
772 wr_period=wr_period,
774 thisDatetime=thisDatetime,
773 thisDatetime=thisDatetime,
775 update_figfile=update_figfile)
774 update_figfile=update_figfile)
776
775
777
776
778
777
779 class Parameters1Plot(Figure):
778 class Parameters1Plot(Figure):
780
779
781 __isConfig = None
780 __isConfig = None
782 __nsubplots = None
781 __nsubplots = None
783
782
784 WIDTHPROF = None
783 WIDTHPROF = None
785 HEIGHTPROF = None
784 HEIGHTPROF = None
786 PREFIX = 'prm'
785 PREFIX = 'prm'
787
786
788 def __init__(self, **kwargs):
787 def __init__(self, **kwargs):
789 Figure.__init__(self, **kwargs)
788 Figure.__init__(self, **kwargs)
790 self.timerange = 2*60*60
789 self.timerange = 2*60*60
791 self.isConfig = False
790 self.isConfig = False
792 self.__nsubplots = 1
791 self.__nsubplots = 1
793
792
794 self.WIDTH = 800
793 self.WIDTH = 800
795 self.HEIGHT = 150
794 self.HEIGHT = 180
796 self.WIDTHPROF = 120
795 self.WIDTHPROF = 120
797 self.HEIGHTPROF = 0
796 self.HEIGHTPROF = 0
798 self.counter_imagwr = 0
797 self.counter_imagwr = 0
799
798
800 self.PLOT_CODE = PARMS_CODE
799 self.PLOT_CODE = PARMS_CODE
801
800
802 self.FTP_WEI = None
801 self.FTP_WEI = None
803 self.EXP_CODE = None
802 self.EXP_CODE = None
804 self.SUB_EXP_CODE = None
803 self.SUB_EXP_CODE = None
805 self.PLOT_POS = None
804 self.PLOT_POS = None
806 self.tmin = None
805 self.tmin = None
807 self.tmax = None
806 self.tmax = None
808
807
809 self.xmin = None
808 self.xmin = None
810 self.xmax = None
809 self.xmax = None
811
810
812 self.figfile = None
811 self.figfile = None
813
812
814 def getSubplots(self):
813 def getSubplots(self):
815
814
816 ncol = 1
815 ncol = 1
817 nrow = self.nplots
816 nrow = self.nplots
818
817
819 return nrow, ncol
818 return nrow, ncol
820
819
821 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
820 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
822
821
823 self.__showprofile = showprofile
822 self.__showprofile = showprofile
824 self.nplots = nplots
823 self.nplots = nplots
825
824
826 ncolspan = 1
825 ncolspan = 1
827 colspan = 1
826 colspan = 1
828
827
829 self.createFigure(id = id,
828 self.createFigure(id = id,
830 wintitle = wintitle,
829 wintitle = wintitle,
831 widthplot = self.WIDTH + self.WIDTHPROF,
830 widthplot = self.WIDTH + self.WIDTHPROF,
832 heightplot = self.HEIGHT + self.HEIGHTPROF,
831 heightplot = self.HEIGHT + self.HEIGHTPROF,
833 show=show)
832 show=show)
834
833
835 nrow, ncol = self.getSubplots()
834 nrow, ncol = self.getSubplots()
836
835
837 counter = 0
836 counter = 0
838 for y in range(nrow):
837 for y in range(nrow):
839 for x in range(ncol):
838 for x in range(ncol):
840
839
841 if counter >= self.nplots:
840 if counter >= self.nplots:
842 break
841 break
843
842
844 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
843 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
845
844
846 if showprofile:
845 if showprofile:
847 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
846 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
848
847
849 counter += 1
848 counter += 1
850
849
851 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
850 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
852 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
851 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
853 parameterIndex = None, onlyPositive = False,
852 parameterIndex = None, onlyPositive = False,
854 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None, onlySNR = False,
853 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None, onlySNR = False,
855 DOP = True,
854 DOP = True,
856 zlabel = "", parameterName = "", parameterObject = "data_param",
855 zlabel = "", parameterName = "", parameterObject = "data_param",
857 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
856 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
858 server=None, folder=None, username=None, password=None,
857 server=None, folder=None, username=None, password=None,
859 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
858 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
860
859 #print inspect.getargspec(self.run).args
861 """
860 """
862
861
863 Input:
862 Input:
864 dataOut :
863 dataOut :
865 id :
864 id :
866 wintitle :
865 wintitle :
867 channelList :
866 channelList :
868 showProfile :
867 showProfile :
869 xmin : None,
868 xmin : None,
870 xmax : None,
869 xmax : None,
871 ymin : None,
870 ymin : None,
872 ymax : None,
871 ymax : None,
873 zmin : None,
872 zmin : None,
874 zmax : None
873 zmax : None
875 """
874 """
876
875
877 data_param = getattr(dataOut, parameterObject)
876 data_param = getattr(dataOut, parameterObject)
878
877
879 if channelList == None:
878 if channelList == None:
880 channelIndexList = numpy.arange(data_param.shape[0])
879 channelIndexList = numpy.arange(data_param.shape[0])
881 else:
880 else:
882 channelIndexList = numpy.array(channelList)
881 channelIndexList = numpy.array(channelList)
883
882
884 nchan = len(channelIndexList) #Number of channels being plotted
883 nchan = len(channelIndexList) #Number of channels being plotted
885
884
886 if nchan < 1:
885 if nchan < 1:
887 return
886 return
888
887
889 nGraphsByChannel = 0
888 nGraphsByChannel = 0
890
889
891 if SNR:
890 if SNR:
892 nGraphsByChannel += 1
891 nGraphsByChannel += 1
893 if DOP:
892 if DOP:
894 nGraphsByChannel += 1
893 nGraphsByChannel += 1
895
894
896 if nGraphsByChannel < 1:
895 if nGraphsByChannel < 1:
897 return
896 return
898
897
899 nplots = nGraphsByChannel*nchan
898 nplots = nGraphsByChannel*nchan
900
899
901 if timerange is not None:
900 if timerange is not None:
902 self.timerange = timerange
901 self.timerange = timerange
903
902
904 #tmin = None
903 #tmin = None
905 #tmax = None
904 #tmax = None
906 if parameterIndex == None:
905 if parameterIndex == None:
907 parameterIndex = 1
906 parameterIndex = 1
908
907
909 x = dataOut.getTimeRange1(dataOut.paramInterval)
908 x = dataOut.getTimeRange1(dataOut.paramInterval)
910 y = dataOut.heightList
909 y = dataOut.heightList
911 z = data_param[channelIndexList,parameterIndex,:].copy()
910 z = data_param[channelIndexList,parameterIndex,:].copy()
912
911
913 zRange = dataOut.abscissaList
912 zRange = dataOut.abscissaList
914 # nChannels = z.shape[0] #Number of wind dimensions estimated
913 # nChannels = z.shape[0] #Number of wind dimensions estimated
915 # thisDatetime = dataOut.datatime
914 # thisDatetime = dataOut.datatime
916
915
917 if dataOut.data_SNR is not None:
916 if dataOut.data_SNR is not None:
918 SNRarray = dataOut.data_SNR[channelIndexList,:]
917 SNRarray = dataOut.data_SNR[channelIndexList,:]
919 SNRdB = 10*numpy.log10(SNRarray)
918 SNRdB = 10*numpy.log10(SNRarray)
920 # SNRavgdB = 10*numpy.log10(SNRavg)
919 # SNRavgdB = 10*numpy.log10(SNRavg)
921 ind = numpy.where(SNRdB < 10**(SNRthresh/10))
920 ind = numpy.where(SNRdB < 10**(SNRthresh/10))
922 z[ind] = numpy.nan
921 z[ind] = numpy.nan
923
922
924 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
923 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
925 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
924 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
926 xlabel = ""
925 xlabel = ""
927 ylabel = "Range (Km)"
926 ylabel = "Range (Km)"
928
927
929 if (SNR and not onlySNR): nplots = 2*nplots
928 if (SNR and not onlySNR): nplots = 2*nplots
930
929
931 if onlyPositive:
930 if onlyPositive:
932 colormap = "jet"
931 colormap = "jet"
933 zmin = 0
932 zmin = 0
934 else: colormap = "RdBu_r"
933 else: colormap = "RdBu_r"
935
934
936 if not self.isConfig:
935 if not self.isConfig:
937
936
938 self.setup(id=id,
937 self.setup(id=id,
939 nplots=nplots,
938 nplots=nplots,
940 wintitle=wintitle,
939 wintitle=wintitle,
941 showprofile=showprofile,
940 showprofile=showprofile,
942 show=show)
941 show=show)
943
942
944 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
943 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
945
944
946 if ymin == None: ymin = numpy.nanmin(y)
945 if ymin == None: ymin = numpy.nanmin(y)
947 if ymax == None: ymax = numpy.nanmax(y)
946 if ymax == None: ymax = numpy.nanmax(y)
948 if zmin == None: zmin = numpy.nanmin(zRange)
947 if zmin == None: zmin = numpy.nanmin(zRange)
949 if zmax == None: zmax = numpy.nanmax(zRange)
948 if zmax == None: zmax = numpy.nanmax(zRange)
950
949
951 if SNR:
950 if SNR:
952 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
951 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
953 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
952 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
954
953
955 self.FTP_WEI = ftp_wei
954 self.FTP_WEI = ftp_wei
956 self.EXP_CODE = exp_code
955 self.EXP_CODE = exp_code
957 self.SUB_EXP_CODE = sub_exp_code
956 self.SUB_EXP_CODE = sub_exp_code
958 self.PLOT_POS = plot_pos
957 self.PLOT_POS = plot_pos
959
958
960 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
959 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
961 self.isConfig = True
960 self.isConfig = True
962 self.figfile = figfile
961 self.figfile = figfile
963
962
964 self.setWinTitle(title)
963 self.setWinTitle(title)
965
964
966 if ((self.xmax - x[1]) < (x[1]-x[0])):
965 if ((self.xmax - x[1]) < (x[1]-x[0])):
967 x[1] = self.xmax
966 x[1] = self.xmax
968
967
969 for i in range(nchan):
968 for i in range(nchan):
970
969
971 if (SNR and not onlySNR): j = 2*i
970 if (SNR and not onlySNR): j = 2*i
972 else: j = i
971 else: j = i
973
972
974 j = nGraphsByChannel*i
973 j = nGraphsByChannel*i
975
974
976 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
975 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
977 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
976 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
978
977
979 if not onlySNR:
978 if not onlySNR:
980 axes = self.axesList[j*self.__nsubplots]
979 axes = self.axesList[j*self.__nsubplots]
981 z1 = z[i,:].reshape((1,-1))
980 z1 = z[i,:].reshape((1,-1))
982 axes.pcolorbuffer(x, y, z1,
981 axes.pcolorbuffer(x, y, z1,
983 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
982 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
984 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
983 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
985 ticksize=9, cblabel=zlabel, cbsize="1%")
984 ticksize=9, cblabel=zlabel, cbsize="1%")
986
985
987 if DOP:
986 if DOP:
988 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
987 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
989
988
990 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
989 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
991 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
990 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
992 axes = self.axesList[j]
991 axes = self.axesList[j]
993 z1 = z[i,:].reshape((1,-1))
992 z1 = z[i,:].reshape((1,-1))
994 axes.pcolorbuffer(x, y, z1,
993 axes.pcolorbuffer(x, y, z1,
995 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
994 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
996 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
995 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
997 ticksize=9, cblabel=zlabel, cbsize="1%")
996 ticksize=9, cblabel=zlabel, cbsize="1%")
998
997
999 if SNR:
998 if SNR:
1000 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
999 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1001 axes = self.axesList[(j)*self.__nsubplots]
1000 axes = self.axesList[(j)*self.__nsubplots]
1002 if not onlySNR:
1001 if not onlySNR:
1003 axes = self.axesList[(j + 1)*self.__nsubplots]
1002 axes = self.axesList[(j + 1)*self.__nsubplots]
1004
1003
1005 axes = self.axesList[(j + nGraphsByChannel-1)]
1004 axes = self.axesList[(j + nGraphsByChannel-1)]
1006
1005
1007 z1 = SNRdB[i,:].reshape((1,-1))
1006 z1 = SNRdB[i,:].reshape((1,-1))
1008 axes.pcolorbuffer(x, y, z1,
1007 axes.pcolorbuffer(x, y, z1,
1009 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1008 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1010 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
1009 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
1011 ticksize=9, cblabel=zlabel, cbsize="1%")
1010 ticksize=9, cblabel=zlabel, cbsize="1%")
1012
1011
1013
1012
1014
1013
1015 self.draw()
1014 self.draw()
1016
1015
1017 if x[1] >= self.axesList[0].xmax:
1016 if x[1] >= self.axesList[0].xmax:
1018 self.counter_imagwr = wr_period
1017 self.counter_imagwr = wr_period
1019 self.isConfig = False
1018 self.isConfig = False
1020 self.figfile = None
1019 self.figfile = None
1021
1020
1022 self.save(figpath=figpath,
1021 self.save(figpath=figpath,
1023 figfile=figfile,
1022 figfile=figfile,
1024 save=save,
1023 save=save,
1025 ftp=ftp,
1024 ftp=ftp,
1026 wr_period=wr_period,
1025 wr_period=wr_period,
1027 thisDatetime=thisDatetime,
1026 thisDatetime=thisDatetime,
1028 update_figfile=False)
1027 update_figfile=False)
1029
1028
1030 class SpectralFittingPlot(Figure):
1029 class SpectralFittingPlot(Figure):
1031
1030
1032 __isConfig = None
1031 __isConfig = None
1033 __nsubplots = None
1032 __nsubplots = None
1034
1033
1035 WIDTHPROF = None
1034 WIDTHPROF = None
1036 HEIGHTPROF = None
1035 HEIGHTPROF = None
1037 PREFIX = 'prm'
1036 PREFIX = 'prm'
1038
1037
1039
1038
1040 N = None
1039 N = None
1041 ippSeconds = None
1040 ippSeconds = None
1042
1041
1043 def __init__(self, **kwargs):
1042 def __init__(self, **kwargs):
1044 Figure.__init__(self, **kwargs)
1043 Figure.__init__(self, **kwargs)
1045 self.isConfig = False
1044 self.isConfig = False
1046 self.__nsubplots = 1
1045 self.__nsubplots = 1
1047
1046
1048 self.PLOT_CODE = SPECFIT_CODE
1047 self.PLOT_CODE = SPECFIT_CODE
1049
1048
1050 self.WIDTH = 450
1049 self.WIDTH = 450
1051 self.HEIGHT = 250
1050 self.HEIGHT = 250
1052 self.WIDTHPROF = 0
1051 self.WIDTHPROF = 0
1053 self.HEIGHTPROF = 0
1052 self.HEIGHTPROF = 0
1054
1053
1055 def getSubplots(self):
1054 def getSubplots(self):
1056
1055
1057 ncol = int(numpy.sqrt(self.nplots)+0.9)
1056 ncol = int(numpy.sqrt(self.nplots)+0.9)
1058 nrow = int(self.nplots*1./ncol + 0.9)
1057 nrow = int(self.nplots*1./ncol + 0.9)
1059
1058
1060 return nrow, ncol
1059 return nrow, ncol
1061
1060
1062 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
1061 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
1063
1062
1064 showprofile = False
1063 showprofile = False
1065 self.__showprofile = showprofile
1064 self.__showprofile = showprofile
1066 self.nplots = nplots
1065 self.nplots = nplots
1067
1066
1068 ncolspan = 5
1067 ncolspan = 5
1069 colspan = 4
1068 colspan = 4
1070 if showprofile:
1069 if showprofile:
1071 ncolspan = 5
1070 ncolspan = 5
1072 colspan = 4
1071 colspan = 4
1073 self.__nsubplots = 2
1072 self.__nsubplots = 2
1074
1073
1075 self.createFigure(id = id,
1074 self.createFigure(id = id,
1076 wintitle = wintitle,
1075 wintitle = wintitle,
1077 widthplot = self.WIDTH + self.WIDTHPROF,
1076 widthplot = self.WIDTH + self.WIDTHPROF,
1078 heightplot = self.HEIGHT + self.HEIGHTPROF,
1077 heightplot = self.HEIGHT + self.HEIGHTPROF,
1079 show=show)
1078 show=show)
1080
1079
1081 nrow, ncol = self.getSubplots()
1080 nrow, ncol = self.getSubplots()
1082
1081
1083 counter = 0
1082 counter = 0
1084 for y in range(nrow):
1083 for y in range(nrow):
1085 for x in range(ncol):
1084 for x in range(ncol):
1086
1085
1087 if counter >= self.nplots:
1086 if counter >= self.nplots:
1088 break
1087 break
1089
1088
1090 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1089 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1091
1090
1092 if showprofile:
1091 if showprofile:
1093 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1092 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
1094
1093
1095 counter += 1
1094 counter += 1
1096
1095
1097 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
1096 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
1098 xmin=None, xmax=None, ymin=None, ymax=None,
1097 xmin=None, xmax=None, ymin=None, ymax=None,
1099 save=False, figpath='./', figfile=None, show=True):
1098 save=False, figpath='./', figfile=None, show=True):
1100
1099
1101 """
1100 """
1102
1101
1103 Input:
1102 Input:
1104 dataOut :
1103 dataOut :
1105 id :
1104 id :
1106 wintitle :
1105 wintitle :
1107 channelList :
1106 channelList :
1108 showProfile :
1107 showProfile :
1109 xmin : None,
1108 xmin : None,
1110 xmax : None,
1109 xmax : None,
1111 zmin : None,
1110 zmin : None,
1112 zmax : None
1111 zmax : None
1113 """
1112 """
1114
1113
1115 if cutHeight==None:
1114 if cutHeight==None:
1116 h=270
1115 h=270
1117 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
1116 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
1118 cutHeight = dataOut.heightList[heightindex]
1117 cutHeight = dataOut.heightList[heightindex]
1119
1118
1120 factor = dataOut.normFactor
1119 factor = dataOut.normFactor
1121 x = dataOut.abscissaList[:-1]
1120 x = dataOut.abscissaList[:-1]
1122 #y = dataOut.getHeiRange()
1121 #y = dataOut.getHeiRange()
1123
1122
1124 z = dataOut.data_pre[:,:,heightindex]/factor
1123 z = dataOut.data_pre[:,:,heightindex]/factor
1125 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1124 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
1126 avg = numpy.average(z, axis=1)
1125 avg = numpy.average(z, axis=1)
1127 listChannels = z.shape[0]
1126 listChannels = z.shape[0]
1128
1127
1129 #Reconstruct Function
1128 #Reconstruct Function
1130 if fit==True:
1129 if fit==True:
1131 groupArray = dataOut.groupList
1130 groupArray = dataOut.groupList
1132 listChannels = groupArray.reshape((groupArray.size))
1131 listChannels = groupArray.reshape((groupArray.size))
1133 listChannels.sort()
1132 listChannels.sort()
1134 spcFitLine = numpy.zeros(z.shape)
1133 spcFitLine = numpy.zeros(z.shape)
1135 constants = dataOut.constants
1134 constants = dataOut.constants
1136
1135
1137 nGroups = groupArray.shape[0]
1136 nGroups = groupArray.shape[0]
1138 nChannels = groupArray.shape[1]
1137 nChannels = groupArray.shape[1]
1139 nProfiles = z.shape[1]
1138 nProfiles = z.shape[1]
1140
1139
1141 for f in range(nGroups):
1140 for f in range(nGroups):
1142 groupChann = groupArray[f,:]
1141 groupChann = groupArray[f,:]
1143 p = dataOut.data_param[f,:,heightindex]
1142 p = dataOut.data_param[f,:,heightindex]
1144 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
1143 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
1145 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
1144 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
1146 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
1145 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
1147 spcFitLine[groupChann,:] = fitLineAux
1146 spcFitLine[groupChann,:] = fitLineAux
1148 # spcFitLine = spcFitLine/factor
1147 # spcFitLine = spcFitLine/factor
1149
1148
1150 z = z[listChannels,:]
1149 z = z[listChannels,:]
1151 spcFitLine = spcFitLine[listChannels,:]
1150 spcFitLine = spcFitLine[listChannels,:]
1152 spcFitLinedB = 10*numpy.log10(spcFitLine)
1151 spcFitLinedB = 10*numpy.log10(spcFitLine)
1153
1152
1154 zdB = 10*numpy.log10(z)
1153 zdB = 10*numpy.log10(z)
1155 #thisDatetime = dataOut.datatime
1154 #thisDatetime = dataOut.datatime
1156 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1155 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1157 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1156 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
1158 xlabel = "Velocity (m/s)"
1157 xlabel = "Velocity (m/s)"
1159 ylabel = "Spectrum"
1158 ylabel = "Spectrum"
1160
1159
1161 if not self.isConfig:
1160 if not self.isConfig:
1162
1161
1163 nplots = listChannels.size
1162 nplots = listChannels.size
1164
1163
1165 self.setup(id=id,
1164 self.setup(id=id,
1166 nplots=nplots,
1165 nplots=nplots,
1167 wintitle=wintitle,
1166 wintitle=wintitle,
1168 showprofile=showprofile,
1167 showprofile=showprofile,
1169 show=show)
1168 show=show)
1170
1169
1171 if xmin == None: xmin = numpy.nanmin(x)
1170 if xmin == None: xmin = numpy.nanmin(x)
1172 if xmax == None: xmax = numpy.nanmax(x)
1171 if xmax == None: xmax = numpy.nanmax(x)
1173 if ymin == None: ymin = numpy.nanmin(zdB)
1172 if ymin == None: ymin = numpy.nanmin(zdB)
1174 if ymax == None: ymax = numpy.nanmax(zdB)+2
1173 if ymax == None: ymax = numpy.nanmax(zdB)+2
1175
1174
1176 self.isConfig = True
1175 self.isConfig = True
1177
1176
1178 self.setWinTitle(title)
1177 self.setWinTitle(title)
1179 for i in range(self.nplots):
1178 for i in range(self.nplots):
1180 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
1179 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
1181 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i])
1180 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i])
1182 axes = self.axesList[i*self.__nsubplots]
1181 axes = self.axesList[i*self.__nsubplots]
1183 if fit == False:
1182 if fit == False:
1184 axes.pline(x, zdB[i,:],
1183 axes.pline(x, zdB[i,:],
1185 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1184 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1186 xlabel=xlabel, ylabel=ylabel, title=title
1185 xlabel=xlabel, ylabel=ylabel, title=title
1187 )
1186 )
1188 if fit == True:
1187 if fit == True:
1189 fitline=spcFitLinedB[i,:]
1188 fitline=spcFitLinedB[i,:]
1190 y=numpy.vstack([zdB[i,:],fitline] )
1189 y=numpy.vstack([zdB[i,:],fitline] )
1191 legendlabels=['Data','Fitting']
1190 legendlabels=['Data','Fitting']
1192 axes.pmultilineyaxis(x, y,
1191 axes.pmultilineyaxis(x, y,
1193 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1192 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
1194 xlabel=xlabel, ylabel=ylabel, title=title,
1193 xlabel=xlabel, ylabel=ylabel, title=title,
1195 legendlabels=legendlabels, marker=None,
1194 legendlabels=legendlabels, marker=None,
1196 linestyle='solid', grid='both')
1195 linestyle='solid', grid='both')
1197
1196
1198 self.draw()
1197 self.draw()
1199
1198
1200 self.save(figpath=figpath,
1199 self.save(figpath=figpath,
1201 figfile=figfile,
1200 figfile=figfile,
1202 save=save,
1201 save=save,
1203 ftp=ftp,
1202 ftp=ftp,
1204 wr_period=wr_period,
1203 wr_period=wr_period,
1205 thisDatetime=thisDatetime)
1204 thisDatetime=thisDatetime)
1206
1205
1207
1206
1208 class EWDriftsPlot(Figure):
1207 class EWDriftsPlot(Figure):
1209
1208
1210 __isConfig = None
1209 __isConfig = None
1211 __nsubplots = None
1210 __nsubplots = None
1212
1211
1213 WIDTHPROF = None
1212 WIDTHPROF = None
1214 HEIGHTPROF = None
1213 HEIGHTPROF = None
1215 PREFIX = 'drift'
1214 PREFIX = 'drift'
1216
1215
1217 def __init__(self, **kwargs):
1216 def __init__(self, **kwargs):
1218 Figure.__init__(self, **kwargs)
1217 Figure.__init__(self, **kwargs)
1219 self.timerange = 2*60*60
1218 self.timerange = 2*60*60
1220 self.isConfig = False
1219 self.isConfig = False
1221 self.__nsubplots = 1
1220 self.__nsubplots = 1
1222
1221
1223 self.WIDTH = 800
1222 self.WIDTH = 800
1224 self.HEIGHT = 150
1223 self.HEIGHT = 150
1225 self.WIDTHPROF = 120
1224 self.WIDTHPROF = 120
1226 self.HEIGHTPROF = 0
1225 self.HEIGHTPROF = 0
1227 self.counter_imagwr = 0
1226 self.counter_imagwr = 0
1228
1227
1229 self.PLOT_CODE = EWDRIFT_CODE
1228 self.PLOT_CODE = EWDRIFT_CODE
1230
1229
1231 self.FTP_WEI = None
1230 self.FTP_WEI = None
1232 self.EXP_CODE = None
1231 self.EXP_CODE = None
1233 self.SUB_EXP_CODE = None
1232 self.SUB_EXP_CODE = None
1234 self.PLOT_POS = None
1233 self.PLOT_POS = None
1235 self.tmin = None
1234 self.tmin = None
1236 self.tmax = None
1235 self.tmax = None
1237
1236
1238 self.xmin = None
1237 self.xmin = None
1239 self.xmax = None
1238 self.xmax = None
1240
1239
1241 self.figfile = None
1240 self.figfile = None
1242
1241
1243 def getSubplots(self):
1242 def getSubplots(self):
1244
1243
1245 ncol = 1
1244 ncol = 1
1246 nrow = self.nplots
1245 nrow = self.nplots
1247
1246
1248 return nrow, ncol
1247 return nrow, ncol
1249
1248
1250 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1249 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1251
1250
1252 self.__showprofile = showprofile
1251 self.__showprofile = showprofile
1253 self.nplots = nplots
1252 self.nplots = nplots
1254
1253
1255 ncolspan = 1
1254 ncolspan = 1
1256 colspan = 1
1255 colspan = 1
1257
1256
1258 self.createFigure(id = id,
1257 self.createFigure(id = id,
1259 wintitle = wintitle,
1258 wintitle = wintitle,
1260 widthplot = self.WIDTH + self.WIDTHPROF,
1259 widthplot = self.WIDTH + self.WIDTHPROF,
1261 heightplot = self.HEIGHT + self.HEIGHTPROF,
1260 heightplot = self.HEIGHT + self.HEIGHTPROF,
1262 show=show)
1261 show=show)
1263
1262
1264 nrow, ncol = self.getSubplots()
1263 nrow, ncol = self.getSubplots()
1265
1264
1266 counter = 0
1265 counter = 0
1267 for y in range(nrow):
1266 for y in range(nrow):
1268 if counter >= self.nplots:
1267 if counter >= self.nplots:
1269 break
1268 break
1270
1269
1271 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1270 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1272 counter += 1
1271 counter += 1
1273
1272
1274 def run(self, dataOut, id, wintitle="", channelList=None,
1273 def run(self, dataOut, id, wintitle="", channelList=None,
1275 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1274 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1276 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1275 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1277 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1276 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1278 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1277 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1279 server=None, folder=None, username=None, password=None,
1278 server=None, folder=None, username=None, password=None,
1280 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1279 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1281 """
1280 """
1282
1281
1283 Input:
1282 Input:
1284 dataOut :
1283 dataOut :
1285 id :
1284 id :
1286 wintitle :
1285 wintitle :
1287 channelList :
1286 channelList :
1288 showProfile :
1287 showProfile :
1289 xmin : None,
1288 xmin : None,
1290 xmax : None,
1289 xmax : None,
1291 ymin : None,
1290 ymin : None,
1292 ymax : None,
1291 ymax : None,
1293 zmin : None,
1292 zmin : None,
1294 zmax : None
1293 zmax : None
1295 """
1294 """
1296
1295
1297 if timerange is not None:
1296 if timerange is not None:
1298 self.timerange = timerange
1297 self.timerange = timerange
1299
1298
1300 tmin = None
1299 tmin = None
1301 tmax = None
1300 tmax = None
1302
1301
1303 x = dataOut.getTimeRange1(dataOut.outputInterval)
1302 x = dataOut.getTimeRange1(dataOut.outputInterval)
1304 # y = dataOut.heightList
1303 # y = dataOut.heightList
1305 y = dataOut.heightList
1304 y = dataOut.heightList
1306
1305
1307 z = dataOut.data_output
1306 z = dataOut.data_output
1308 nplots = z.shape[0] #Number of wind dimensions estimated
1307 nplots = z.shape[0] #Number of wind dimensions estimated
1309 nplotsw = nplots
1308 nplotsw = nplots
1310
1309
1311 #If there is a SNR function defined
1310 #If there is a SNR function defined
1312 if dataOut.data_SNR is not None:
1311 if dataOut.data_SNR is not None:
1313 nplots += 1
1312 nplots += 1
1314 SNR = dataOut.data_SNR
1313 SNR = dataOut.data_SNR
1315
1314
1316 if SNR_1:
1315 if SNR_1:
1317 SNR += 1
1316 SNR += 1
1318
1317
1319 SNRavg = numpy.average(SNR, axis=0)
1318 SNRavg = numpy.average(SNR, axis=0)
1320
1319
1321 SNRdB = 10*numpy.log10(SNR)
1320 SNRdB = 10*numpy.log10(SNR)
1322 SNRavgdB = 10*numpy.log10(SNRavg)
1321 SNRavgdB = 10*numpy.log10(SNRavg)
1323
1322
1324 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1323 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1325
1324
1326 for i in range(nplotsw):
1325 for i in range(nplotsw):
1327 z[i,ind] = numpy.nan
1326 z[i,ind] = numpy.nan
1328
1327
1329
1328
1330 showprofile = False
1329 showprofile = False
1331 # thisDatetime = dataOut.datatime
1330 # thisDatetime = dataOut.datatime
1332 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1331 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1333 title = wintitle + " EW Drifts"
1332 title = wintitle + " EW Drifts"
1334 xlabel = ""
1333 xlabel = ""
1335 ylabel = "Height (Km)"
1334 ylabel = "Height (Km)"
1336
1335
1337 if not self.isConfig:
1336 if not self.isConfig:
1338
1337
1339 self.setup(id=id,
1338 self.setup(id=id,
1340 nplots=nplots,
1339 nplots=nplots,
1341 wintitle=wintitle,
1340 wintitle=wintitle,
1342 showprofile=showprofile,
1341 showprofile=showprofile,
1343 show=show)
1342 show=show)
1344
1343
1345 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1344 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1346
1345
1347 if ymin == None: ymin = numpy.nanmin(y)
1346 if ymin == None: ymin = numpy.nanmin(y)
1348 if ymax == None: ymax = numpy.nanmax(y)
1347 if ymax == None: ymax = numpy.nanmax(y)
1349
1348
1350 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1349 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1351 if zminZonal == None: zminZonal = -zmaxZonal
1350 if zminZonal == None: zminZonal = -zmaxZonal
1352 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1351 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1353 if zminVertical == None: zminVertical = -zmaxVertical
1352 if zminVertical == None: zminVertical = -zmaxVertical
1354
1353
1355 if dataOut.data_SNR is not None:
1354 if dataOut.data_SNR is not None:
1356 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1355 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1357 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1356 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1358
1357
1359 self.FTP_WEI = ftp_wei
1358 self.FTP_WEI = ftp_wei
1360 self.EXP_CODE = exp_code
1359 self.EXP_CODE = exp_code
1361 self.SUB_EXP_CODE = sub_exp_code
1360 self.SUB_EXP_CODE = sub_exp_code
1362 self.PLOT_POS = plot_pos
1361 self.PLOT_POS = plot_pos
1363
1362
1364 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1363 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1365 self.isConfig = True
1364 self.isConfig = True
1366
1365
1367
1366
1368 self.setWinTitle(title)
1367 self.setWinTitle(title)
1369
1368
1370 if ((self.xmax - x[1]) < (x[1]-x[0])):
1369 if ((self.xmax - x[1]) < (x[1]-x[0])):
1371 x[1] = self.xmax
1370 x[1] = self.xmax
1372
1371
1373 strWind = ['Zonal','Vertical']
1372 strWind = ['Zonal','Vertical']
1374 strCb = 'Velocity (m/s)'
1373 strCb = 'Velocity (m/s)'
1375 zmaxVector = [zmaxZonal, zmaxVertical]
1374 zmaxVector = [zmaxZonal, zmaxVertical]
1376 zminVector = [zminZonal, zminVertical]
1375 zminVector = [zminZonal, zminVertical]
1377
1376
1378 for i in range(nplotsw):
1377 for i in range(nplotsw):
1379
1378
1380 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1379 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1381 axes = self.axesList[i*self.__nsubplots]
1380 axes = self.axesList[i*self.__nsubplots]
1382
1381
1383 z1 = z[i,:].reshape((1,-1))
1382 z1 = z[i,:].reshape((1,-1))
1384
1383
1385 axes.pcolorbuffer(x, y, z1,
1384 axes.pcolorbuffer(x, y, z1,
1386 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1385 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1387 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1386 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1388 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1387 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1389
1388
1390 if dataOut.data_SNR is not None:
1389 if dataOut.data_SNR is not None:
1391 i += 1
1390 i += 1
1392 if SNR_1:
1391 if SNR_1:
1393 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1392 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1394 else:
1393 else:
1395 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1394 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1396 axes = self.axesList[i*self.__nsubplots]
1395 axes = self.axesList[i*self.__nsubplots]
1397 SNRavgdB = SNRavgdB.reshape((1,-1))
1396 SNRavgdB = SNRavgdB.reshape((1,-1))
1398
1397
1399 axes.pcolorbuffer(x, y, SNRavgdB,
1398 axes.pcolorbuffer(x, y, SNRavgdB,
1400 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1399 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1401 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1400 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1402 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1401 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1403
1402
1404 self.draw()
1403 self.draw()
1405
1404
1406 if x[1] >= self.axesList[0].xmax:
1405 if x[1] >= self.axesList[0].xmax:
1407 self.counter_imagwr = wr_period
1406 self.counter_imagwr = wr_period
1408 self.isConfig = False
1407 self.isConfig = False
1409 self.figfile = None
1408 self.figfile = None
1410
1409
1411
1410
1412
1411
1413
1412
1414 class PhasePlot(Figure):
1413 class PhasePlot(Figure):
1415
1414
1416 __isConfig = None
1415 __isConfig = None
1417 __nsubplots = None
1416 __nsubplots = None
1418
1417
1419 PREFIX = 'mphase'
1418 PREFIX = 'mphase'
1420
1419
1421 def __init__(self, **kwargs):
1420 def __init__(self, **kwargs):
1422 Figure.__init__(self, **kwargs)
1421 Figure.__init__(self, **kwargs)
1423 self.timerange = 24*60*60
1422 self.timerange = 24*60*60
1424 self.isConfig = False
1423 self.isConfig = False
1425 self.__nsubplots = 1
1424 self.__nsubplots = 1
1426 self.counter_imagwr = 0
1425 self.counter_imagwr = 0
1427 self.WIDTH = 600
1426 self.WIDTH = 600
1428 self.HEIGHT = 300
1427 self.HEIGHT = 300
1429 self.WIDTHPROF = 120
1428 self.WIDTHPROF = 120
1430 self.HEIGHTPROF = 0
1429 self.HEIGHTPROF = 0
1431 self.xdata = None
1430 self.xdata = None
1432 self.ydata = None
1431 self.ydata = None
1433
1432
1434 self.PLOT_CODE = MPHASE_CODE
1433 self.PLOT_CODE = MPHASE_CODE
1435
1434
1436 self.FTP_WEI = None
1435 self.FTP_WEI = None
1437 self.EXP_CODE = None
1436 self.EXP_CODE = None
1438 self.SUB_EXP_CODE = None
1437 self.SUB_EXP_CODE = None
1439 self.PLOT_POS = None
1438 self.PLOT_POS = None
1440
1439
1441
1440
1442 self.filename_phase = None
1441 self.filename_phase = None
1443
1442
1444 self.figfile = None
1443 self.figfile = None
1445
1444
1446 def getSubplots(self):
1445 def getSubplots(self):
1447
1446
1448 ncol = 1
1447 ncol = 1
1449 nrow = 1
1448 nrow = 1
1450
1449
1451 return nrow, ncol
1450 return nrow, ncol
1452
1451
1453 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1452 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1454
1453
1455 self.__showprofile = showprofile
1454 self.__showprofile = showprofile
1456 self.nplots = nplots
1455 self.nplots = nplots
1457
1456
1458 ncolspan = 7
1457 ncolspan = 7
1459 colspan = 6
1458 colspan = 6
1460 self.__nsubplots = 2
1459 self.__nsubplots = 2
1461
1460
1462 self.createFigure(id = id,
1461 self.createFigure(id = id,
1463 wintitle = wintitle,
1462 wintitle = wintitle,
1464 widthplot = self.WIDTH+self.WIDTHPROF,
1463 widthplot = self.WIDTH+self.WIDTHPROF,
1465 heightplot = self.HEIGHT+self.HEIGHTPROF,
1464 heightplot = self.HEIGHT+self.HEIGHTPROF,
1466 show=show)
1465 show=show)
1467
1466
1468 nrow, ncol = self.getSubplots()
1467 nrow, ncol = self.getSubplots()
1469
1468
1470 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1469 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1471
1470
1472
1471
1473 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1472 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1474 xmin=None, xmax=None, ymin=None, ymax=None,
1473 xmin=None, xmax=None, ymin=None, ymax=None,
1475 timerange=None,
1474 timerange=None,
1476 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1475 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1477 server=None, folder=None, username=None, password=None,
1476 server=None, folder=None, username=None, password=None,
1478 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1477 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1479
1478
1480
1479
1481 tmin = None
1480 tmin = None
1482 tmax = None
1481 tmax = None
1483 x = dataOut.getTimeRange1(dataOut.outputInterval)
1482 x = dataOut.getTimeRange1(dataOut.outputInterval)
1484 y = dataOut.getHeiRange()
1483 y = dataOut.getHeiRange()
1485
1484
1486
1485
1487 #thisDatetime = dataOut.datatime
1486 #thisDatetime = dataOut.datatime
1488 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1487 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1489 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1488 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1490 xlabel = "Local Time"
1489 xlabel = "Local Time"
1491 ylabel = "Phase"
1490 ylabel = "Phase"
1492
1491
1493
1492
1494 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1493 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1495 phase_beacon = dataOut.data_output
1494 phase_beacon = dataOut.data_output
1496 update_figfile = False
1495 update_figfile = False
1497
1496
1498 if not self.isConfig:
1497 if not self.isConfig:
1499
1498
1500 self.nplots = phase_beacon.size
1499 self.nplots = phase_beacon.size
1501
1500
1502 self.setup(id=id,
1501 self.setup(id=id,
1503 nplots=self.nplots,
1502 nplots=self.nplots,
1504 wintitle=wintitle,
1503 wintitle=wintitle,
1505 showprofile=showprofile,
1504 showprofile=showprofile,
1506 show=show)
1505 show=show)
1507
1506
1508 if timerange is not None:
1507 if timerange is not None:
1509 self.timerange = timerange
1508 self.timerange = timerange
1510
1509
1511 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1510 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1512
1511
1513 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1512 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1514 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1513 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1515
1514
1516 self.FTP_WEI = ftp_wei
1515 self.FTP_WEI = ftp_wei
1517 self.EXP_CODE = exp_code
1516 self.EXP_CODE = exp_code
1518 self.SUB_EXP_CODE = sub_exp_code
1517 self.SUB_EXP_CODE = sub_exp_code
1519 self.PLOT_POS = plot_pos
1518 self.PLOT_POS = plot_pos
1520
1519
1521 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1520 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1522 self.isConfig = True
1521 self.isConfig = True
1523 self.figfile = figfile
1522 self.figfile = figfile
1524 self.xdata = numpy.array([])
1523 self.xdata = numpy.array([])
1525 self.ydata = numpy.array([])
1524 self.ydata = numpy.array([])
1526
1525
1527 #open file beacon phase
1526 #open file beacon phase
1528 path = '%s%03d' %(self.PREFIX, self.id)
1527 path = '%s%03d' %(self.PREFIX, self.id)
1529 beacon_file = os.path.join(path,'%s.txt'%self.name)
1528 beacon_file = os.path.join(path,'%s.txt'%self.name)
1530 self.filename_phase = os.path.join(figpath,beacon_file)
1529 self.filename_phase = os.path.join(figpath,beacon_file)
1531 update_figfile = True
1530 update_figfile = True
1532
1531
1533
1532
1534 #store data beacon phase
1533 #store data beacon phase
1535 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1534 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1536
1535
1537 self.setWinTitle(title)
1536 self.setWinTitle(title)
1538
1537
1539
1538
1540 title = "Phase Offset %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1539 title = "Phase Offset %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1541
1540
1542 legendlabels = ["phase %d"%(chan) for chan in numpy.arange(self.nplots)]
1541 legendlabels = ["phase %d"%(chan) for chan in numpy.arange(self.nplots)]
1543
1542
1544 axes = self.axesList[0]
1543 axes = self.axesList[0]
1545
1544
1546 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1545 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1547
1546
1548 if len(self.ydata)==0:
1547 if len(self.ydata)==0:
1549 self.ydata = phase_beacon.reshape(-1,1)
1548 self.ydata = phase_beacon.reshape(-1,1)
1550 else:
1549 else:
1551 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1550 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1552
1551
1553
1552
1554 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1553 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1555 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1554 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1556 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1555 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1557 XAxisAsTime=True, grid='both'
1556 XAxisAsTime=True, grid='both'
1558 )
1557 )
1559
1558
1560 self.draw()
1559 self.draw()
1561
1560
1562 self.save(figpath=figpath,
1561 self.save(figpath=figpath,
1563 figfile=figfile,
1562 figfile=figfile,
1564 save=save,
1563 save=save,
1565 ftp=ftp,
1564 ftp=ftp,
1566 wr_period=wr_period,
1565 wr_period=wr_period,
1567 thisDatetime=thisDatetime,
1566 thisDatetime=thisDatetime,
1568 update_figfile=update_figfile)
1567 update_figfile=update_figfile)
1569
1568
1570 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
1569 if dataOut.ltctime + dataOut.outputInterval >= self.xmax:
1571 self.counter_imagwr = wr_period
1570 self.counter_imagwr = wr_period
1572 self.isConfig = False
1571 self.isConfig = False
1573 update_figfile = True
1572 update_figfile = True
1574
1573
1575
1574
1576
1575
1577 class NSMeteorDetection1Plot(Figure):
1576 class NSMeteorDetection1Plot(Figure):
1578
1577
1579 isConfig = None
1578 isConfig = None
1580 __nsubplots = None
1579 __nsubplots = None
1581
1580
1582 WIDTHPROF = None
1581 WIDTHPROF = None
1583 HEIGHTPROF = None
1582 HEIGHTPROF = None
1584 PREFIX = 'nsm'
1583 PREFIX = 'nsm'
1585
1584
1586 zminList = None
1585 zminList = None
1587 zmaxList = None
1586 zmaxList = None
1588 cmapList = None
1587 cmapList = None
1589 titleList = None
1588 titleList = None
1590 nPairs = None
1589 nPairs = None
1591 nChannels = None
1590 nChannels = None
1592 nParam = None
1591 nParam = None
1593
1592
1594 def __init__(self, **kwargs):
1593 def __init__(self, **kwargs):
1595 Figure.__init__(self, **kwargs)
1594 Figure.__init__(self, **kwargs)
1596 self.isConfig = False
1595 self.isConfig = False
1597 self.__nsubplots = 1
1596 self.__nsubplots = 1
1598
1597
1599 self.WIDTH = 750
1598 self.WIDTH = 750
1600 self.HEIGHT = 250
1599 self.HEIGHT = 250
1601 self.WIDTHPROF = 120
1600 self.WIDTHPROF = 120
1602 self.HEIGHTPROF = 0
1601 self.HEIGHTPROF = 0
1603 self.counter_imagwr = 0
1602 self.counter_imagwr = 0
1604
1603
1605 self.PLOT_CODE = SPEC_CODE
1604 self.PLOT_CODE = SPEC_CODE
1606
1605
1607 self.FTP_WEI = None
1606 self.FTP_WEI = None
1608 self.EXP_CODE = None
1607 self.EXP_CODE = None
1609 self.SUB_EXP_CODE = None
1608 self.SUB_EXP_CODE = None
1610 self.PLOT_POS = None
1609 self.PLOT_POS = None
1611
1610
1612 self.__xfilter_ena = False
1611 self.__xfilter_ena = False
1613 self.__yfilter_ena = False
1612 self.__yfilter_ena = False
1614
1613
1615 def getSubplots(self):
1614 def getSubplots(self):
1616
1615
1617 ncol = 3
1616 ncol = 3
1618 nrow = int(numpy.ceil(self.nplots/3.0))
1617 nrow = int(numpy.ceil(self.nplots/3.0))
1619
1618
1620 return nrow, ncol
1619 return nrow, ncol
1621
1620
1622 def setup(self, id, nplots, wintitle, show=True):
1621 def setup(self, id, nplots, wintitle, show=True):
1623
1622
1624 self.nplots = nplots
1623 self.nplots = nplots
1625
1624
1626 ncolspan = 1
1625 ncolspan = 1
1627 colspan = 1
1626 colspan = 1
1628
1627
1629 self.createFigure(id = id,
1628 self.createFigure(id = id,
1630 wintitle = wintitle,
1629 wintitle = wintitle,
1631 widthplot = self.WIDTH + self.WIDTHPROF,
1630 widthplot = self.WIDTH + self.WIDTHPROF,
1632 heightplot = self.HEIGHT + self.HEIGHTPROF,
1631 heightplot = self.HEIGHT + self.HEIGHTPROF,
1633 show=show)
1632 show=show)
1634
1633
1635 nrow, ncol = self.getSubplots()
1634 nrow, ncol = self.getSubplots()
1636
1635
1637 counter = 0
1636 counter = 0
1638 for y in range(nrow):
1637 for y in range(nrow):
1639 for x in range(ncol):
1638 for x in range(ncol):
1640
1639
1641 if counter >= self.nplots:
1640 if counter >= self.nplots:
1642 break
1641 break
1643
1642
1644 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1643 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1645
1644
1646 counter += 1
1645 counter += 1
1647
1646
1648 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1647 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1649 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1648 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1650 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1649 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1651 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1650 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1652 server=None, folder=None, username=None, password=None,
1651 server=None, folder=None, username=None, password=None,
1653 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1652 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1654 xaxis="frequency"):
1653 xaxis="frequency"):
1655
1654
1656 """
1655 """
1657
1656
1658 Input:
1657 Input:
1659 dataOut :
1658 dataOut :
1660 id :
1659 id :
1661 wintitle :
1660 wintitle :
1662 channelList :
1661 channelList :
1663 showProfile :
1662 showProfile :
1664 xmin : None,
1663 xmin : None,
1665 xmax : None,
1664 xmax : None,
1666 ymin : None,
1665 ymin : None,
1667 ymax : None,
1666 ymax : None,
1668 zmin : None,
1667 zmin : None,
1669 zmax : None
1668 zmax : None
1670 """
1669 """
1671 #SEPARAR EN DOS PLOTS
1670 #SEPARAR EN DOS PLOTS
1672 nParam = dataOut.data_param.shape[1] - 3
1671 nParam = dataOut.data_param.shape[1] - 3
1673
1672
1674 utctime = dataOut.data_param[0,0]
1673 utctime = dataOut.data_param[0,0]
1675 tmet = dataOut.data_param[:,1].astype(int)
1674 tmet = dataOut.data_param[:,1].astype(int)
1676 hmet = dataOut.data_param[:,2].astype(int)
1675 hmet = dataOut.data_param[:,2].astype(int)
1677
1676
1678 x = dataOut.abscissaList
1677 x = dataOut.abscissaList
1679 y = dataOut.heightList
1678 y = dataOut.heightList
1680
1679
1681 z = numpy.zeros((nParam, y.size, x.size - 1))
1680 z = numpy.zeros((nParam, y.size, x.size - 1))
1682 z[:,:] = numpy.nan
1681 z[:,:] = numpy.nan
1683 z[:,hmet,tmet] = dataOut.data_param[:,3:].T
1682 z[:,hmet,tmet] = dataOut.data_param[:,3:].T
1684 z[0,:,:] = 10*numpy.log10(z[0,:,:])
1683 z[0,:,:] = 10*numpy.log10(z[0,:,:])
1685
1684
1686 xlabel = "Time (s)"
1685 xlabel = "Time (s)"
1687 ylabel = "Range (km)"
1686 ylabel = "Range (km)"
1688
1687
1689 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1688 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1690
1689
1691 if not self.isConfig:
1690 if not self.isConfig:
1692
1691
1693 nplots = nParam
1692 nplots = nParam
1694
1693
1695 self.setup(id=id,
1694 self.setup(id=id,
1696 nplots=nplots,
1695 nplots=nplots,
1697 wintitle=wintitle,
1696 wintitle=wintitle,
1698 show=show)
1697 show=show)
1699
1698
1700 if xmin is None: xmin = numpy.nanmin(x)
1699 if xmin is None: xmin = numpy.nanmin(x)
1701 if xmax is None: xmax = numpy.nanmax(x)
1700 if xmax is None: xmax = numpy.nanmax(x)
1702 if ymin is None: ymin = numpy.nanmin(y)
1701 if ymin is None: ymin = numpy.nanmin(y)
1703 if ymax is None: ymax = numpy.nanmax(y)
1702 if ymax is None: ymax = numpy.nanmax(y)
1704 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1703 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1705 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1704 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1706 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1705 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1707 if vmin is None: vmin = -vmax
1706 if vmin is None: vmin = -vmax
1708 if wmin is None: wmin = 0
1707 if wmin is None: wmin = 0
1709 if wmax is None: wmax = 50
1708 if wmax is None: wmax = 50
1710
1709
1711 pairsList = dataOut.groupList
1710 pairsList = dataOut.groupList
1712 self.nPairs = len(dataOut.groupList)
1711 self.nPairs = len(dataOut.groupList)
1713
1712
1714 zminList = [SNRmin, vmin, cmin] + [pmin]*self.nPairs
1713 zminList = [SNRmin, vmin, cmin] + [pmin]*self.nPairs
1715 zmaxList = [SNRmax, vmax, cmax] + [pmax]*self.nPairs
1714 zmaxList = [SNRmax, vmax, cmax] + [pmax]*self.nPairs
1716 titleList = ["SNR","Radial Velocity","Coherence"]
1715 titleList = ["SNR","Radial Velocity","Coherence"]
1717 cmapList = ["jet","RdBu_r","jet"]
1716 cmapList = ["jet","RdBu_r","jet"]
1718
1717
1719 for i in range(self.nPairs):
1718 for i in range(self.nPairs):
1720 strAux1 = "Phase Difference "+ str(pairsList[i][0]) + str(pairsList[i][1])
1719 strAux1 = "Phase Difference "+ str(pairsList[i][0]) + str(pairsList[i][1])
1721 titleList = titleList + [strAux1]
1720 titleList = titleList + [strAux1]
1722 cmapList = cmapList + ["RdBu_r"]
1721 cmapList = cmapList + ["RdBu_r"]
1723
1722
1724 self.zminList = zminList
1723 self.zminList = zminList
1725 self.zmaxList = zmaxList
1724 self.zmaxList = zmaxList
1726 self.cmapList = cmapList
1725 self.cmapList = cmapList
1727 self.titleList = titleList
1726 self.titleList = titleList
1728
1727
1729 self.FTP_WEI = ftp_wei
1728 self.FTP_WEI = ftp_wei
1730 self.EXP_CODE = exp_code
1729 self.EXP_CODE = exp_code
1731 self.SUB_EXP_CODE = sub_exp_code
1730 self.SUB_EXP_CODE = sub_exp_code
1732 self.PLOT_POS = plot_pos
1731 self.PLOT_POS = plot_pos
1733
1732
1734 self.isConfig = True
1733 self.isConfig = True
1735
1734
1736 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1735 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1737
1736
1738 for i in range(nParam):
1737 for i in range(nParam):
1739 title = self.titleList[i] + ": " +str_datetime
1738 title = self.titleList[i] + ": " +str_datetime
1740 axes = self.axesList[i]
1739 axes = self.axesList[i]
1741 axes.pcolor(x, y, z[i,:].T,
1740 axes.pcolor(x, y, z[i,:].T,
1742 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1741 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1743 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1742 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1744 self.draw()
1743 self.draw()
1745
1744
1746 if figfile == None:
1745 if figfile == None:
1747 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1746 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1748 name = str_datetime
1747 name = str_datetime
1749 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1748 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1750 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1749 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1751 figfile = self.getFilename(name)
1750 figfile = self.getFilename(name)
1752
1751
1753 self.save(figpath=figpath,
1752 self.save(figpath=figpath,
1754 figfile=figfile,
1753 figfile=figfile,
1755 save=save,
1754 save=save,
1756 ftp=ftp,
1755 ftp=ftp,
1757 wr_period=wr_period,
1756 wr_period=wr_period,
1758 thisDatetime=thisDatetime)
1757 thisDatetime=thisDatetime)
1759
1758
1760
1759
1761 class NSMeteorDetection2Plot(Figure):
1760 class NSMeteorDetection2Plot(Figure):
1762
1761
1763 isConfig = None
1762 isConfig = None
1764 __nsubplots = None
1763 __nsubplots = None
1765
1764
1766 WIDTHPROF = None
1765 WIDTHPROF = None
1767 HEIGHTPROF = None
1766 HEIGHTPROF = None
1768 PREFIX = 'nsm'
1767 PREFIX = 'nsm'
1769
1768
1770 zminList = None
1769 zminList = None
1771 zmaxList = None
1770 zmaxList = None
1772 cmapList = None
1771 cmapList = None
1773 titleList = None
1772 titleList = None
1774 nPairs = None
1773 nPairs = None
1775 nChannels = None
1774 nChannels = None
1776 nParam = None
1775 nParam = None
1777
1776
1778 def __init__(self, **kwargs):
1777 def __init__(self, **kwargs):
1779 Figure.__init__(self, **kwargs)
1778 Figure.__init__(self, **kwargs)
1780 self.isConfig = False
1779 self.isConfig = False
1781 self.__nsubplots = 1
1780 self.__nsubplots = 1
1782
1781
1783 self.WIDTH = 750
1782 self.WIDTH = 750
1784 self.HEIGHT = 250
1783 self.HEIGHT = 250
1785 self.WIDTHPROF = 120
1784 self.WIDTHPROF = 120
1786 self.HEIGHTPROF = 0
1785 self.HEIGHTPROF = 0
1787 self.counter_imagwr = 0
1786 self.counter_imagwr = 0
1788
1787
1789 self.PLOT_CODE = SPEC_CODE
1788 self.PLOT_CODE = SPEC_CODE
1790
1789
1791 self.FTP_WEI = None
1790 self.FTP_WEI = None
1792 self.EXP_CODE = None
1791 self.EXP_CODE = None
1793 self.SUB_EXP_CODE = None
1792 self.SUB_EXP_CODE = None
1794 self.PLOT_POS = None
1793 self.PLOT_POS = None
1795
1794
1796 self.__xfilter_ena = False
1795 self.__xfilter_ena = False
1797 self.__yfilter_ena = False
1796 self.__yfilter_ena = False
1798
1797
1799 def getSubplots(self):
1798 def getSubplots(self):
1800
1799
1801 ncol = 3
1800 ncol = 3
1802 nrow = int(numpy.ceil(self.nplots/3.0))
1801 nrow = int(numpy.ceil(self.nplots/3.0))
1803
1802
1804 return nrow, ncol
1803 return nrow, ncol
1805
1804
1806 def setup(self, id, nplots, wintitle, show=True):
1805 def setup(self, id, nplots, wintitle, show=True):
1807
1806
1808 self.nplots = nplots
1807 self.nplots = nplots
1809
1808
1810 ncolspan = 1
1809 ncolspan = 1
1811 colspan = 1
1810 colspan = 1
1812
1811
1813 self.createFigure(id = id,
1812 self.createFigure(id = id,
1814 wintitle = wintitle,
1813 wintitle = wintitle,
1815 widthplot = self.WIDTH + self.WIDTHPROF,
1814 widthplot = self.WIDTH + self.WIDTHPROF,
1816 heightplot = self.HEIGHT + self.HEIGHTPROF,
1815 heightplot = self.HEIGHT + self.HEIGHTPROF,
1817 show=show)
1816 show=show)
1818
1817
1819 nrow, ncol = self.getSubplots()
1818 nrow, ncol = self.getSubplots()
1820
1819
1821 counter = 0
1820 counter = 0
1822 for y in range(nrow):
1821 for y in range(nrow):
1823 for x in range(ncol):
1822 for x in range(ncol):
1824
1823
1825 if counter >= self.nplots:
1824 if counter >= self.nplots:
1826 break
1825 break
1827
1826
1828 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1827 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
1829
1828
1830 counter += 1
1829 counter += 1
1831
1830
1832 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1831 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
1833 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1832 xmin=None, xmax=None, ymin=None, ymax=None, SNRmin=None, SNRmax=None,
1834 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1833 vmin=None, vmax=None, wmin=None, wmax=None, mode = 'SA',
1835 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1834 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1836 server=None, folder=None, username=None, password=None,
1835 server=None, folder=None, username=None, password=None,
1837 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1836 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False,
1838 xaxis="frequency"):
1837 xaxis="frequency"):
1839
1838
1840 """
1839 """
1841
1840
1842 Input:
1841 Input:
1843 dataOut :
1842 dataOut :
1844 id :
1843 id :
1845 wintitle :
1844 wintitle :
1846 channelList :
1845 channelList :
1847 showProfile :
1846 showProfile :
1848 xmin : None,
1847 xmin : None,
1849 xmax : None,
1848 xmax : None,
1850 ymin : None,
1849 ymin : None,
1851 ymax : None,
1850 ymax : None,
1852 zmin : None,
1851 zmin : None,
1853 zmax : None
1852 zmax : None
1854 """
1853 """
1855 #Rebuild matrix
1854 #Rebuild matrix
1856 utctime = dataOut.data_param[0,0]
1855 utctime = dataOut.data_param[0,0]
1857 cmet = dataOut.data_param[:,1].astype(int)
1856 cmet = dataOut.data_param[:,1].astype(int)
1858 tmet = dataOut.data_param[:,2].astype(int)
1857 tmet = dataOut.data_param[:,2].astype(int)
1859 hmet = dataOut.data_param[:,3].astype(int)
1858 hmet = dataOut.data_param[:,3].astype(int)
1860
1859
1861 nParam = 3
1860 nParam = 3
1862 nChan = len(dataOut.groupList)
1861 nChan = len(dataOut.groupList)
1863 x = dataOut.abscissaList
1862 x = dataOut.abscissaList
1864 y = dataOut.heightList
1863 y = dataOut.heightList
1865
1864
1866 z = numpy.full((nChan, nParam, y.size, x.size - 1),numpy.nan)
1865 z = numpy.full((nChan, nParam, y.size, x.size - 1),numpy.nan)
1867 z[cmet,:,hmet,tmet] = dataOut.data_param[:,4:]
1866 z[cmet,:,hmet,tmet] = dataOut.data_param[:,4:]
1868 z[:,0,:,:] = 10*numpy.log10(z[:,0,:,:]) #logarithmic scale
1867 z[:,0,:,:] = 10*numpy.log10(z[:,0,:,:]) #logarithmic scale
1869 z = numpy.reshape(z, (nChan*nParam, y.size, x.size-1))
1868 z = numpy.reshape(z, (nChan*nParam, y.size, x.size-1))
1870
1869
1871 xlabel = "Time (s)"
1870 xlabel = "Time (s)"
1872 ylabel = "Range (km)"
1871 ylabel = "Range (km)"
1873
1872
1874 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1873 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.ltctime)
1875
1874
1876 if not self.isConfig:
1875 if not self.isConfig:
1877
1876
1878 nplots = nParam*nChan
1877 nplots = nParam*nChan
1879
1878
1880 self.setup(id=id,
1879 self.setup(id=id,
1881 nplots=nplots,
1880 nplots=nplots,
1882 wintitle=wintitle,
1881 wintitle=wintitle,
1883 show=show)
1882 show=show)
1884
1883
1885 if xmin is None: xmin = numpy.nanmin(x)
1884 if xmin is None: xmin = numpy.nanmin(x)
1886 if xmax is None: xmax = numpy.nanmax(x)
1885 if xmax is None: xmax = numpy.nanmax(x)
1887 if ymin is None: ymin = numpy.nanmin(y)
1886 if ymin is None: ymin = numpy.nanmin(y)
1888 if ymax is None: ymax = numpy.nanmax(y)
1887 if ymax is None: ymax = numpy.nanmax(y)
1889 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1888 if SNRmin is None: SNRmin = numpy.nanmin(z[0,:])
1890 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1889 if SNRmax is None: SNRmax = numpy.nanmax(z[0,:])
1891 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1890 if vmax is None: vmax = numpy.nanmax(numpy.abs(z[1,:]))
1892 if vmin is None: vmin = -vmax
1891 if vmin is None: vmin = -vmax
1893 if wmin is None: wmin = 0
1892 if wmin is None: wmin = 0
1894 if wmax is None: wmax = 50
1893 if wmax is None: wmax = 50
1895
1894
1896 self.nChannels = nChan
1895 self.nChannels = nChan
1897
1896
1898 zminList = []
1897 zminList = []
1899 zmaxList = []
1898 zmaxList = []
1900 titleList = []
1899 titleList = []
1901 cmapList = []
1900 cmapList = []
1902 for i in range(self.nChannels):
1901 for i in range(self.nChannels):
1903 strAux1 = "SNR Channel "+ str(i)
1902 strAux1 = "SNR Channel "+ str(i)
1904 strAux2 = "Radial Velocity Channel "+ str(i)
1903 strAux2 = "Radial Velocity Channel "+ str(i)
1905 strAux3 = "Spectral Width Channel "+ str(i)
1904 strAux3 = "Spectral Width Channel "+ str(i)
1906
1905
1907 titleList = titleList + [strAux1,strAux2,strAux3]
1906 titleList = titleList + [strAux1,strAux2,strAux3]
1908 cmapList = cmapList + ["jet","RdBu_r","jet"]
1907 cmapList = cmapList + ["jet","RdBu_r","jet"]
1909 zminList = zminList + [SNRmin,vmin,wmin]
1908 zminList = zminList + [SNRmin,vmin,wmin]
1910 zmaxList = zmaxList + [SNRmax,vmax,wmax]
1909 zmaxList = zmaxList + [SNRmax,vmax,wmax]
1911
1910
1912 self.zminList = zminList
1911 self.zminList = zminList
1913 self.zmaxList = zmaxList
1912 self.zmaxList = zmaxList
1914 self.cmapList = cmapList
1913 self.cmapList = cmapList
1915 self.titleList = titleList
1914 self.titleList = titleList
1916
1915
1917 self.FTP_WEI = ftp_wei
1916 self.FTP_WEI = ftp_wei
1918 self.EXP_CODE = exp_code
1917 self.EXP_CODE = exp_code
1919 self.SUB_EXP_CODE = sub_exp_code
1918 self.SUB_EXP_CODE = sub_exp_code
1920 self.PLOT_POS = plot_pos
1919 self.PLOT_POS = plot_pos
1921
1920
1922 self.isConfig = True
1921 self.isConfig = True
1923
1922
1924 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1923 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
1925
1924
1926 for i in range(self.nplots):
1925 for i in range(self.nplots):
1927 title = self.titleList[i] + ": " +str_datetime
1926 title = self.titleList[i] + ": " +str_datetime
1928 axes = self.axesList[i]
1927 axes = self.axesList[i]
1929 axes.pcolor(x, y, z[i,:].T,
1928 axes.pcolor(x, y, z[i,:].T,
1930 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1929 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=self.zminList[i], zmax=self.zmaxList[i],
1931 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1930 xlabel=xlabel, ylabel=ylabel, title=title, colormap=self.cmapList[i],ticksize=9, cblabel='')
1932 self.draw()
1931 self.draw()
1933
1932
1934 if figfile == None:
1933 if figfile == None:
1935 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1934 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1936 name = str_datetime
1935 name = str_datetime
1937 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1936 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
1938 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1937 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
1939 figfile = self.getFilename(name)
1938 figfile = self.getFilename(name)
1940
1939
1941 self.save(figpath=figpath,
1940 self.save(figpath=figpath,
1942 figfile=figfile,
1941 figfile=figfile,
1943 save=save,
1942 save=save,
1944 ftp=ftp,
1943 ftp=ftp,
1945 wr_period=wr_period,
1944 wr_period=wr_period,
1946 thisDatetime=thisDatetime)
1945 thisDatetime=thisDatetime)
@@ -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,318 +1,349
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
7 from fuzzywuzzy import process
8
9 def checkKwargs(method, kwargs):
10 currentKwargs = kwargs
11 choices = inspect.getargspec(method).args
12 try:
13 choices.remove('self')
14 except Exception as e:
15 pass
16
17 try:
18 choices.remove('dataOut')
19 except Exception as e:
20 pass
21
22 for kwarg in kwargs:
23 fuzz = process.extractOne(kwarg, choices)
24 if fuzz is None:
25 continue
26 if fuzz[1] < 100:
27 raise Exception('\x1b[0;32;40mDid you mean {} instead of {} in {}? \x1b[0m'.
28 format(fuzz[0], kwarg, method.__self__.__class__.__name__))
6
29
7 class ProcessingUnit(object):
30 class ProcessingUnit(object):
8
31
9 """
32 """
10 Esta es la clase base para el procesamiento de datos.
33 Esta es la clase base para el procesamiento de datos.
11
34
12 Contiene el metodo "call" para llamar operaciones. Las operaciones pueden ser:
35 Contiene el metodo "call" para llamar operaciones. Las operaciones pueden ser:
13 - Metodos internos (callMethod)
36 - Metodos internos (callMethod)
14 - Objetos del tipo Operation (callObject). Antes de ser llamados, estos objetos
37 - Objetos del tipo Operation (callObject). Antes de ser llamados, estos objetos
15 tienen que ser agreagados con el metodo "add".
38 tienen que ser agreagados con el metodo "add".
16
39
17 """
40 """
18 # objeto de datos de entrada (Voltage, Spectra o Correlation)
41 # objeto de datos de entrada (Voltage, Spectra o Correlation)
19 dataIn = None
42 dataIn = None
20 dataInList = []
43 dataInList = []
21
44
22 # objeto de datos de entrada (Voltage, Spectra o Correlation)
45 # objeto de datos de entrada (Voltage, Spectra o Correlation)
23 dataOut = None
46 dataOut = None
24
47
25 operations2RunDict = None
48 operations2RunDict = None
26
49
27 isConfig = False
50 isConfig = False
28
51
29
52
30 def __init__(self, *args, **kwargs):
53 def __init__(self, *args, **kwargs):
31
54
32 self.dataIn = None
55 self.dataIn = None
33 self.dataInList = []
56 self.dataInList = []
34
57
35 self.dataOut = None
58 self.dataOut = None
36
59
37 self.operations2RunDict = {}
60 self.operations2RunDict = {}
38 self.operationKwargs = {}
61 self.operationKwargs = {}
39
62
40 self.isConfig = False
63 self.isConfig = False
41
64
42 self.args = args
65 self.args = args
43 self.kwargs = kwargs
66 self.kwargs = kwargs
67 checkKwargs(self.run, kwargs)
68
69 def getAllowedArgs(self):
70 return inspect.getargspec(self.run).args
44
71
45 def addOperationKwargs(self, objId, **kwargs):
72 def addOperationKwargs(self, objId, **kwargs):
46 '''
73 '''
47 '''
74 '''
48
75
49 self.operationKwargs[objId] = kwargs
76 self.operationKwargs[objId] = kwargs
50
77
51
78
52 def addOperation(self, opObj, objId):
79 def addOperation(self, opObj, objId):
53
80
54 """
81 """
55 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
56 identificador asociado a este objeto.
83 identificador asociado a este objeto.
57
84
58 Input:
85 Input:
59
86
60 object : objeto de la clase "Operation"
87 object : objeto de la clase "Operation"
61
88
62 Return:
89 Return:
63
90
64 objId : identificador del objeto, necesario para ejecutar la operacion
91 objId : identificador del objeto, necesario para ejecutar la operacion
65 """
92 """
66
93
67 self.operations2RunDict[objId] = opObj
94 self.operations2RunDict[objId] = opObj
68
95
69 return objId
96 return objId
70
97
71 def getOperationObj(self, objId):
98 def getOperationObj(self, objId):
72
99
73 if objId not in self.operations2RunDict.keys():
100 if objId not in self.operations2RunDict.keys():
74 return None
101 return None
75
102
76 return self.operations2RunDict[objId]
103 return self.operations2RunDict[objId]
77
104
78 def operation(self, **kwargs):
105 def operation(self, **kwargs):
79
106
80 """
107 """
81 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
82 atributos del objeto dataOut
109 atributos del objeto dataOut
83
110
84 Input:
111 Input:
85
112
86 **kwargs : Diccionario de argumentos de la funcion a ejecutar
113 **kwargs : Diccionario de argumentos de la funcion a ejecutar
87 """
114 """
88
115
89 raise NotImplementedError
116 raise NotImplementedError
90
117
91 def callMethod(self, name, opId):
118 def callMethod(self, name, opId):
92
119
93 """
120 """
94 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.
95
122
96 Input:
123 Input:
97 name : nombre del metodo a ejecutar
124 name : nombre del metodo a ejecutar
98
125
99 **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.
100
127
101 """
128 """
102
129
103 #Checking the inputs
130 #Checking the inputs
104 if name == 'run':
131 if name == 'run':
105
132
106 if not self.checkInputs():
133 if not self.checkInputs():
107 self.dataOut.flagNoData = True
134 self.dataOut.flagNoData = True
108 return False
135 return False
109 else:
136 else:
110 #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)
111 if self.dataOut is not None and self.dataOut.isEmpty():
138 if self.dataOut is not None and self.dataOut.isEmpty():
112 return False
139 return False
113
140
114 #Getting the pointer to method
141 #Getting the pointer to method
115 methodToCall = getattr(self, name)
142 methodToCall = getattr(self, name)
116
143
117 #Executing the self method
144 #Executing the self method
118
145
119 if hasattr(self, 'mp'):
146 if hasattr(self, 'mp'):
120 if name=='run':
147 if name=='run':
121 if self.mp is False:
148 if self.mp is False:
122 self.mp = True
149 self.mp = True
123 self.start()
150 self.start()
124 else:
151 else:
125 self.operationKwargs[opId]['parent'] = self.kwargs
152 self.operationKwargs[opId]['parent'] = self.kwargs
126 methodToCall(**self.operationKwargs[opId])
153 methodToCall(**self.operationKwargs[opId])
127 else:
154 else:
128 if name=='run':
155 if name=='run':
129 methodToCall(**self.kwargs)
156 methodToCall(**self.kwargs)
130 else:
157 else:
131 methodToCall(**self.operationKwargs[opId])
158 methodToCall(**self.operationKwargs[opId])
132
159
133 if self.dataOut is None:
160 if self.dataOut is None:
134 return False
161 return False
135
162
136 if self.dataOut.isEmpty():
163 if self.dataOut.isEmpty():
137 return False
164 return False
138
165
139 return True
166 return True
140
167
141 def callObject(self, objId):
168 def callObject(self, objId):
142
169
143 """
170 """
144 Ejecuta la operacion asociada al identificador del objeto "objId"
171 Ejecuta la operacion asociada al identificador del objeto "objId"
145
172
146 Input:
173 Input:
147
174
148 objId : identificador del objeto a ejecutar
175 objId : identificador del objeto a ejecutar
149
176
150 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
177 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
151
178
152 Return:
179 Return:
153
180
154 None
181 None
155 """
182 """
156
183
157 if self.dataOut is not None and self.dataOut.isEmpty():
184 if self.dataOut is not None and self.dataOut.isEmpty():
158 return False
185 return False
159
186
160 externalProcObj = self.operations2RunDict[objId]
187 externalProcObj = self.operations2RunDict[objId]
161
188
162 if hasattr(externalProcObj, 'mp'):
189 if hasattr(externalProcObj, 'mp'):
163 if externalProcObj.mp is False:
190 if externalProcObj.mp is False:
164 externalProcObj.kwargs['parent'] = self.kwargs
191 externalProcObj.kwargs['parent'] = self.kwargs
165 self.operationKwargs[objId] = externalProcObj.kwargs
192 self.operationKwargs[objId] = externalProcObj.kwargs
166 externalProcObj.mp = True
193 externalProcObj.mp = True
167 externalProcObj.start()
194 externalProcObj.start()
168 else:
195 else:
169 externalProcObj.run(self.dataOut, **externalProcObj.kwargs)
196 externalProcObj.run(self.dataOut, **externalProcObj.kwargs)
170 self.operationKwargs[objId] = externalProcObj.kwargs
197 self.operationKwargs[objId] = externalProcObj.kwargs
171
198
172
199
173 return True
200 return True
174
201
175 def call(self, opType, opName=None, opId=None):
202 def call(self, opType, opName=None, opId=None):
176
203
177 """
204 """
178 Return True si ejecuta la operacion interna nombrada "opName" o la operacion externa
205 Return True si ejecuta la operacion interna nombrada "opName" o la operacion externa
179 identificada con el id "opId"; con los argumentos "**kwargs".
206 identificada con el id "opId"; con los argumentos "**kwargs".
180
207
181 False si la operacion no se ha ejecutado.
208 False si la operacion no se ha ejecutado.
182
209
183 Input:
210 Input:
184
211
185 opType : Puede ser "self" o "external"
212 opType : Puede ser "self" o "external"
186
213
187 Depende del tipo de operacion para llamar a:callMethod or callObject:
214 Depende del tipo de operacion para llamar a:callMethod or callObject:
188
215
189 1. If opType = "self": Llama a un metodo propio de esta clase:
216 1. If opType = "self": Llama a un metodo propio de esta clase:
190
217
191 name_method = getattr(self, name)
218 name_method = getattr(self, name)
192 name_method(**kwargs)
219 name_method(**kwargs)
193
220
194
221
195 2. If opType = "other" o"external": Llama al metodo "run()" de una instancia de la
222 2. If opType = "other" o"external": Llama al metodo "run()" de una instancia de la
196 clase "Operation" o de un derivado de ella:
223 clase "Operation" o de un derivado de ella:
197
224
198 instanceName = self.operationList[opId]
225 instanceName = self.operationList[opId]
199 instanceName.run(**kwargs)
226 instanceName.run(**kwargs)
200
227
201 opName : Si la operacion es interna (opType = 'self'), entonces el "opName" sera
228 opName : Si la operacion es interna (opType = 'self'), entonces el "opName" sera
202 usada para llamar a un metodo interno de la clase Processing
229 usada para llamar a un metodo interno de la clase Processing
203
230
204 opId : Si la operacion es externa (opType = 'other' o 'external), entonces el
231 opId : Si la operacion es externa (opType = 'other' o 'external), entonces el
205 "opId" sera usada para llamar al metodo "run" de la clase Operation
232 "opId" sera usada para llamar al metodo "run" de la clase Operation
206 registrada anteriormente con ese Id
233 registrada anteriormente con ese Id
207
234
208 Exception:
235 Exception:
209 Este objeto de tipo Operation debe de haber sido agregado antes con el metodo:
236 Este objeto de tipo Operation debe de haber sido agregado antes con el metodo:
210 "addOperation" e identificado con el valor "opId" = el id de la operacion.
237 "addOperation" e identificado con el valor "opId" = el id de la operacion.
211 De lo contrario retornara un error del tipo ValueError
238 De lo contrario retornara un error del tipo ValueError
212
239
213 """
240 """
214
241
215 if opType == 'self':
242 if opType == 'self':
216
243
217 if not opName:
244 if not opName:
218 raise ValueError, "opName parameter should be defined"
245 raise ValueError, "opName parameter should be defined"
219
246
220 sts = self.callMethod(opName, opId)
247 sts = self.callMethod(opName, opId)
221
248
222 elif opType == 'other' or opType == 'external' or opType == 'plotter':
249 elif opType == 'other' or opType == 'external' or opType == 'plotter':
223
250
224 if not opId:
251 if not opId:
225 raise ValueError, "opId parameter should be defined"
252 raise ValueError, "opId parameter should be defined"
226
253
227 if opId not in self.operations2RunDict.keys():
254 if opId not in self.operations2RunDict.keys():
228 raise ValueError, "Any operation with id=%s has been added" %str(opId)
255 raise ValueError, "Any operation with id=%s has been added" %str(opId)
229
256
230 sts = self.callObject(opId)
257 sts = self.callObject(opId)
231
258
232 else:
259 else:
233 raise ValueError, "opType should be 'self', 'external' or 'plotter'; and not '%s'" %opType
260 raise ValueError, "opType should be 'self', 'external' or 'plotter'; and not '%s'" %opType
234
261
235 return sts
262 return sts
236
263
237 def setInput(self, dataIn):
264 def setInput(self, dataIn):
238
265
239 self.dataIn = dataIn
266 self.dataIn = dataIn
240 self.dataInList.append(dataIn)
267 self.dataInList.append(dataIn)
241
268
242 def getOutputObj(self):
269 def getOutputObj(self):
243
270
244 return self.dataOut
271 return self.dataOut
245
272
246 def checkInputs(self):
273 def checkInputs(self):
247
274
248 for thisDataIn in self.dataInList:
275 for thisDataIn in self.dataInList:
249
276
250 if thisDataIn.isEmpty():
277 if thisDataIn.isEmpty():
251 return False
278 return False
252
279
253 return True
280 return True
254
281
255 def setup(self):
282 def setup(self):
256
283
257 raise NotImplementedError
284 raise NotImplementedError
258
285
259 def run(self):
286 def run(self):
260
287
261 raise NotImplementedError
288 raise NotImplementedError
262
289
263 def close(self):
290 def close(self):
264 #Close every thread, queue or any other object here is it is neccesary.
291 #Close every thread, queue or any other object here is it is neccesary.
265 return
292 return
266
293
267 class Operation(object):
294 class Operation(object):
268
295
269 """
296 """
270 Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit
297 Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit
271 y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de
298 y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de
272 acumulacion dentro de esta clase
299 acumulacion dentro de esta clase
273
300
274 Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer)
301 Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer)
275
302
276 """
303 """
277
304
278 __buffer = None
305 __buffer = None
279 isConfig = False
306 isConfig = False
280
307
281 def __init__(self, **kwargs):
308 def __init__(self, **kwargs):
282
309
283 self.__buffer = None
310 self.__buffer = None
284 self.isConfig = False
311 self.isConfig = False
285 self.kwargs = kwargs
312 self.kwargs = kwargs
313 checkKwargs(self.run, kwargs)
314
315 def getAllowedArgs(self):
316 return inspect.getargspec(self.run).args
286
317
287 def setup(self):
318 def setup(self):
288
319
289 self.isConfig = True
320 self.isConfig = True
290
321
291 raise NotImplementedError
322 raise NotImplementedError
292
323
293 def run(self, dataIn, **kwargs):
324 def run(self, dataIn, **kwargs):
294
325
295 """
326 """
296 Realiza las operaciones necesarias sobre la dataIn.data y actualiza los
327 Realiza las operaciones necesarias sobre la dataIn.data y actualiza los
297 atributos del objeto dataIn.
328 atributos del objeto dataIn.
298
329
299 Input:
330 Input:
300
331
301 dataIn : objeto del tipo JROData
332 dataIn : objeto del tipo JROData
302
333
303 Return:
334 Return:
304
335
305 None
336 None
306
337
307 Affected:
338 Affected:
308 __buffer : buffer de recepcion de datos.
339 __buffer : buffer de recepcion de datos.
309
340
310 """
341 """
311 if not self.isConfig:
342 if not self.isConfig:
312 self.setup(**kwargs)
343 self.setup(**kwargs)
313
344
314 raise NotImplementedError
345 raise NotImplementedError
315
346
316 def close(self):
347 def close(self):
317
348
318 pass
349 pass
@@ -1,450 +1,465
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 == 'output':
376 if plottype == 'output':
371 self.data[plottype][t] = self.dataOut.data_output
377 self.data[plottype][t] = self.dataOut.data_output
372 if plottype == 'param':
378 if plottype == 'param':
373 self.data[plottype][t] = self.dataOut.data_param
379 self.data[plottype][t] = self.dataOut.data_param
374 if self.realtime:
380 if self.realtime:
375 self.data_web['timestamp'] = t
381 self.data_web['timestamp'] = t
376 if plottype == 'spc':
382 if plottype == 'spc':
377 self.data_web[plottype] = roundFloats(decimate(self.data[plottype]).tolist())
383 self.data_web[plottype] = roundFloats(decimate(self.data[plottype]).tolist())
378 elif plottype == 'cspc':
384 elif plottype == 'cspc':
379 self.data_web['cspc_coh'] = roundFloats(decimate(self.data['cspc_coh']).tolist())
385 self.data_web['cspc_coh'] = roundFloats(decimate(self.data['cspc_coh']).tolist())
380 self.data_web['cspc_phase'] = roundFloats(decimate(self.data['cspc_phase']).tolist())
386 self.data_web['cspc_phase'] = roundFloats(decimate(self.data['cspc_phase']).tolist())
381 elif plottype == 'noise':
387 elif plottype == 'noise':
382 self.data_web['noise'] = roundFloats(self.data['noise'][t].tolist())
388 self.data_web['noise'] = roundFloats(self.data['noise'][t].tolist())
383 else:
389 else:
384 self.data_web[plottype] = roundFloats(decimate(self.data[plottype][t]).tolist())
390 self.data_web[plottype] = roundFloats(decimate(self.data[plottype][t]).tolist())
385 self.data_web['interval'] = self.dataOut.getTimeInterval()
391 self.data_web['interval'] = self.dataOut.getTimeInterval()
386 self.data_web['type'] = plottype
392 self.data_web['type'] = plottype
387
393
388 def run(self):
394 def run(self):
389
395
390 print '[Starting] {} from {}'.format(self.name, self.address)
396 print '[Starting] {} from {}'.format(self.name, self.address)
391
397
392 self.context = zmq.Context()
398 self.context = zmq.Context()
393 self.receiver = self.context.socket(zmq.PULL)
399 self.receiver = self.context.socket(zmq.PULL)
394 self.receiver.bind(self.address)
400 self.receiver.bind(self.address)
395 monitor = self.receiver.get_monitor_socket()
401 monitor = self.receiver.get_monitor_socket()
396 self.sender = self.context.socket(zmq.PUB)
402 self.sender = self.context.socket(zmq.PUB)
397 if self.realtime:
403 if self.realtime:
398 self.sender_web = self.context.socket(zmq.PUB)
404 self.sender_web = self.context.socket(zmq.PUB)
399 self.sender_web.connect(self.plot_address)
405 self.sender_web.connect(self.plot_address)
400 time.sleep(1)
406 time.sleep(1)
407
401 if 'server' in self.kwargs:
408 if 'server' in self.kwargs:
402 self.sender.bind("ipc:///tmp/{}.plots".format(self.kwargs['server']))
409 self.sender.bind("ipc:///tmp/{}.plots".format(self.kwargs['server']))
403 else:
410 else:
404 self.sender.bind("ipc:///tmp/zmq.plots")
411 self.sender.bind("ipc:///tmp/zmq.plots")
405
412
413 time.sleep(3)
414
406 t = Thread(target=self.event_monitor, args=(monitor,))
415 t = Thread(target=self.event_monitor, args=(monitor,))
407 t.start()
416 t.start()
408
417
409 while True:
418 while True:
410 self.dataOut = self.receiver.recv_pyobj()
419 self.dataOut = self.receiver.recv_pyobj()
411 # print '[Receiving] {} - {}'.format(self.dataOut.type,
420 # print '[Receiving] {} - {}'.format(self.dataOut.type,
412 # self.dataOut.datatime.ctime())
421 # self.dataOut.datatime.ctime())
413
422
414 self.update()
423 self.update()
415
424
425 if self.dataOut.firstdata is True:
426 self.data['STARTED'] = True
427
428
416 if self.dataOut.finished is True:
429 if self.dataOut.finished is True:
417 self.send(self.data)
430 self.send(self.data)
418 self.connections -= 1
431 self.connections -= 1
419 if self.connections == 0 and self.started:
432 if self.connections == 0 and self.started:
420 self.ended = True
433 self.ended = True
421 self.data['ENDED'] = True
434 self.data['ENDED'] = True
422 self.send(self.data)
435 self.send(self.data)
423 self.setup()
436 self.setup()
437 self.started = False
424 else:
438 else:
425 if self.realtime:
439 if self.realtime:
426 self.send(self.data)
440 self.send(self.data)
427 self.sender_web.send_string(json.dumps(self.data_web))
441 self.sender_web.send_string(json.dumps(self.data_web))
428 else:
442 else:
429 self.sendData(self.send, self.data)
443 self.sendData(self.send, self.data)
430 self.started = True
444 self.started = True
431
445
446 self.data['STARTED'] = False
432 return
447 return
433
448
434 def sendToWeb(self):
449 def sendToWeb(self):
435
450
436 if not self.isWebConfig:
451 if not self.isWebConfig:
437 context = zmq.Context()
452 context = zmq.Context()
438 sender_web_config = context.socket(zmq.PUB)
453 sender_web_config = context.socket(zmq.PUB)
439 if 'tcp://' in self.plot_address:
454 if 'tcp://' in self.plot_address:
440 dum, address, port = self.plot_address.split(':')
455 dum, address, port = self.plot_address.split(':')
441 conf_address = '{}:{}:{}'.format(dum, address, int(port)+1)
456 conf_address = '{}:{}:{}'.format(dum, address, int(port)+1)
442 else:
457 else:
443 conf_address = self.plot_address + '.config'
458 conf_address = self.plot_address + '.config'
444 sender_web_config.bind(conf_address)
459 sender_web_config.bind(conf_address)
445 time.sleep(1)
460 time.sleep(1)
446 for kwargs in self.operationKwargs.values():
461 for kwargs in self.operationKwargs.values():
447 if 'plot' in kwargs:
462 if 'plot' in kwargs:
448 print '[Sending] Config data to web for {}'.format(kwargs['code'].upper())
463 print '[Sending] Config data to web for {}'.format(kwargs['code'].upper())
449 sender_web_config.send_string(json.dumps(kwargs))
464 sender_web_config.send_string(json.dumps(kwargs))
450 self.isWebConfig = True
465 self.isWebConfig = True
@@ -1,87 +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/hysell_data20/pdata',
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 # opObj11 = procUnitConfObj2.addParameter(name='pairsList', value='(0,1)', format='pairslist')
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 = procUnitConfObj2.addOperation(name='RTIPlot', optype='other')
47 # opObj11 = procUnitConfObj3.addOperation(name='Parameters1Plot', optype='other')
48 # opObj11.addParameter(name='channelList', value='0', format='intList')
49
48 # opObj11.addParameter(name='id', value='2000', format='int')
50 # opObj11.addParameter(name='id', value='2000', format='int')
49 # opObj11.addParameter(name='wintitzmaxle', value='HF_Jicamarca', format='str')
51 # # opObj11.addParameter(name='colormap', value='0', format='bool')
50 # opObj11.addParameter(name='showprofile', value='0', format='int')
52 # opObj11.addParameter(name='onlySNR', value='1', format='bool')
53 # opObj11.addParameter(name='DOP', value='0', format='bool')
54 # # opObj11.addParameter(name='showSNR', value='1', format='bool')
55 # # opObj11.addParameter(name='SNRthresh', value='0', format='int')
56 # opObj11.addParameter(name='SNRmin', value='-10', format='int')
57 # opObj11.addParameter(name='SNRmax', value='30', format='int')
58
59 # opObj11.addParameter(name='showSNR', value='1', format='int')
51 # # opObj11.addParameter(name='channelList', value='0', format='intlist')
60 # # opObj11.addParameter(name='channelList', value='0', format='intlist')
52 # # opObj11.addParameter(name='xmin', value='0', format='float')
61 # # opObj11.addParameter(name='xmin', value='0', format='float')
53 # opObj11.addParameter(name='xmin', value='0', format='float')
62 # opObj11.addParameter(name='xmin', value='0', format='float')
54 # opObj11.addParameter(name='xmax', value='24', format='float')
63 # opObj11.addParameter(name='xmax', value='24', format='float')
55
64
56 # opObj11.addParameter(name='zmin', value='-110', format='float')
65 # opObj11.addParameter(name='zmin', value='-110', format='float')
57 # opObj11.addParameter(name='zmax', value='-70', format='float')
66 # opObj11.addParameter(name='zmax', value='-70', format='float')
58 # opObj11.addParameter(name='save', value='0', format='int')
67 # opObj11.addParameter(name='save', value='0', format='int')
59 # # opObj11.addParameter(name='figpath', value='/tmp/', format='str')
68 # # opObj11.addParameter(name='figpath', value='/tmp/', format='str')
60 #
69 #
61 opObj12 = procUnitConfObj3.addOperation(name='PublishData', optype='other')
70 opObj12 = procUnitConfObj3.addOperation(name='PublishData', optype='other')
62 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')
63
73
64
74
65 # opObj13 = procUnitConfObj3.addOperation(name='PublishData', optype='other')
75 # opObj13 = procUnitConfObj3.addOperation(name='PublishData', optype='other')
66 # opObj13.addParameter(name='zeromq', value=1, format='int')
76 # opObj13.addParameter(name='zeromq', value=1, format='int')
67 # opObj13.addParameter(name='server', value="juanca", format='str')
77 # opObj13.addParameter(name='server', value="juanca", format='str')
68
78
69 opObj12.addParameter(name='delay', value=1, format='int')
79 opObj12.addParameter(name='delay', value=0, format='int')
70
80
71
81
72 # print "Escribiendo el archivo XML"
82 # print "Escribiendo el archivo XML"
73 # controllerObj.writeXml(filename)
83 # controllerObj.writeXml(filename)
74 # print "Leyendo el archivo XML"
84 # print "Leyendo el archivo XML"
75 # controllerObj.readXml(filename)
85 # controllerObj.readXml(filename)
76
86
77
87
78 # timeit.timeit('controllerObj.run()', number=2)
88 # timeit.timeit('controllerObj.run()', number=2)
79
89
80 controllerObj.start()
90 controllerObj.start()
81
91
82
92
83 if __name__ == '__main__':
93 if __name__ == '__main__':
84 parser = argparse.ArgumentParser(description='Set number of parallel processes')
94 parser = argparse.ArgumentParser(description='Set number of parallel processes')
85 parser.add_argument('--nProcess', default=1, type=int)
95 parser.add_argument('--nProcess', default=1, type=int)
86 args = parser.parse_args()
96 args = parser.parse_args()
87 multiSchain(fiber, nProcess=args.nProcess, startDate='2015/09/26', endDate='2015/09/26')
97 multiSchain(fiber, nProcess=args.nProcess, startDate='2017/01/26', endDate='2017/01/28')
@@ -1,75 +1,97
1 #!/usr/bin/env python
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/hysell_data20/pdata" /><Parameter format="date" id="191113" name="startDate" value="2015/09/26" /><Parameter format="date" id="191114" name="endDate" value="2015/09/26" /><Parameter format="time" id="191115" name="startTime" value="00:00:00" /><Parameter format="time" id="191116" name="endTime" value="23:59:59" /><Parameter format="int" id="191118" name="cursor" value="2" /><Parameter format="int" id="191119" name="skip" value="720" /><Parameter format="int" id="191120" name="delay" value="10" /><Parameter format="int" id="191121" name="walk" value="1" /><Parameter format="int" id="191122" name="online" value="0" /></Operation></ReadUnit><ProcUnit datatype="ParametersProc" id="1913" inputId="1911" name="ParametersProc"><Operation id="19131" name="run" priority="1" type="self" /><Operation id="19132" name="SpectralMoments" priority="2" type="other" /><Operation id="19133" name="PublishData" priority="3" type="other"><Parameter format="int" id="191331" name="zeromq" value="1" /><Parameter format="int" id="191332" name="delay" value="1" /></Operation></ProcUnit><ProcUnit datatype="Spectra" id="1912" inputId="1911" name="SpectraProc"><Operation id="19121" name="run" priority="1" type="self" /></ProcUnit></Project> No newline at end of file
1 <Project description="HF_EXAMPLE" id="191" name="test01"><ReadUnit datatype="SpectraReader" id="1911" inputId="0" name="SpectraReader"><Operation id="19111" name="run" priority="1" type="self"><Parameter format="str" id="191111" name="datatype" value="SpectraReader" /><Parameter format="str" id="191112" name="path" value="/home/nanosat/data/sp1_f0" /><Parameter format="date" id="191113" name="startDate" value="2017/01/28" /><Parameter format="date" id="191114" name="endDate" value="2017/01/28" /><Parameter format="time" id="191115" name="startTime" value="00:00:00" /><Parameter format="time" id="191116" name="endTime" value="23:59:59" /><Parameter format="int" id="191118" name="cursor" value="28" /><Parameter format="int" id="191119" name="skip" value="22" /><Parameter format="int" id="191120" name="walk" value="1" /><Parameter format="int" id="191121" name="verbose" value="1" /><Parameter format="int" id="191122" name="online" value="0" /></Operation></ReadUnit><ProcUnit datatype="ParametersProc" id="1913" inputId="1911" name="ParametersProc"><Operation id="19131" name="run" priority="1" type="self" /><Operation id="19132" name="SpectralMoments" priority="2" type="other" /><Operation id="19133" name="PublishData" priority="3" type="other"><Parameter format="int" id="191331" name="zeromq" value="1" /><Parameter format="bool" id="191332" name="verbose" value="0" /><Parameter format="int" id="191333" name="delay" value="0" /></Operation></ProcUnit><ProcUnit datatype="Spectra" id="1912" inputId="1911" name="SpectraProc"><Operation id="19121" name="run" priority="1" type="self" /></ProcUnit></Project> No newline at end of file
@@ -1,48 +1,49
1 '''
1 '''
2 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