##// END OF EJS Templates
Bug fixed in Signal Chain GUI: Updating FTP configuration from old SendByFTP operation.
Miguel Valdez -
r607:bc5d3588d2df
parent child
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,1209 +1,1209
1 '''
1 '''
2 Created on September , 2012
2 Created on September , 2012
3 @author:
3 @author:
4 '''
4 '''
5 from xml.etree.ElementTree import Element, SubElement
5 from xml.etree.ElementTree import Element, SubElement
6 from xml.etree import ElementTree as ET
6 from xml.etree import ElementTree as ET
7 from xml.dom import minidom
7 from xml.dom import minidom
8
8
9 #import datetime
9 #import datetime
10 from model import *
10 from model import *
11
11
12 try:
12 try:
13 from gevent import sleep
13 from gevent import sleep
14 except:
14 except:
15 from time import sleep
15 from time import sleep
16
16
17 import ast
17 import ast
18
18
19 def prettify(elem):
19 def prettify(elem):
20 """Return a pretty-printed XML string for the Element.
20 """Return a pretty-printed XML string for the Element.
21 """
21 """
22 rough_string = ET.tostring(elem, 'utf-8')
22 rough_string = ET.tostring(elem, 'utf-8')
23 reparsed = minidom.parseString(rough_string)
23 reparsed = minidom.parseString(rough_string)
24 return reparsed.toprettyxml(indent=" ")
24 return reparsed.toprettyxml(indent=" ")
25
25
26 class ParameterConf():
26 class ParameterConf():
27
27
28 id = None
28 id = None
29 name = None
29 name = None
30 value = None
30 value = None
31 format = None
31 format = None
32
32
33 __formated_value = None
33 __formated_value = None
34
34
35 ELEMENTNAME = 'Parameter'
35 ELEMENTNAME = 'Parameter'
36
36
37 def __init__(self):
37 def __init__(self):
38
38
39 self.format = 'str'
39 self.format = 'str'
40
40
41 def getElementName(self):
41 def getElementName(self):
42
42
43 return self.ELEMENTNAME
43 return self.ELEMENTNAME
44
44
45 def getValue(self):
45 def getValue(self):
46
46
47 value = self.value
47 value = self.value
48 format = self.format
48 format = self.format
49
49
50 if self.__formated_value != None:
50 if self.__formated_value != None:
51
51
52 return self.__formated_value
52 return self.__formated_value
53
53
54 if format == 'str':
54 if format == 'str':
55 self.__formated_value = str(value)
55 self.__formated_value = str(value)
56 return self.__formated_value
56 return self.__formated_value
57
57
58 if value == '':
58 if value == '':
59 raise ValueError, "%s: This parameter value is empty" %self.name
59 raise ValueError, "%s: This parameter value is empty" %self.name
60
60
61 if format == 'bool':
61 if format == 'bool':
62 value = int(value)
62 value = int(value)
63
63
64 if format == 'list':
64 if format == 'list':
65 strList = value.split(',')
65 strList = value.split(',')
66
66
67 self.__formated_value = strList
67 self.__formated_value = strList
68
68
69 return self.__formated_value
69 return self.__formated_value
70
70
71 if format == 'intlist':
71 if format == 'intlist':
72 """
72 """
73 Example:
73 Example:
74 value = (0,1,2)
74 value = (0,1,2)
75 """
75 """
76 value = value.replace('(', '')
76 value = value.replace('(', '')
77 value = value.replace(')', '')
77 value = value.replace(')', '')
78
78
79 value = value.replace('[', '')
79 value = value.replace('[', '')
80 value = value.replace(']', '')
80 value = value.replace(']', '')
81
81
82 strList = value.split(',')
82 strList = value.split(',')
83 intList = [int(x) for x in strList]
83 intList = [int(x) for x in strList]
84
84
85 self.__formated_value = intList
85 self.__formated_value = intList
86
86
87 return self.__formated_value
87 return self.__formated_value
88
88
89 if format == 'floatlist':
89 if format == 'floatlist':
90 """
90 """
91 Example:
91 Example:
92 value = (0.5, 1.4, 2.7)
92 value = (0.5, 1.4, 2.7)
93 """
93 """
94
94
95 value = value.replace('(', '')
95 value = value.replace('(', '')
96 value = value.replace(')', '')
96 value = value.replace(')', '')
97
97
98 value = value.replace('[', '')
98 value = value.replace('[', '')
99 value = value.replace(']', '')
99 value = value.replace(']', '')
100
100
101 strList = value.split(',')
101 strList = value.split(',')
102 floatList = [float(x) for x in strList]
102 floatList = [float(x) for x in strList]
103
103
104 self.__formated_value = floatList
104 self.__formated_value = floatList
105
105
106 return self.__formated_value
106 return self.__formated_value
107
107
108 if format == 'date':
108 if format == 'date':
109 strList = value.split('/')
109 strList = value.split('/')
110 intList = [int(x) for x in strList]
110 intList = [int(x) for x in strList]
111 date = datetime.date(intList[0], intList[1], intList[2])
111 date = datetime.date(intList[0], intList[1], intList[2])
112
112
113 self.__formated_value = date
113 self.__formated_value = date
114
114
115 return self.__formated_value
115 return self.__formated_value
116
116
117 if format == 'time':
117 if format == 'time':
118 strList = value.split(':')
118 strList = value.split(':')
119 intList = [int(x) for x in strList]
119 intList = [int(x) for x in strList]
120 time = datetime.time(intList[0], intList[1], intList[2])
120 time = datetime.time(intList[0], intList[1], intList[2])
121
121
122 self.__formated_value = time
122 self.__formated_value = time
123
123
124 return self.__formated_value
124 return self.__formated_value
125
125
126 if format == 'pairslist':
126 if format == 'pairslist':
127 """
127 """
128 Example:
128 Example:
129 value = (0,1),(1,2)
129 value = (0,1),(1,2)
130 """
130 """
131
131
132 value = value.replace('(', '')
132 value = value.replace('(', '')
133 value = value.replace(')', '')
133 value = value.replace(')', '')
134
134
135 value = value.replace('[', '')
135 value = value.replace('[', '')
136 value = value.replace(']', '')
136 value = value.replace(']', '')
137
137
138 strList = value.split(',')
138 strList = value.split(',')
139 intList = [int(item) for item in strList]
139 intList = [int(item) for item in strList]
140 pairList = []
140 pairList = []
141 for i in range(len(intList)/2):
141 for i in range(len(intList)/2):
142 pairList.append((intList[i*2], intList[i*2 + 1]))
142 pairList.append((intList[i*2], intList[i*2 + 1]))
143
143
144 self.__formated_value = pairList
144 self.__formated_value = pairList
145
145
146 return self.__formated_value
146 return self.__formated_value
147
147
148 if format == 'multilist':
148 if format == 'multilist':
149 """
149 """
150 Example:
150 Example:
151 value = (0,1,2),(3,4,5)
151 value = (0,1,2),(3,4,5)
152 """
152 """
153 multiList = ast.literal_eval(value)
153 multiList = ast.literal_eval(value)
154
154
155 if type(multiList[0]) == int:
155 if type(multiList[0]) == int:
156 multiList = ast.literal_eval("(" + value + ")")
156 multiList = ast.literal_eval("(" + value + ")")
157
157
158 self.__formated_value = multiList
158 self.__formated_value = multiList
159
159
160 return self.__formated_value
160 return self.__formated_value
161
161
162 format_func = eval(format)
162 format_func = eval(format)
163
163
164 self.__formated_value = format_func(value)
164 self.__formated_value = format_func(value)
165
165
166 return self.__formated_value
166 return self.__formated_value
167
167
168 def updateId(self, new_id):
168 def updateId(self, new_id):
169
169
170 self.id = str(new_id)
170 self.id = str(new_id)
171
171
172 def setup(self, id, name, value, format='str'):
172 def setup(self, id, name, value, format='str'):
173
173
174 self.id = str(id)
174 self.id = str(id)
175 self.name = name
175 self.name = name
176 self.value = str(value)
176 self.value = str(value)
177 self.format = str.lower(format)
177 self.format = str.lower(format)
178
178
179 def update(self, name, value, format='str'):
179 def update(self, name, value, format='str'):
180
180
181 self.name = name
181 self.name = name
182 self.value = str(value)
182 self.value = str(value)
183 self.format = format
183 self.format = format
184
184
185 def makeXml(self, opElement):
185 def makeXml(self, opElement):
186
186
187 parmElement = SubElement(opElement, self.ELEMENTNAME)
187 parmElement = SubElement(opElement, self.ELEMENTNAME)
188 parmElement.set('id', str(self.id))
188 parmElement.set('id', str(self.id))
189 parmElement.set('name', self.name)
189 parmElement.set('name', self.name)
190 parmElement.set('value', self.value)
190 parmElement.set('value', self.value)
191 parmElement.set('format', self.format)
191 parmElement.set('format', self.format)
192
192
193 def readXml(self, parmElement):
193 def readXml(self, parmElement):
194
194
195 self.id = parmElement.get('id')
195 self.id = parmElement.get('id')
196 self.name = parmElement.get('name')
196 self.name = parmElement.get('name')
197 self.value = parmElement.get('value')
197 self.value = parmElement.get('value')
198 self.format = str.lower(parmElement.get('format'))
198 self.format = str.lower(parmElement.get('format'))
199
199
200 #Compatible with old signal chain version
200 #Compatible with old signal chain version
201 if self.format == 'int' and self.name == 'idfigure':
201 if self.format == 'int' and self.name == 'idfigure':
202 self.name = 'id'
202 self.name = 'id'
203
203
204 def printattr(self):
204 def printattr(self):
205
205
206 print "Parameter[%s]: name = %s, value = %s, format = %s" %(self.id, self.name, self.value, self.format)
206 print "Parameter[%s]: name = %s, value = %s, format = %s" %(self.id, self.name, self.value, self.format)
207
207
208 class OperationConf():
208 class OperationConf():
209
209
210 id = None
210 id = None
211 name = None
211 name = None
212 priority = None
212 priority = None
213 type = None
213 type = None
214
214
215 parmConfObjList = []
215 parmConfObjList = []
216
216
217 ELEMENTNAME = 'Operation'
217 ELEMENTNAME = 'Operation'
218
218
219 def __init__(self):
219 def __init__(self):
220
220
221 self.id = '0'
221 self.id = '0'
222 self.name = None
222 self.name = None
223 self.priority = None
223 self.priority = None
224 self.type = 'self'
224 self.type = 'self'
225
225
226
226
227 def __getNewId(self):
227 def __getNewId(self):
228
228
229 return int(self.id)*10 + len(self.parmConfObjList) + 1
229 return int(self.id)*10 + len(self.parmConfObjList) + 1
230
230
231 def updateId(self, new_id):
231 def updateId(self, new_id):
232
232
233 self.id = str(new_id)
233 self.id = str(new_id)
234
234
235 n = 1
235 n = 1
236 for parmObj in self.parmConfObjList:
236 for parmObj in self.parmConfObjList:
237
237
238 idParm = str(int(new_id)*10 + n)
238 idParm = str(int(new_id)*10 + n)
239 parmObj.updateId(idParm)
239 parmObj.updateId(idParm)
240
240
241 n += 1
241 n += 1
242
242
243 def getElementName(self):
243 def getElementName(self):
244
244
245 return self.ELEMENTNAME
245 return self.ELEMENTNAME
246
246
247 def getParameterObjList(self):
247 def getParameterObjList(self):
248
248
249 return self.parmConfObjList
249 return self.parmConfObjList
250
250
251 def getParameterObj(self, parameterName):
251 def getParameterObj(self, parameterName):
252
252
253 for parmConfObj in self.parmConfObjList:
253 for parmConfObj in self.parmConfObjList:
254
254
255 if parmConfObj.name != parameterName:
255 if parmConfObj.name != parameterName:
256 continue
256 continue
257
257
258 return parmConfObj
258 return parmConfObj
259
259
260 return None
260 return None
261
261
262 def getParameterObjfromValue(self, parameterValue):
262 def getParameterObjfromValue(self, parameterValue):
263
263
264 for parmConfObj in self.parmConfObjList:
264 for parmConfObj in self.parmConfObjList:
265
265
266 if parmConfObj.getValue() != parameterValue:
266 if parmConfObj.getValue() != parameterValue:
267 continue
267 continue
268
268
269 return parmConfObj.getValue()
269 return parmConfObj.getValue()
270
270
271 return None
271 return None
272
272
273 def getParameterValue(self, parameterName):
273 def getParameterValue(self, parameterName):
274
274
275 parameterObj = self.getParameterObj(parameterName)
275 parameterObj = self.getParameterObj(parameterName)
276
276
277 if not parameterObj:
277 # if not parameterObj:
278 return None
278 # return None
279
279
280 value = parameterObj.getValue()
280 value = parameterObj.getValue()
281
281
282 return value
282 return value
283
283
284 def setup(self, id, name, priority, type):
284 def setup(self, id, name, priority, type):
285
285
286 self.id = str(id)
286 self.id = str(id)
287 self.name = name
287 self.name = name
288 self.type = type
288 self.type = type
289 self.priority = priority
289 self.priority = priority
290
290
291 self.parmConfObjList = []
291 self.parmConfObjList = []
292
292
293 def removeParameters(self):
293 def removeParameters(self):
294
294
295 for obj in self.parmConfObjList:
295 for obj in self.parmConfObjList:
296 del obj
296 del obj
297
297
298 self.parmConfObjList = []
298 self.parmConfObjList = []
299
299
300 def addParameter(self, name, value, format='str'):
300 def addParameter(self, name, value, format='str'):
301
301
302 id = self.__getNewId()
302 id = self.__getNewId()
303
303
304 parmConfObj = ParameterConf()
304 parmConfObj = ParameterConf()
305 parmConfObj.setup(id, name, value, format)
305 parmConfObj.setup(id, name, value, format)
306
306
307 self.parmConfObjList.append(parmConfObj)
307 self.parmConfObjList.append(parmConfObj)
308
308
309 return parmConfObj
309 return parmConfObj
310
310
311 def changeParameter(self, name, value, format='str'):
311 def changeParameter(self, name, value, format='str'):
312
312
313 parmConfObj = self.getParameterObj(name)
313 parmConfObj = self.getParameterObj(name)
314 parmConfObj.update(name, value, format)
314 parmConfObj.update(name, value, format)
315
315
316 return parmConfObj
316 return parmConfObj
317
317
318 def makeXml(self, upElement):
318 def makeXml(self, upElement):
319
319
320 opElement = SubElement(upElement, self.ELEMENTNAME)
320 opElement = SubElement(upElement, self.ELEMENTNAME)
321 opElement.set('id', str(self.id))
321 opElement.set('id', str(self.id))
322 opElement.set('name', self.name)
322 opElement.set('name', self.name)
323 opElement.set('type', self.type)
323 opElement.set('type', self.type)
324 opElement.set('priority', str(self.priority))
324 opElement.set('priority', str(self.priority))
325
325
326 for parmConfObj in self.parmConfObjList:
326 for parmConfObj in self.parmConfObjList:
327 parmConfObj.makeXml(opElement)
327 parmConfObj.makeXml(opElement)
328
328
329 def readXml(self, opElement):
329 def readXml(self, opElement):
330
330
331 self.id = opElement.get('id')
331 self.id = opElement.get('id')
332 self.name = opElement.get('name')
332 self.name = opElement.get('name')
333 self.type = opElement.get('type')
333 self.type = opElement.get('type')
334 self.priority = opElement.get('priority')
334 self.priority = opElement.get('priority')
335
335
336 #Compatible with old signal chain version
336 #Compatible with old signal chain version
337 #Use of 'run' method instead 'init'
337 #Use of 'run' method instead 'init'
338 if self.type == 'self' and self.name == 'init':
338 if self.type == 'self' and self.name == 'init':
339 self.name = 'run'
339 self.name = 'run'
340
340
341 self.parmConfObjList = []
341 self.parmConfObjList = []
342
342
343 parmElementList = opElement.getiterator(ParameterConf().getElementName())
343 parmElementList = opElement.getiterator(ParameterConf().getElementName())
344
344
345 for parmElement in parmElementList:
345 for parmElement in parmElementList:
346 parmConfObj = ParameterConf()
346 parmConfObj = ParameterConf()
347 parmConfObj.readXml(parmElement)
347 parmConfObj.readXml(parmElement)
348
348
349 #Compatible with old signal chain version
349 #Compatible with old signal chain version
350 #If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER
350 #If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER
351 if self.type != 'self' and self.name == 'Plot':
351 if self.type != 'self' and self.name == 'Plot':
352 if parmConfObj.format == 'str' and parmConfObj.name == 'type':
352 if parmConfObj.format == 'str' and parmConfObj.name == 'type':
353 self.name = parmConfObj.value
353 self.name = parmConfObj.value
354 continue
354 continue
355
355
356 self.parmConfObjList.append(parmConfObj)
356 self.parmConfObjList.append(parmConfObj)
357
357
358 def printattr(self):
358 def printattr(self):
359
359
360 print "%s[%s]: name = %s, type = %s, priority = %s" %(self.ELEMENTNAME,
360 print "%s[%s]: name = %s, type = %s, priority = %s" %(self.ELEMENTNAME,
361 self.id,
361 self.id,
362 self.name,
362 self.name,
363 self.type,
363 self.type,
364 self.priority)
364 self.priority)
365
365
366 for parmConfObj in self.parmConfObjList:
366 for parmConfObj in self.parmConfObjList:
367 parmConfObj.printattr()
367 parmConfObj.printattr()
368
368
369 def createObject(self):
369 def createObject(self):
370
370
371 if self.type == 'self':
371 if self.type == 'self':
372 raise ValueError, "This operation type cannot be created"
372 raise ValueError, "This operation type cannot be created"
373
373
374 if self.type == 'external' or self.type == 'other':
374 if self.type == 'external' or self.type == 'other':
375 className = eval(self.name)
375 className = eval(self.name)
376 opObj = className()
376 opObj = className()
377
377
378 return opObj
378 return opObj
379
379
380 class ProcUnitConf():
380 class ProcUnitConf():
381
381
382 id = None
382 id = None
383 name = None
383 name = None
384 datatype = None
384 datatype = None
385 inputId = None
385 inputId = None
386 parentId = None
386 parentId = None
387
387
388 opConfObjList = []
388 opConfObjList = []
389
389
390 procUnitObj = None
390 procUnitObj = None
391 opObjList = []
391 opObjList = []
392
392
393 ELEMENTNAME = 'ProcUnit'
393 ELEMENTNAME = 'ProcUnit'
394
394
395 def __init__(self):
395 def __init__(self):
396
396
397 self.id = None
397 self.id = None
398 self.datatype = None
398 self.datatype = None
399 self.name = None
399 self.name = None
400 self.inputId = None
400 self.inputId = None
401
401
402 self.opConfObjList = []
402 self.opConfObjList = []
403
403
404 self.procUnitObj = None
404 self.procUnitObj = None
405 self.opObjDict = {}
405 self.opObjDict = {}
406
406
407 def __getPriority(self):
407 def __getPriority(self):
408
408
409 return len(self.opConfObjList)+1
409 return len(self.opConfObjList)+1
410
410
411 def __getNewId(self):
411 def __getNewId(self):
412
412
413 return int(self.id)*10 + len(self.opConfObjList) + 1
413 return int(self.id)*10 + len(self.opConfObjList) + 1
414
414
415 def getElementName(self):
415 def getElementName(self):
416
416
417 return self.ELEMENTNAME
417 return self.ELEMENTNAME
418
418
419 def getId(self):
419 def getId(self):
420
420
421 return self.id
421 return self.id
422
422
423 def updateId(self, new_id, parentId=parentId):
423 def updateId(self, new_id, parentId=parentId):
424
424
425
425
426 new_id = int(parentId)*10 + (int(self.id) % 10)
426 new_id = int(parentId)*10 + (int(self.id) % 10)
427 new_inputId = int(parentId)*10 + (int(self.inputId) % 10)
427 new_inputId = int(parentId)*10 + (int(self.inputId) % 10)
428
428
429 #If this proc unit has not inputs
429 #If this proc unit has not inputs
430 if self.inputId == '0':
430 if self.inputId == '0':
431 new_inputId = 0
431 new_inputId = 0
432
432
433 n = 1
433 n = 1
434 for opConfObj in self.opConfObjList:
434 for opConfObj in self.opConfObjList:
435
435
436 idOp = str(int(new_id)*10 + n)
436 idOp = str(int(new_id)*10 + n)
437 opConfObj.updateId(idOp)
437 opConfObj.updateId(idOp)
438
438
439 n += 1
439 n += 1
440
440
441 self.parentId = str(parentId)
441 self.parentId = str(parentId)
442 self.id = str(new_id)
442 self.id = str(new_id)
443 self.inputId = str(new_inputId)
443 self.inputId = str(new_inputId)
444
444
445
445
446 def getInputId(self):
446 def getInputId(self):
447
447
448 return self.inputId
448 return self.inputId
449
449
450 def getOperationObjList(self):
450 def getOperationObjList(self):
451
451
452 return self.opConfObjList
452 return self.opConfObjList
453
453
454 def getOperationObj(self, name=None):
454 def getOperationObj(self, name=None):
455
455
456 for opConfObj in self.opConfObjList:
456 for opConfObj in self.opConfObjList:
457
457
458 if opConfObj.name != name:
458 if opConfObj.name != name:
459 continue
459 continue
460
460
461 return opConfObj
461 return opConfObj
462
462
463 return None
463 return None
464
464
465 def getOpObjfromParamValue(self, value=None):
465 def getOpObjfromParamValue(self, value=None):
466
466
467 for opConfObj in self.opConfObjList:
467 for opConfObj in self.opConfObjList:
468 if opConfObj.getParameterObjfromValue(parameterValue=value) != value:
468 if opConfObj.getParameterObjfromValue(parameterValue=value) != value:
469 continue
469 continue
470 return opConfObj
470 return opConfObj
471 return None
471 return None
472
472
473 def getProcUnitObj(self):
473 def getProcUnitObj(self):
474
474
475 return self.procUnitObj
475 return self.procUnitObj
476
476
477 def setup(self, id, name, datatype, inputId, parentId=None):
477 def setup(self, id, name, datatype, inputId, parentId=None):
478
478
479 #Compatible with old signal chain version
479 #Compatible with old signal chain version
480 if datatype==None and name==None:
480 if datatype==None and name==None:
481 raise ValueError, "datatype or name should be defined"
481 raise ValueError, "datatype or name should be defined"
482
482
483 if name==None:
483 if name==None:
484 if 'Proc' in datatype:
484 if 'Proc' in datatype:
485 name = datatype
485 name = datatype
486 else:
486 else:
487 name = '%sProc' %(datatype)
487 name = '%sProc' %(datatype)
488
488
489 if datatype==None:
489 if datatype==None:
490 datatype = name.replace('Proc','')
490 datatype = name.replace('Proc','')
491
491
492 self.id = str(id)
492 self.id = str(id)
493 self.name = name
493 self.name = name
494 self.datatype = datatype
494 self.datatype = datatype
495 self.inputId = inputId
495 self.inputId = inputId
496 self.parentId = parentId
496 self.parentId = parentId
497
497
498 self.opConfObjList = []
498 self.opConfObjList = []
499
499
500 self.addOperation(name='run', optype='self')
500 self.addOperation(name='run', optype='self')
501
501
502 def removeOperations(self):
502 def removeOperations(self):
503
503
504 for obj in self.opConfObjList:
504 for obj in self.opConfObjList:
505 del obj
505 del obj
506
506
507 self.opConfObjList = []
507 self.opConfObjList = []
508 self.addOperation(name='run')
508 self.addOperation(name='run')
509
509
510 def addParameter(self, **kwargs):
510 def addParameter(self, **kwargs):
511 '''
511 '''
512 Add parameters to "run" operation
512 Add parameters to "run" operation
513 '''
513 '''
514 opObj = self.opConfObjList[0]
514 opObj = self.opConfObjList[0]
515
515
516 opObj.addParameter(**kwargs)
516 opObj.addParameter(**kwargs)
517
517
518 return opObj
518 return opObj
519
519
520 def addOperation(self, name, optype='self'):
520 def addOperation(self, name, optype='self'):
521
521
522 id = self.__getNewId()
522 id = self.__getNewId()
523 priority = self.__getPriority()
523 priority = self.__getPriority()
524
524
525 opConfObj = OperationConf()
525 opConfObj = OperationConf()
526 opConfObj.setup(id, name=name, priority=priority, type=optype)
526 opConfObj.setup(id, name=name, priority=priority, type=optype)
527
527
528 self.opConfObjList.append(opConfObj)
528 self.opConfObjList.append(opConfObj)
529
529
530 return opConfObj
530 return opConfObj
531
531
532 def makeXml(self, procUnitElement):
532 def makeXml(self, procUnitElement):
533
533
534 upElement = SubElement(procUnitElement, self.ELEMENTNAME)
534 upElement = SubElement(procUnitElement, self.ELEMENTNAME)
535 upElement.set('id', str(self.id))
535 upElement.set('id', str(self.id))
536 upElement.set('name', self.name)
536 upElement.set('name', self.name)
537 upElement.set('datatype', self.datatype)
537 upElement.set('datatype', self.datatype)
538 upElement.set('inputId', str(self.inputId))
538 upElement.set('inputId', str(self.inputId))
539
539
540 for opConfObj in self.opConfObjList:
540 for opConfObj in self.opConfObjList:
541 opConfObj.makeXml(upElement)
541 opConfObj.makeXml(upElement)
542
542
543 def readXml(self, upElement):
543 def readXml(self, upElement):
544
544
545 self.id = upElement.get('id')
545 self.id = upElement.get('id')
546 self.name = upElement.get('name')
546 self.name = upElement.get('name')
547 self.datatype = upElement.get('datatype')
547 self.datatype = upElement.get('datatype')
548 self.inputId = upElement.get('inputId')
548 self.inputId = upElement.get('inputId')
549
549
550 if self.ELEMENTNAME == "ReadUnit":
550 if self.ELEMENTNAME == "ReadUnit":
551 self.datatype = self.datatype.replace("Reader", "")
551 self.datatype = self.datatype.replace("Reader", "")
552
552
553 if self.ELEMENTNAME == "ProcUnit":
553 if self.ELEMENTNAME == "ProcUnit":
554 self.datatype = self.datatype.replace("Proc", "")
554 self.datatype = self.datatype.replace("Proc", "")
555
555
556 if self.inputId == 'None':
556 if self.inputId == 'None':
557 self.inputId = '0'
557 self.inputId = '0'
558
558
559 self.opConfObjList = []
559 self.opConfObjList = []
560
560
561 opElementList = upElement.getiterator(OperationConf().getElementName())
561 opElementList = upElement.getiterator(OperationConf().getElementName())
562
562
563 for opElement in opElementList:
563 for opElement in opElementList:
564 opConfObj = OperationConf()
564 opConfObj = OperationConf()
565 opConfObj.readXml(opElement)
565 opConfObj.readXml(opElement)
566 self.opConfObjList.append(opConfObj)
566 self.opConfObjList.append(opConfObj)
567
567
568 def printattr(self):
568 def printattr(self):
569
569
570 print "%s[%s]: name = %s, datatype = %s, inputId = %s" %(self.ELEMENTNAME,
570 print "%s[%s]: name = %s, datatype = %s, inputId = %s" %(self.ELEMENTNAME,
571 self.id,
571 self.id,
572 self.name,
572 self.name,
573 self.datatype,
573 self.datatype,
574 self.inputId)
574 self.inputId)
575
575
576 for opConfObj in self.opConfObjList:
576 for opConfObj in self.opConfObjList:
577 opConfObj.printattr()
577 opConfObj.printattr()
578
578
579 def createObjects(self):
579 def createObjects(self):
580
580
581 className = eval(self.name)
581 className = eval(self.name)
582 procUnitObj = className()
582 procUnitObj = className()
583
583
584 for opConfObj in self.opConfObjList:
584 for opConfObj in self.opConfObjList:
585
585
586 if opConfObj.type == 'self':
586 if opConfObj.type == 'self':
587 continue
587 continue
588
588
589 opObj = opConfObj.createObject()
589 opObj = opConfObj.createObject()
590
590
591 self.opObjDict[opConfObj.id] = opObj
591 self.opObjDict[opConfObj.id] = opObj
592 procUnitObj.addOperation(opObj, opConfObj.id)
592 procUnitObj.addOperation(opObj, opConfObj.id)
593
593
594 self.procUnitObj = procUnitObj
594 self.procUnitObj = procUnitObj
595
595
596 return procUnitObj
596 return procUnitObj
597
597
598 def run(self):
598 def run(self):
599
599
600 finalSts = False
600 finalSts = False
601
601
602 for opConfObj in self.opConfObjList:
602 for opConfObj in self.opConfObjList:
603
603
604 kwargs = {}
604 kwargs = {}
605 for parmConfObj in opConfObj.getParameterObjList():
605 for parmConfObj in opConfObj.getParameterObjList():
606 if opConfObj.name == 'run' and parmConfObj.name == 'datatype':
606 if opConfObj.name == 'run' and parmConfObj.name == 'datatype':
607 continue
607 continue
608
608
609 kwargs[parmConfObj.name] = parmConfObj.getValue()
609 kwargs[parmConfObj.name] = parmConfObj.getValue()
610
610
611 #print "\tRunning the '%s' operation with %s" %(opConfObj.name, opConfObj.id)
611 #print "\tRunning the '%s' operation with %s" %(opConfObj.name, opConfObj.id)
612 sts = self.procUnitObj.call(opType = opConfObj.type,
612 sts = self.procUnitObj.call(opType = opConfObj.type,
613 opName = opConfObj.name,
613 opName = opConfObj.name,
614 opId = opConfObj.id,
614 opId = opConfObj.id,
615 **kwargs)
615 **kwargs)
616 finalSts = finalSts or sts
616 finalSts = finalSts or sts
617
617
618 return finalSts
618 return finalSts
619
619
620 def close(self):
620 def close(self):
621
621
622 for opConfObj in self.opConfObjList:
622 for opConfObj in self.opConfObjList:
623 if opConfObj.type == 'self':
623 if opConfObj.type == 'self':
624 continue
624 continue
625
625
626 opObj = self.procUnitObj.getOperationObj(opConfObj.id)
626 opObj = self.procUnitObj.getOperationObj(opConfObj.id)
627 opObj.close()
627 opObj.close()
628
628
629 self.procUnitObj.close()
629 self.procUnitObj.close()
630
630
631 return
631 return
632
632
633 class ReadUnitConf(ProcUnitConf):
633 class ReadUnitConf(ProcUnitConf):
634
634
635 path = None
635 path = None
636 startDate = None
636 startDate = None
637 endDate = None
637 endDate = None
638 startTime = None
638 startTime = None
639 endTime = None
639 endTime = None
640
640
641 ELEMENTNAME = 'ReadUnit'
641 ELEMENTNAME = 'ReadUnit'
642
642
643 def __init__(self):
643 def __init__(self):
644
644
645 self.id = None
645 self.id = None
646 self.datatype = None
646 self.datatype = None
647 self.name = None
647 self.name = None
648 self.inputId = None
648 self.inputId = None
649
649
650 self.parentId = None
650 self.parentId = None
651
651
652 self.opConfObjList = []
652 self.opConfObjList = []
653 self.opObjList = []
653 self.opObjList = []
654
654
655 def getElementName(self):
655 def getElementName(self):
656
656
657 return self.ELEMENTNAME
657 return self.ELEMENTNAME
658
658
659 def setup(self, id, name, datatype, path, startDate="", endDate="", startTime="", endTime="", parentId=None, **kwargs):
659 def setup(self, id, name, datatype, path, startDate="", endDate="", startTime="", endTime="", parentId=None, **kwargs):
660
660
661 #Compatible with old signal chain version
661 #Compatible with old signal chain version
662 if datatype==None and name==None:
662 if datatype==None and name==None:
663 raise ValueError, "datatype or name should be defined"
663 raise ValueError, "datatype or name should be defined"
664
664
665 if name==None:
665 if name==None:
666 if 'Reader' in datatype:
666 if 'Reader' in datatype:
667 name = datatype
667 name = datatype
668 else:
668 else:
669 name = '%sReader' %(datatype)
669 name = '%sReader' %(datatype)
670
670
671 if datatype==None:
671 if datatype==None:
672 datatype = name.replace('Reader','')
672 datatype = name.replace('Reader','')
673
673
674 self.id = id
674 self.id = id
675 self.name = name
675 self.name = name
676 self.datatype = datatype
676 self.datatype = datatype
677
677
678 self.path = path
678 self.path = path
679 self.startDate = startDate
679 self.startDate = startDate
680 self.endDate = endDate
680 self.endDate = endDate
681 self.startTime = startTime
681 self.startTime = startTime
682 self.endTime = endTime
682 self.endTime = endTime
683
683
684 self.inputId = '0'
684 self.inputId = '0'
685 self.parentId = parentId
685 self.parentId = parentId
686
686
687 self.addRunOperation(**kwargs)
687 self.addRunOperation(**kwargs)
688
688
689 def update(self, datatype, path, startDate, endDate, startTime, endTime, parentId=None, name=None, **kwargs):
689 def update(self, datatype, path, startDate, endDate, startTime, endTime, parentId=None, name=None, **kwargs):
690
690
691 #Compatible with old signal chain version
691 #Compatible with old signal chain version
692 if datatype==None and name==None:
692 if datatype==None and name==None:
693 raise ValueError, "datatype or name should be defined"
693 raise ValueError, "datatype or name should be defined"
694
694
695 if name==None:
695 if name==None:
696 if 'Reader' in datatype:
696 if 'Reader' in datatype:
697 name = datatype
697 name = datatype
698 else:
698 else:
699 name = '%sReader' %(datatype)
699 name = '%sReader' %(datatype)
700
700
701 if datatype==None:
701 if datatype==None:
702 datatype = name.replace('Reader','')
702 datatype = name.replace('Reader','')
703
703
704 self.datatype = datatype
704 self.datatype = datatype
705 self.name = name
705 self.name = name
706 self.path = path
706 self.path = path
707 self.startDate = startDate
707 self.startDate = startDate
708 self.endDate = endDate
708 self.endDate = endDate
709 self.startTime = startTime
709 self.startTime = startTime
710 self.endTime = endTime
710 self.endTime = endTime
711
711
712 self.inputId = '0'
712 self.inputId = '0'
713 self.parentId = parentId
713 self.parentId = parentId
714
714
715 self.updateRunOperation(**kwargs)
715 self.updateRunOperation(**kwargs)
716
716
717 def addRunOperation(self, **kwargs):
717 def addRunOperation(self, **kwargs):
718
718
719 opObj = self.addOperation(name = 'run', optype = 'self')
719 opObj = self.addOperation(name = 'run', optype = 'self')
720
720
721 opObj.addParameter(name='datatype' , value=self.datatype, format='str')
721 opObj.addParameter(name='datatype' , value=self.datatype, format='str')
722 opObj.addParameter(name='path' , value=self.path, format='str')
722 opObj.addParameter(name='path' , value=self.path, format='str')
723 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
723 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
724 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
724 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
725 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
725 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
726 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
726 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
727
727
728 for key, value in kwargs.items():
728 for key, value in kwargs.items():
729 opObj.addParameter(name=key, value=value, format=type(value).__name__)
729 opObj.addParameter(name=key, value=value, format=type(value).__name__)
730
730
731 return opObj
731 return opObj
732
732
733 def updateRunOperation(self, **kwargs):
733 def updateRunOperation(self, **kwargs):
734
734
735 opObj = self.getOperationObj(name = 'run')
735 opObj = self.getOperationObj(name = 'run')
736 opObj.removeParameters()
736 opObj.removeParameters()
737
737
738 opObj.addParameter(name='datatype' , value=self.datatype, format='str')
738 opObj.addParameter(name='datatype' , value=self.datatype, format='str')
739 opObj.addParameter(name='path' , value=self.path, format='str')
739 opObj.addParameter(name='path' , value=self.path, format='str')
740 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
740 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
741 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
741 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
742 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
742 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
743 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
743 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
744
744
745 for key, value in kwargs.items():
745 for key, value in kwargs.items():
746 opObj.addParameter(name=key, value=value, format=type(value).__name__)
746 opObj.addParameter(name=key, value=value, format=type(value).__name__)
747
747
748 return opObj
748 return opObj
749
749
750 class Project():
750 class Project():
751
751
752 id = None
752 id = None
753 name = None
753 name = None
754 description = None
754 description = None
755 # readUnitConfObjList = None
755 # readUnitConfObjList = None
756 procUnitConfObjDict = None
756 procUnitConfObjDict = None
757
757
758 ELEMENTNAME = 'Project'
758 ELEMENTNAME = 'Project'
759
759
760 def __init__(self, control=None, dataq=None):
760 def __init__(self, control=None, dataq=None):
761
761
762 self.id = None
762 self.id = None
763 self.name = None
763 self.name = None
764 self.description = None
764 self.description = None
765
765
766 self.procUnitConfObjDict = {}
766 self.procUnitConfObjDict = {}
767
767
768 #global data_q
768 #global data_q
769 #data_q = dataq
769 #data_q = dataq
770
770
771 if control==None:
771 if control==None:
772 control = {'stop':False,'pause':False}
772 control = {'stop':False,'pause':False}
773
773
774 self.control = control
774 self.control = control
775
775
776 def __getNewId(self):
776 def __getNewId(self):
777
777
778 id = int(self.id)*10 + len(self.procUnitConfObjDict) + 1
778 id = int(self.id)*10 + len(self.procUnitConfObjDict) + 1
779
779
780 return str(id)
780 return str(id)
781
781
782 def getElementName(self):
782 def getElementName(self):
783
783
784 return self.ELEMENTNAME
784 return self.ELEMENTNAME
785
785
786 def getId(self):
786 def getId(self):
787
787
788 return self.id
788 return self.id
789
789
790 def updateId(self, new_id):
790 def updateId(self, new_id):
791
791
792 self.id = str(new_id)
792 self.id = str(new_id)
793
793
794 keyList = self.procUnitConfObjDict.keys()
794 keyList = self.procUnitConfObjDict.keys()
795 keyList.sort()
795 keyList.sort()
796
796
797 n = 1
797 n = 1
798 newProcUnitConfObjDict = {}
798 newProcUnitConfObjDict = {}
799
799
800 for procKey in keyList:
800 for procKey in keyList:
801
801
802 procUnitConfObj = self.procUnitConfObjDict[procKey]
802 procUnitConfObj = self.procUnitConfObjDict[procKey]
803 idProcUnit = str(int(self.id)*10 + n)
803 idProcUnit = str(int(self.id)*10 + n)
804 procUnitConfObj.updateId(idProcUnit, parentId = self.id)
804 procUnitConfObj.updateId(idProcUnit, parentId = self.id)
805
805
806 newProcUnitConfObjDict[idProcUnit] = procUnitConfObj
806 newProcUnitConfObjDict[idProcUnit] = procUnitConfObj
807 n += 1
807 n += 1
808
808
809 self.procUnitConfObjDict = newProcUnitConfObjDict
809 self.procUnitConfObjDict = newProcUnitConfObjDict
810
810
811 def setup(self, id, name, description):
811 def setup(self, id, name, description):
812
812
813 self.id = str(id)
813 self.id = str(id)
814 self.name = name
814 self.name = name
815 self.description = description
815 self.description = description
816
816
817 def update(self, name, description):
817 def update(self, name, description):
818
818
819 self.name = name
819 self.name = name
820 self.description = description
820 self.description = description
821
821
822 def addReadUnit(self, datatype=None, name=None, **kwargs):
822 def addReadUnit(self, datatype=None, name=None, **kwargs):
823
823
824 idReadUnit = self.__getNewId()
824 idReadUnit = self.__getNewId()
825
825
826 readUnitConfObj = ReadUnitConf()
826 readUnitConfObj = ReadUnitConf()
827 readUnitConfObj.setup(idReadUnit, name, datatype, parentId=self.id, **kwargs)
827 readUnitConfObj.setup(idReadUnit, name, datatype, parentId=self.id, **kwargs)
828
828
829 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
829 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
830
830
831 return readUnitConfObj
831 return readUnitConfObj
832
832
833 def addProcUnit(self, inputId='0', datatype=None, name=None):
833 def addProcUnit(self, inputId='0', datatype=None, name=None):
834
834
835 idProcUnit = self.__getNewId()
835 idProcUnit = self.__getNewId()
836
836
837 procUnitConfObj = ProcUnitConf()
837 procUnitConfObj = ProcUnitConf()
838 procUnitConfObj.setup(idProcUnit, name, datatype, inputId, parentId=self.id)
838 procUnitConfObj.setup(idProcUnit, name, datatype, inputId, parentId=self.id)
839
839
840 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
840 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
841
841
842 return procUnitConfObj
842 return procUnitConfObj
843
843
844 def removeProcUnit(self, id):
844 def removeProcUnit(self, id):
845
845
846 if id in self.procUnitConfObjDict.keys():
846 if id in self.procUnitConfObjDict.keys():
847 self.procUnitConfObjDict.pop(id)
847 self.procUnitConfObjDict.pop(id)
848
848
849 def getReadUnitId(self):
849 def getReadUnitId(self):
850
850
851 readUnitConfObj = self.getReadUnitObj()
851 readUnitConfObj = self.getReadUnitObj()
852
852
853 return readUnitConfObj.id
853 return readUnitConfObj.id
854
854
855 def getReadUnitObj(self):
855 def getReadUnitObj(self):
856
856
857 for obj in self.procUnitConfObjDict.values():
857 for obj in self.procUnitConfObjDict.values():
858 if obj.getElementName() == "ReadUnit":
858 if obj.getElementName() == "ReadUnit":
859 return obj
859 return obj
860
860
861 return None
861 return None
862
862
863 def getProcUnitObj(self, id=None, name=None):
863 def getProcUnitObj(self, id=None, name=None):
864
864
865 if id != None:
865 if id != None:
866 return self.procUnitConfObjDict[id]
866 return self.procUnitConfObjDict[id]
867
867
868 if name != None:
868 if name != None:
869 return self.getProcUnitObjByName(name)
869 return self.getProcUnitObjByName(name)
870
870
871 return None
871 return None
872
872
873 def getProcUnitObjByName(self, name):
873 def getProcUnitObjByName(self, name):
874
874
875 for obj in self.procUnitConfObjDict.values():
875 for obj in self.procUnitConfObjDict.values():
876 if obj.name == name:
876 if obj.name == name:
877 return obj
877 return obj
878
878
879 return None
879 return None
880
880
881 def procUnitItems(self):
881 def procUnitItems(self):
882
882
883 return self.procUnitConfObjDict.items()
883 return self.procUnitConfObjDict.items()
884
884
885 def makeXml(self):
885 def makeXml(self):
886
886
887 projectElement = Element('Project')
887 projectElement = Element('Project')
888 projectElement.set('id', str(self.id))
888 projectElement.set('id', str(self.id))
889 projectElement.set('name', self.name)
889 projectElement.set('name', self.name)
890 projectElement.set('description', self.description)
890 projectElement.set('description', self.description)
891
891
892 # for readUnitConfObj in self.readUnitConfObjList:
892 # for readUnitConfObj in self.readUnitConfObjList:
893 # readUnitConfObj.makeXml(projectElement)
893 # readUnitConfObj.makeXml(projectElement)
894
894
895 for procUnitConfObj in self.procUnitConfObjDict.values():
895 for procUnitConfObj in self.procUnitConfObjDict.values():
896 procUnitConfObj.makeXml(projectElement)
896 procUnitConfObj.makeXml(projectElement)
897
897
898 self.projectElement = projectElement
898 self.projectElement = projectElement
899
899
900 def writeXml(self, filename):
900 def writeXml(self, filename):
901
901
902 self.makeXml()
902 self.makeXml()
903
903
904 #print prettify(self.projectElement)
904 #print prettify(self.projectElement)
905
905
906 ElementTree(self.projectElement).write(filename, method='xml')
906 ElementTree(self.projectElement).write(filename, method='xml')
907
907
908 def readXml(self, filename):
908 def readXml(self, filename):
909
909
910 #tree = ET.parse(filename)
910 #tree = ET.parse(filename)
911 self.projectElement = None
911 self.projectElement = None
912 # self.readUnitConfObjList = []
912 # self.readUnitConfObjList = []
913 self.procUnitConfObjDict = {}
913 self.procUnitConfObjDict = {}
914
914
915 self.projectElement = ElementTree().parse(filename)
915 self.projectElement = ElementTree().parse(filename)
916
916
917 self.project = self.projectElement.tag
917 self.project = self.projectElement.tag
918
918
919 self.id = self.projectElement.get('id')
919 self.id = self.projectElement.get('id')
920 self.name = self.projectElement.get('name')
920 self.name = self.projectElement.get('name')
921 self.description = self.projectElement.get('description')
921 self.description = self.projectElement.get('description')
922
922
923 readUnitElementList = self.projectElement.getiterator(ReadUnitConf().getElementName())
923 readUnitElementList = self.projectElement.getiterator(ReadUnitConf().getElementName())
924
924
925 for readUnitElement in readUnitElementList:
925 for readUnitElement in readUnitElementList:
926 readUnitConfObj = ReadUnitConf()
926 readUnitConfObj = ReadUnitConf()
927 readUnitConfObj.readXml(readUnitElement)
927 readUnitConfObj.readXml(readUnitElement)
928
928
929 if readUnitConfObj.parentId == None:
929 if readUnitConfObj.parentId == None:
930 readUnitConfObj.parentId = self.id
930 readUnitConfObj.parentId = self.id
931
931
932 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
932 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
933
933
934 procUnitElementList = self.projectElement.getiterator(ProcUnitConf().getElementName())
934 procUnitElementList = self.projectElement.getiterator(ProcUnitConf().getElementName())
935
935
936 for procUnitElement in procUnitElementList:
936 for procUnitElement in procUnitElementList:
937 procUnitConfObj = ProcUnitConf()
937 procUnitConfObj = ProcUnitConf()
938 procUnitConfObj.readXml(procUnitElement)
938 procUnitConfObj.readXml(procUnitElement)
939
939
940 if procUnitConfObj.parentId == None:
940 if procUnitConfObj.parentId == None:
941 procUnitConfObj.parentId = self.id
941 procUnitConfObj.parentId = self.id
942
942
943 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
943 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
944
944
945 def printattr(self):
945 def printattr(self):
946
946
947 print "Project[%s]: name = %s, description = %s" %(self.id,
947 print "Project[%s]: name = %s, description = %s" %(self.id,
948 self.name,
948 self.name,
949 self.description)
949 self.description)
950
950
951 # for readUnitConfObj in self.readUnitConfObjList:
951 # for readUnitConfObj in self.readUnitConfObjList:
952 # readUnitConfObj.printattr()
952 # readUnitConfObj.printattr()
953
953
954 for procUnitConfObj in self.procUnitConfObjDict.values():
954 for procUnitConfObj in self.procUnitConfObjDict.values():
955 procUnitConfObj.printattr()
955 procUnitConfObj.printattr()
956
956
957 def createObjects(self):
957 def createObjects(self):
958
958
959 # for readUnitConfObj in self.readUnitConfObjList:
959 # for readUnitConfObj in self.readUnitConfObjList:
960 # readUnitConfObj.createObjects()
960 # readUnitConfObj.createObjects()
961
961
962 for procUnitConfObj in self.procUnitConfObjDict.values():
962 for procUnitConfObj in self.procUnitConfObjDict.values():
963 procUnitConfObj.createObjects()
963 procUnitConfObj.createObjects()
964
964
965 def __connect(self, objIN, thisObj):
965 def __connect(self, objIN, thisObj):
966
966
967 thisObj.setInput(objIN.getOutputObj())
967 thisObj.setInput(objIN.getOutputObj())
968
968
969 def connectObjects(self):
969 def connectObjects(self):
970
970
971 for thisPUConfObj in self.procUnitConfObjDict.values():
971 for thisPUConfObj in self.procUnitConfObjDict.values():
972
972
973 inputId = thisPUConfObj.getInputId()
973 inputId = thisPUConfObj.getInputId()
974
974
975 if int(inputId) == 0:
975 if int(inputId) == 0:
976 continue
976 continue
977
977
978 #Get input object
978 #Get input object
979 puConfINObj = self.procUnitConfObjDict[inputId]
979 puConfINObj = self.procUnitConfObjDict[inputId]
980 puObjIN = puConfINObj.getProcUnitObj()
980 puObjIN = puConfINObj.getProcUnitObj()
981
981
982 #Get current object
982 #Get current object
983 thisPUObj = thisPUConfObj.getProcUnitObj()
983 thisPUObj = thisPUConfObj.getProcUnitObj()
984
984
985 self.__connect(puObjIN, thisPUObj)
985 self.__connect(puObjIN, thisPUObj)
986
986
987 def run(self):
987 def run(self):
988
988
989 # for readUnitConfObj in self.readUnitConfObjList:
989 # for readUnitConfObj in self.readUnitConfObjList:
990 # readUnitConfObj.run()
990 # readUnitConfObj.run()
991 print
991 print
992 print "*"*40
992 print "*"*40
993 print " Starting SIGNAL CHAIN PROCESSING "
993 print " Starting SIGNAL CHAIN PROCESSING "
994 print "*"*40
994 print "*"*40
995 print
995 print
996
996
997 keyList = self.procUnitConfObjDict.keys()
997 keyList = self.procUnitConfObjDict.keys()
998 keyList.sort()
998 keyList.sort()
999
999
1000 while(True):
1000 while(True):
1001
1001
1002 finalSts = False
1002 finalSts = False
1003
1003
1004 for procKey in keyList:
1004 for procKey in keyList:
1005 # print "Running the '%s' process with %s" %(procUnitConfObj.name, procUnitConfObj.id)
1005 # print "Running the '%s' process with %s" %(procUnitConfObj.name, procUnitConfObj.id)
1006
1006
1007 procUnitConfObj = self.procUnitConfObjDict[procKey]
1007 procUnitConfObj = self.procUnitConfObjDict[procKey]
1008 sts = procUnitConfObj.run()
1008 sts = procUnitConfObj.run()
1009 finalSts = finalSts or sts
1009 finalSts = finalSts or sts
1010
1010
1011 #If every process unit finished so end process
1011 #If every process unit finished so end process
1012 if not(finalSts):
1012 if not(finalSts):
1013 print "Every process unit have finished"
1013 print "Every process unit have finished"
1014 break
1014 break
1015
1015
1016 if self.control['pause']:
1016 if self.control['pause']:
1017 print "Process suspended"
1017 print "Process suspended"
1018
1018
1019 while True:
1019 while True:
1020 sleep(0.1)
1020 sleep(0.1)
1021
1021
1022 if not self.control['pause']:
1022 if not self.control['pause']:
1023 break
1023 break
1024
1024
1025 if self.control['stop']:
1025 if self.control['stop']:
1026 break
1026 break
1027 print "Process reinitialized"
1027 print "Process reinitialized"
1028
1028
1029 if self.control['stop']:
1029 if self.control['stop']:
1030 print "Process stopped"
1030 print "Process stopped"
1031 break
1031 break
1032
1032
1033 #Closing every process
1033 #Closing every process
1034 for procKey in keyList:
1034 for procKey in keyList:
1035 procUnitConfObj = self.procUnitConfObjDict[procKey]
1035 procUnitConfObj = self.procUnitConfObjDict[procKey]
1036 procUnitConfObj.close()
1036 procUnitConfObj.close()
1037
1037
1038 print "Process finished"
1038 print "Process finished"
1039
1039
1040 def start(self, filename):
1040 def start(self, filename):
1041
1041
1042 self.writeXml(filename)
1042 self.writeXml(filename)
1043 self.readXml(filename)
1043 self.readXml(filename)
1044
1044
1045 self.createObjects()
1045 self.createObjects()
1046 self.connectObjects()
1046 self.connectObjects()
1047 self.run()
1047 self.run()
1048
1048
1049 class ControllerThread(threading.Thread, Project):
1049 class ControllerThread(threading.Thread, Project):
1050
1050
1051 def __init__(self, filename):
1051 def __init__(self, filename):
1052
1052
1053 threading.Thread.__init__(self)
1053 threading.Thread.__init__(self)
1054 Project.__init__(self)
1054 Project.__init__(self)
1055
1055
1056 self.setDaemon(True)
1056 self.setDaemon(True)
1057
1057
1058 self.filename = filename
1058 self.filename = filename
1059 self.control = {'stop':False, 'pause':False}
1059 self.control = {'stop':False, 'pause':False}
1060
1060
1061 def stop(self):
1061 def stop(self):
1062 self.control['stop'] = True
1062 self.control['stop'] = True
1063
1063
1064 def pause(self):
1064 def pause(self):
1065 self.control['pause'] = not(self.control['pause'])
1065 self.control['pause'] = not(self.control['pause'])
1066
1066
1067 def run(self):
1067 def run(self):
1068 self.control['stop'] = False
1068 self.control['stop'] = False
1069 self.control['pause'] = False
1069 self.control['pause'] = False
1070
1070
1071 self.readXml(self.filename)
1071 self.readXml(self.filename)
1072 self.createObjects()
1072 self.createObjects()
1073 self.connectObjects()
1073 self.connectObjects()
1074 Project.run(self)
1074 Project.run(self)
1075
1075
1076 if __name__ == '__main__':
1076 if __name__ == '__main__':
1077
1077
1078 desc = "Segundo Test"
1078 desc = "Segundo Test"
1079 filename = "schain.xml"
1079 filename = "schain.xml"
1080
1080
1081 controllerObj = Project()
1081 controllerObj = Project()
1082
1082
1083 controllerObj.setup(id = '191', name='test01', description=desc)
1083 controllerObj.setup(id = '191', name='test01', description=desc)
1084
1084
1085 readUnitConfObj = controllerObj.addReadUnit(datatype='Voltage',
1085 readUnitConfObj = controllerObj.addReadUnit(datatype='Voltage',
1086 path='data/rawdata/',
1086 path='data/rawdata/',
1087 startDate='2011/01/01',
1087 startDate='2011/01/01',
1088 endDate='2012/12/31',
1088 endDate='2012/12/31',
1089 startTime='00:00:00',
1089 startTime='00:00:00',
1090 endTime='23:59:59',
1090 endTime='23:59:59',
1091 online=1,
1091 online=1,
1092 walk=1)
1092 walk=1)
1093
1093
1094 # opObj00 = readUnitConfObj.addOperation(name='printInfo')
1094 # opObj00 = readUnitConfObj.addOperation(name='printInfo')
1095
1095
1096 procUnitConfObj0 = controllerObj.addProcUnit(datatype='Voltage', inputId=readUnitConfObj.getId())
1096 procUnitConfObj0 = controllerObj.addProcUnit(datatype='Voltage', inputId=readUnitConfObj.getId())
1097
1097
1098 opObj10 = procUnitConfObj0.addOperation(name='selectChannels')
1098 opObj10 = procUnitConfObj0.addOperation(name='selectChannels')
1099 opObj10.addParameter(name='channelList', value='3,4,5', format='intlist')
1099 opObj10.addParameter(name='channelList', value='3,4,5', format='intlist')
1100
1100
1101 opObj10 = procUnitConfObj0.addOperation(name='selectHeights')
1101 opObj10 = procUnitConfObj0.addOperation(name='selectHeights')
1102 opObj10.addParameter(name='minHei', value='90', format='float')
1102 opObj10.addParameter(name='minHei', value='90', format='float')
1103 opObj10.addParameter(name='maxHei', value='180', format='float')
1103 opObj10.addParameter(name='maxHei', value='180', format='float')
1104
1104
1105 opObj12 = procUnitConfObj0.addOperation(name='CohInt', optype='external')
1105 opObj12 = procUnitConfObj0.addOperation(name='CohInt', optype='external')
1106 opObj12.addParameter(name='n', value='10', format='int')
1106 opObj12.addParameter(name='n', value='10', format='int')
1107
1107
1108 procUnitConfObj1 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj0.getId())
1108 procUnitConfObj1 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj0.getId())
1109 procUnitConfObj1.addParameter(name='nFFTPoints', value='32', format='int')
1109 procUnitConfObj1.addParameter(name='nFFTPoints', value='32', format='int')
1110 # procUnitConfObj1.addParameter(name='pairList', value='(0,1),(0,2),(1,2)', format='')
1110 # procUnitConfObj1.addParameter(name='pairList', value='(0,1),(0,2),(1,2)', format='')
1111
1111
1112
1112
1113 opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
1113 opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
1114 opObj11.addParameter(name='idfigure', value='1', format='int')
1114 opObj11.addParameter(name='idfigure', value='1', format='int')
1115 opObj11.addParameter(name='wintitle', value='SpectraPlot0', format='str')
1115 opObj11.addParameter(name='wintitle', value='SpectraPlot0', format='str')
1116 opObj11.addParameter(name='zmin', value='40', format='int')
1116 opObj11.addParameter(name='zmin', value='40', format='int')
1117 opObj11.addParameter(name='zmax', value='90', format='int')
1117 opObj11.addParameter(name='zmax', value='90', format='int')
1118 opObj11.addParameter(name='showprofile', value='1', format='int')
1118 opObj11.addParameter(name='showprofile', value='1', format='int')
1119
1119
1120 # opObj11 = procUnitConfObj1.addOperation(name='CrossSpectraPlot', optype='external')
1120 # opObj11 = procUnitConfObj1.addOperation(name='CrossSpectraPlot', optype='external')
1121 # opObj11.addParameter(name='idfigure', value='2', format='int')
1121 # opObj11.addParameter(name='idfigure', value='2', format='int')
1122 # opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str')
1122 # opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str')
1123 # opObj11.addParameter(name='zmin', value='40', format='int')
1123 # opObj11.addParameter(name='zmin', value='40', format='int')
1124 # opObj11.addParameter(name='zmax', value='90', format='int')
1124 # opObj11.addParameter(name='zmax', value='90', format='int')
1125
1125
1126
1126
1127 # procUnitConfObj2 = controllerObj.addProcUnit(datatype='Voltage', inputId=procUnitConfObj0.getId())
1127 # procUnitConfObj2 = controllerObj.addProcUnit(datatype='Voltage', inputId=procUnitConfObj0.getId())
1128 #
1128 #
1129 # opObj12 = procUnitConfObj2.addOperation(name='CohInt', optype='external')
1129 # opObj12 = procUnitConfObj2.addOperation(name='CohInt', optype='external')
1130 # opObj12.addParameter(name='n', value='2', format='int')
1130 # opObj12.addParameter(name='n', value='2', format='int')
1131 # opObj12.addParameter(name='overlapping', value='1', format='int')
1131 # opObj12.addParameter(name='overlapping', value='1', format='int')
1132 #
1132 #
1133 # procUnitConfObj3 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj2.getId())
1133 # procUnitConfObj3 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj2.getId())
1134 # procUnitConfObj3.addParameter(name='nFFTPoints', value='32', format='int')
1134 # procUnitConfObj3.addParameter(name='nFFTPoints', value='32', format='int')
1135 #
1135 #
1136 # opObj11 = procUnitConfObj3.addOperation(name='SpectraPlot', optype='external')
1136 # opObj11 = procUnitConfObj3.addOperation(name='SpectraPlot', optype='external')
1137 # opObj11.addParameter(name='idfigure', value='2', format='int')
1137 # opObj11.addParameter(name='idfigure', value='2', format='int')
1138 # opObj11.addParameter(name='wintitle', value='SpectraPlot1', format='str')
1138 # opObj11.addParameter(name='wintitle', value='SpectraPlot1', format='str')
1139 # opObj11.addParameter(name='zmin', value='40', format='int')
1139 # opObj11.addParameter(name='zmin', value='40', format='int')
1140 # opObj11.addParameter(name='zmax', value='90', format='int')
1140 # opObj11.addParameter(name='zmax', value='90', format='int')
1141 # opObj11.addParameter(name='showprofile', value='1', format='int')
1141 # opObj11.addParameter(name='showprofile', value='1', format='int')
1142
1142
1143 # opObj11 = procUnitConfObj1.addOperation(name='RTIPlot', optype='external')
1143 # opObj11 = procUnitConfObj1.addOperation(name='RTIPlot', optype='external')
1144 # opObj11.addParameter(name='idfigure', value='10', format='int')
1144 # opObj11.addParameter(name='idfigure', value='10', format='int')
1145 # opObj11.addParameter(name='wintitle', value='RTI', format='str')
1145 # opObj11.addParameter(name='wintitle', value='RTI', format='str')
1146 ## opObj11.addParameter(name='xmin', value='21', format='float')
1146 ## opObj11.addParameter(name='xmin', value='21', format='float')
1147 ## opObj11.addParameter(name='xmax', value='22', format='float')
1147 ## opObj11.addParameter(name='xmax', value='22', format='float')
1148 # opObj11.addParameter(name='zmin', value='40', format='int')
1148 # opObj11.addParameter(name='zmin', value='40', format='int')
1149 # opObj11.addParameter(name='zmax', value='90', format='int')
1149 # opObj11.addParameter(name='zmax', value='90', format='int')
1150 # opObj11.addParameter(name='showprofile', value='1', format='int')
1150 # opObj11.addParameter(name='showprofile', value='1', format='int')
1151 # opObj11.addParameter(name='timerange', value=str(60), format='int')
1151 # opObj11.addParameter(name='timerange', value=str(60), format='int')
1152
1152
1153 # opObj10 = procUnitConfObj1.addOperation(name='selectChannels')
1153 # opObj10 = procUnitConfObj1.addOperation(name='selectChannels')
1154 # opObj10.addParameter(name='channelList', value='0,2,4,6', format='intlist')
1154 # opObj10.addParameter(name='channelList', value='0,2,4,6', format='intlist')
1155 #
1155 #
1156 # opObj12 = procUnitConfObj1.addOperation(name='IncohInt', optype='external')
1156 # opObj12 = procUnitConfObj1.addOperation(name='IncohInt', optype='external')
1157 # opObj12.addParameter(name='n', value='2', format='int')
1157 # opObj12.addParameter(name='n', value='2', format='int')
1158 #
1158 #
1159 # opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
1159 # opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
1160 # opObj11.addParameter(name='idfigure', value='2', format='int')
1160 # opObj11.addParameter(name='idfigure', value='2', format='int')
1161 # opObj11.addParameter(name='wintitle', value='SpectraPlot10', format='str')
1161 # opObj11.addParameter(name='wintitle', value='SpectraPlot10', format='str')
1162 # opObj11.addParameter(name='zmin', value='70', format='int')
1162 # opObj11.addParameter(name='zmin', value='70', format='int')
1163 # opObj11.addParameter(name='zmax', value='90', format='int')
1163 # opObj11.addParameter(name='zmax', value='90', format='int')
1164 #
1164 #
1165 # opObj10 = procUnitConfObj1.addOperation(name='selectChannels')
1165 # opObj10 = procUnitConfObj1.addOperation(name='selectChannels')
1166 # opObj10.addParameter(name='channelList', value='2,6', format='intlist')
1166 # opObj10.addParameter(name='channelList', value='2,6', format='intlist')
1167 #
1167 #
1168 # opObj12 = procUnitConfObj1.addOperation(name='IncohInt', optype='external')
1168 # opObj12 = procUnitConfObj1.addOperation(name='IncohInt', optype='external')
1169 # opObj12.addParameter(name='n', value='2', format='int')
1169 # opObj12.addParameter(name='n', value='2', format='int')
1170 #
1170 #
1171 # opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
1171 # opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
1172 # opObj11.addParameter(name='idfigure', value='3', format='int')
1172 # opObj11.addParameter(name='idfigure', value='3', format='int')
1173 # opObj11.addParameter(name='wintitle', value='SpectraPlot10', format='str')
1173 # opObj11.addParameter(name='wintitle', value='SpectraPlot10', format='str')
1174 # opObj11.addParameter(name='zmin', value='70', format='int')
1174 # opObj11.addParameter(name='zmin', value='70', format='int')
1175 # opObj11.addParameter(name='zmax', value='90', format='int')
1175 # opObj11.addParameter(name='zmax', value='90', format='int')
1176
1176
1177
1177
1178 # opObj12 = procUnitConfObj1.addOperation(name='decoder')
1178 # opObj12 = procUnitConfObj1.addOperation(name='decoder')
1179 # opObj12.addParameter(name='ncode', value='2', format='int')
1179 # opObj12.addParameter(name='ncode', value='2', format='int')
1180 # opObj12.addParameter(name='nbauds', value='8', format='int')
1180 # opObj12.addParameter(name='nbauds', value='8', format='int')
1181 # opObj12.addParameter(name='code0', value='001110011', format='int')
1181 # opObj12.addParameter(name='code0', value='001110011', format='int')
1182 # opObj12.addParameter(name='code1', value='001110011', format='int')
1182 # opObj12.addParameter(name='code1', value='001110011', format='int')
1183
1183
1184
1184
1185
1185
1186 # procUnitConfObj2 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj1.getId())
1186 # procUnitConfObj2 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj1.getId())
1187 #
1187 #
1188 # opObj21 = procUnitConfObj2.addOperation(name='IncohInt', optype='external')
1188 # opObj21 = procUnitConfObj2.addOperation(name='IncohInt', optype='external')
1189 # opObj21.addParameter(name='n', value='2', format='int')
1189 # opObj21.addParameter(name='n', value='2', format='int')
1190 #
1190 #
1191 # opObj11 = procUnitConfObj2.addOperation(name='SpectraPlot', optype='external')
1191 # opObj11 = procUnitConfObj2.addOperation(name='SpectraPlot', optype='external')
1192 # opObj11.addParameter(name='idfigure', value='4', format='int')
1192 # opObj11.addParameter(name='idfigure', value='4', format='int')
1193 # opObj11.addParameter(name='wintitle', value='SpectraPlot OBJ 2', format='str')
1193 # opObj11.addParameter(name='wintitle', value='SpectraPlot OBJ 2', format='str')
1194 # opObj11.addParameter(name='zmin', value='70', format='int')
1194 # opObj11.addParameter(name='zmin', value='70', format='int')
1195 # opObj11.addParameter(name='zmax', value='90', format='int')
1195 # opObj11.addParameter(name='zmax', value='90', format='int')
1196
1196
1197 print "Escribiendo el archivo XML"
1197 print "Escribiendo el archivo XML"
1198
1198
1199 controllerObj.writeXml(filename)
1199 controllerObj.writeXml(filename)
1200
1200
1201 print "Leyendo el archivo XML"
1201 print "Leyendo el archivo XML"
1202 controllerObj.readXml(filename)
1202 controllerObj.readXml(filename)
1203 #controllerObj.printattr()
1203 #controllerObj.printattr()
1204
1204
1205 controllerObj.createObjects()
1205 controllerObj.createObjects()
1206 controllerObj.connectObjects()
1206 controllerObj.connectObjects()
1207 controllerObj.run()
1207 controllerObj.run()
1208
1208
1209 No newline at end of file
1209
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,1451 +1,1465
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
22
23 LOCALTIME = True
23 LOCALTIME = True
24
24
25 def isNumber(cad):
25 def isNumber(cad):
26 """
26 """
27 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
27 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
28
28
29 Excepciones:
29 Excepciones:
30 Si un determinado string no puede ser convertido a numero
30 Si un determinado string no puede ser convertido a numero
31 Input:
31 Input:
32 str, string al cual se le analiza para determinar si convertible a un numero o no
32 str, string al cual se le analiza para determinar si convertible a un numero o no
33
33
34 Return:
34 Return:
35 True : si el string es uno numerico
35 True : si el string es uno numerico
36 False : no es un string numerico
36 False : no es un string numerico
37 """
37 """
38 try:
38 try:
39 float( cad )
39 float( cad )
40 return True
40 return True
41 except:
41 except:
42 return False
42 return False
43
43
44 def isThisFileinRange(filename, startUTSeconds, endUTSeconds):
44 def isThisFileinRange(filename, startUTSeconds, endUTSeconds):
45 """
45 """
46 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
46 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
47
47
48 Inputs:
48 Inputs:
49 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
49 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
50
50
51 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
51 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
52 segundos contados desde 01/01/1970.
52 segundos contados desde 01/01/1970.
53 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
53 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
54 segundos contados desde 01/01/1970.
54 segundos contados desde 01/01/1970.
55
55
56 Return:
56 Return:
57 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
57 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
58 fecha especificado, de lo contrario retorna False.
58 fecha especificado, de lo contrario retorna False.
59
59
60 Excepciones:
60 Excepciones:
61 Si el archivo no existe o no puede ser abierto
61 Si el archivo no existe o no puede ser abierto
62 Si la cabecera no puede ser leida.
62 Si la cabecera no puede ser leida.
63
63
64 """
64 """
65 basicHeaderObj = BasicHeader(LOCALTIME)
65 basicHeaderObj = BasicHeader(LOCALTIME)
66
66
67 try:
67 try:
68 fp = open(filename,'rb')
68 fp = open(filename,'rb')
69 except IOError:
69 except IOError:
70 traceback.print_exc()
70 traceback.print_exc()
71 raise IOError, "The file %s can't be opened" %(filename)
71 raise IOError, "The file %s can't be opened" %(filename)
72
72
73 sts = basicHeaderObj.read(fp)
73 sts = basicHeaderObj.read(fp)
74 fp.close()
74 fp.close()
75
75
76 if not(sts):
76 if not(sts):
77 print "Skipping the file %s because it has not a valid header" %(filename)
77 print "Skipping the file %s because it has not a valid header" %(filename)
78 return 0
78 return 0
79
79
80 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
80 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
81 return 0
81 return 0
82
82
83 return 1
83 return 1
84
84
85 def isFileinThisTime(filename, startTime, endTime):
85 def isFileinThisTime(filename, startTime, endTime):
86 """
86 """
87 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
87 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
88
88
89 Inputs:
89 Inputs:
90 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
90 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
91
91
92 startTime : tiempo inicial del rango seleccionado en formato datetime.time
92 startTime : tiempo inicial del rango seleccionado en formato datetime.time
93
93
94 endTime : tiempo final del rango seleccionado en formato datetime.time
94 endTime : tiempo final del rango seleccionado en formato datetime.time
95
95
96 Return:
96 Return:
97 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
97 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
98 fecha especificado, de lo contrario retorna False.
98 fecha especificado, de lo contrario retorna False.
99
99
100 Excepciones:
100 Excepciones:
101 Si el archivo no existe o no puede ser abierto
101 Si el archivo no existe o no puede ser abierto
102 Si la cabecera no puede ser leida.
102 Si la cabecera no puede ser leida.
103
103
104 """
104 """
105
105
106
106
107 try:
107 try:
108 fp = open(filename,'rb')
108 fp = open(filename,'rb')
109 except IOError:
109 except IOError:
110 traceback.print_exc()
110 traceback.print_exc()
111 raise IOError, "The file %s can't be opened" %(filename)
111 raise IOError, "The file %s can't be opened" %(filename)
112
112
113 basicHeaderObj = BasicHeader(LOCALTIME)
113 basicHeaderObj = BasicHeader(LOCALTIME)
114 sts = basicHeaderObj.read(fp)
114 sts = basicHeaderObj.read(fp)
115 fp.close()
115 fp.close()
116
116
117 thisDatetime = basicHeaderObj.datatime
117 thisDatetime = basicHeaderObj.datatime
118 thisTime = thisDatetime.time()
118 thisTime = thisDatetime.time()
119
119
120 if not(sts):
120 if not(sts):
121 print "Skipping the file %s because it has not a valid header" %(filename)
121 print "Skipping the file %s because it has not a valid header" %(filename)
122 return None
122 return None
123
123
124 if not ((startTime <= thisTime) and (endTime > thisTime)):
124 if not ((startTime <= thisTime) and (endTime > thisTime)):
125 return None
125 return None
126
126
127 return thisDatetime
127 return thisDatetime
128
128
129 def getFileFromSet(path, ext, set):
129 def getFileFromSet(path, ext, set):
130 validFilelist = []
130 validFilelist = []
131 fileList = os.listdir(path)
131 fileList = os.listdir(path)
132
132
133 # 0 1234 567 89A BCDE
133 # 0 1234 567 89A BCDE
134 # H YYYY DDD SSS .ext
134 # H YYYY DDD SSS .ext
135
135
136 for thisFile in fileList:
136 for thisFile in fileList:
137 try:
137 try:
138 year = int(thisFile[1:5])
138 year = int(thisFile[1:5])
139 doy = int(thisFile[5:8])
139 doy = int(thisFile[5:8])
140 except:
140 except:
141 continue
141 continue
142
142
143 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
143 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
144 continue
144 continue
145
145
146 validFilelist.append(thisFile)
146 validFilelist.append(thisFile)
147
147
148 myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set))
148 myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set))
149
149
150 if len(myfile)!= 0:
150 if len(myfile)!= 0:
151 return myfile[0]
151 return myfile[0]
152 else:
152 else:
153 filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower())
153 filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower())
154 print 'the filename %s does not exist'%filename
154 print 'the filename %s does not exist'%filename
155 print '...going to the last file: '
155 print '...going to the last file: '
156
156
157 if validFilelist:
157 if validFilelist:
158 validFilelist = sorted( validFilelist, key=str.lower )
158 validFilelist = sorted( validFilelist, key=str.lower )
159 return validFilelist[-1]
159 return validFilelist[-1]
160
160
161 return None
161 return None
162
162
163 def getlastFileFromPath(path, ext):
163 def getlastFileFromPath(path, ext):
164 """
164 """
165 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
165 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
166 al final de la depuracion devuelve el ultimo file de la lista que quedo.
166 al final de la depuracion devuelve el ultimo file de la lista que quedo.
167
167
168 Input:
168 Input:
169 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
169 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
170 ext : extension de los files contenidos en una carpeta
170 ext : extension de los files contenidos en una carpeta
171
171
172 Return:
172 Return:
173 El ultimo file de una determinada carpeta, no se considera el path.
173 El ultimo file de una determinada carpeta, no se considera el path.
174 """
174 """
175 validFilelist = []
175 validFilelist = []
176 fileList = os.listdir(path)
176 fileList = os.listdir(path)
177
177
178 # 0 1234 567 89A BCDE
178 # 0 1234 567 89A BCDE
179 # H YYYY DDD SSS .ext
179 # H YYYY DDD SSS .ext
180
180
181 for thisFile in fileList:
181 for thisFile in fileList:
182
182
183 year = thisFile[1:5]
183 year = thisFile[1:5]
184 if not isNumber(year):
184 if not isNumber(year):
185 continue
185 continue
186
186
187 doy = thisFile[5:8]
187 doy = thisFile[5:8]
188 if not isNumber(doy):
188 if not isNumber(doy):
189 continue
189 continue
190
190
191 year = int(year)
191 year = int(year)
192 doy = int(doy)
192 doy = int(doy)
193
193
194 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
194 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
195 continue
195 continue
196
196
197 validFilelist.append(thisFile)
197 validFilelist.append(thisFile)
198
198
199 if validFilelist:
199 if validFilelist:
200 validFilelist = sorted( validFilelist, key=str.lower )
200 validFilelist = sorted( validFilelist, key=str.lower )
201 return validFilelist[-1]
201 return validFilelist[-1]
202
202
203 return None
203 return None
204
204
205 def checkForRealPath(path, foldercounter, year, doy, set, ext):
205 def checkForRealPath(path, foldercounter, year, doy, set, ext):
206 """
206 """
207 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
207 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
208 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
208 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
209 el path exacto de un determinado file.
209 el path exacto de un determinado file.
210
210
211 Example :
211 Example :
212 nombre correcto del file es .../.../D2009307/P2009307367.ext
212 nombre correcto del file es .../.../D2009307/P2009307367.ext
213
213
214 Entonces la funcion prueba con las siguientes combinaciones
214 Entonces la funcion prueba con las siguientes combinaciones
215 .../.../y2009307367.ext
215 .../.../y2009307367.ext
216 .../.../Y2009307367.ext
216 .../.../Y2009307367.ext
217 .../.../x2009307/y2009307367.ext
217 .../.../x2009307/y2009307367.ext
218 .../.../x2009307/Y2009307367.ext
218 .../.../x2009307/Y2009307367.ext
219 .../.../X2009307/y2009307367.ext
219 .../.../X2009307/y2009307367.ext
220 .../.../X2009307/Y2009307367.ext
220 .../.../X2009307/Y2009307367.ext
221 siendo para este caso, la ultima combinacion de letras, identica al file buscado
221 siendo para este caso, la ultima combinacion de letras, identica al file buscado
222
222
223 Return:
223 Return:
224 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
224 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
225 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
225 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
226 para el filename
226 para el filename
227 """
227 """
228 fullfilename = None
228 fullfilename = None
229 find_flag = False
229 find_flag = False
230 filename = None
230 filename = None
231
231
232 prefixDirList = [None,'d','D']
232 prefixDirList = [None,'d','D']
233 if ext.lower() == ".r": #voltage
233 if ext.lower() == ".r": #voltage
234 prefixFileList = ['d','D']
234 prefixFileList = ['d','D']
235 elif ext.lower() == ".pdata": #spectra
235 elif ext.lower() == ".pdata": #spectra
236 prefixFileList = ['p','P']
236 prefixFileList = ['p','P']
237 else:
237 else:
238 return None, filename
238 return None, filename
239
239
240 #barrido por las combinaciones posibles
240 #barrido por las combinaciones posibles
241 for prefixDir in prefixDirList:
241 for prefixDir in prefixDirList:
242 thispath = path
242 thispath = path
243 if prefixDir != None:
243 if prefixDir != None:
244 #formo el nombre del directorio xYYYYDDD (x=d o x=D)
244 #formo el nombre del directorio xYYYYDDD (x=d o x=D)
245 if foldercounter == 0:
245 if foldercounter == 0:
246 thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy ))
246 thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy ))
247 else:
247 else:
248 thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter))
248 thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter))
249 for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D"
249 for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D"
250 filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
250 filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
251 fullfilename = os.path.join( thispath, filename ) #formo el path completo
251 fullfilename = os.path.join( thispath, filename ) #formo el path completo
252
252
253 if os.path.exists( fullfilename ): #verifico que exista
253 if os.path.exists( fullfilename ): #verifico que exista
254 find_flag = True
254 find_flag = True
255 break
255 break
256 if find_flag:
256 if find_flag:
257 break
257 break
258
258
259 if not(find_flag):
259 if not(find_flag):
260 return None, filename
260 return None, filename
261
261
262 return fullfilename, filename
262 return fullfilename, filename
263
263
264 def isRadarFolder(folder):
264 def isRadarFolder(folder):
265 try:
265 try:
266 year = int(folder[1:5])
266 year = int(folder[1:5])
267 doy = int(folder[5:8])
267 doy = int(folder[5:8])
268 except:
268 except:
269 return 0
269 return 0
270
270
271 return 1
271 return 1
272
272
273 def isRadarFile(file):
273 def isRadarFile(file):
274 try:
274 try:
275 year = int(file[1:5])
275 year = int(file[1:5])
276 doy = int(file[5:8])
276 doy = int(file[5:8])
277 set = int(file[8:11])
277 set = int(file[8:11])
278 except:
278 except:
279 return 0
279 return 0
280
280
281 return 1
281 return 1
282
282
283 def getDateFromRadarFile(file):
283 def getDateFromRadarFile(file):
284 try:
284 try:
285 year = int(file[1:5])
285 year = int(file[1:5])
286 doy = int(file[5:8])
286 doy = int(file[5:8])
287 set = int(file[8:11])
287 set = int(file[8:11])
288 except:
288 except:
289 return None
289 return None
290
290
291 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
291 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1)
292 return thisDate
292 return thisDate
293
293
294 class JRODataIO:
294 class JRODataIO:
295
295
296 c = 3E8
296 c = 3E8
297
297
298 isConfig = False
298 isConfig = False
299
299
300 basicHeaderObj = None
300 basicHeaderObj = None
301
301
302 systemHeaderObj = None
302 systemHeaderObj = None
303
303
304 radarControllerHeaderObj = None
304 radarControllerHeaderObj = None
305
305
306 processingHeaderObj = None
306 processingHeaderObj = None
307
307
308 online = 0
308 online = 0
309
309
310 dtype = None
310 dtype = None
311
311
312 pathList = []
312 pathList = []
313
313
314 filenameList = []
314 filenameList = []
315
315
316 filename = None
316 filename = None
317
317
318 ext = None
318 ext = None
319
319
320 flagIsNewFile = 1
320 flagIsNewFile = 1
321
321
322 flagDiscontinuousBlock = 0
322 flagDiscontinuousBlock = 0
323
323
324 flagIsNewBlock = 0
324 flagIsNewBlock = 0
325
325
326 fp = None
326 fp = None
327
327
328 firstHeaderSize = 0
328 firstHeaderSize = 0
329
329
330 basicHeaderSize = 24
330 basicHeaderSize = 24
331
331
332 versionFile = 1103
332 versionFile = 1103
333
333
334 fileSize = None
334 fileSize = None
335
335
336 # ippSeconds = None
336 # ippSeconds = None
337
337
338 fileSizeByHeader = None
338 fileSizeByHeader = None
339
339
340 fileIndex = None
340 fileIndex = None
341
341
342 profileIndex = None
342 profileIndex = None
343
343
344 blockIndex = None
344 blockIndex = None
345
345
346 nTotalBlocks = None
346 nTotalBlocks = None
347
347
348 maxTimeStep = 30
348 maxTimeStep = 30
349
349
350 lastUTTime = None
350 lastUTTime = None
351
351
352 datablock = None
352 datablock = None
353
353
354 dataOut = None
354 dataOut = None
355
355
356 blocksize = None
356 blocksize = None
357
357
358 getByBlock = False
358 getByBlock = False
359
359
360 def __init__(self):
360 def __init__(self):
361
361
362 raise ValueError, "Not implemented"
362 raise ValueError, "Not implemented"
363
363
364 def run(self):
364 def run(self):
365
365
366 raise ValueError, "Not implemented"
366 raise ValueError, "Not implemented"
367
367
368 class JRODataReader(JRODataIO):
368 class JRODataReader(JRODataIO):
369
369
370 nReadBlocks = 0
370 nReadBlocks = 0
371
371
372 delay = 10 #number of seconds waiting a new file
372 delay = 10 #number of seconds waiting a new file
373
373
374 nTries = 3 #quantity tries
374 nTries = 3 #quantity tries
375
375
376 nFiles = 3 #number of files for searching
376 nFiles = 3 #number of files for searching
377
377
378 path = None
378 path = None
379
379
380 foldercounter = 0
380 foldercounter = 0
381
381
382 flagNoMoreFiles = 0
382 flagNoMoreFiles = 0
383
383
384 datetimeList = []
384 datetimeList = []
385
385
386 __isFirstTimeOnline = 1
386 __isFirstTimeOnline = 1
387
387
388 __printInfo = True
388 __printInfo = True
389
389
390 profileIndex = None
390 profileIndex = None
391
391
392 nTxs = 1
392 nTxs = 1
393
393
394 txIndex = None
394 txIndex = None
395
395
396 def __init__(self):
396 def __init__(self):
397
397
398 """
398 """
399
399
400 """
400 """
401
401
402 # raise NotImplementedError, "This method has not been implemented"
402 # raise NotImplementedError, "This method has not been implemented"
403
403
404
404
405 def createObjByDefault(self):
405 def createObjByDefault(self):
406 """
406 """
407
407
408 """
408 """
409 raise NotImplementedError, "This method has not been implemented"
409 raise NotImplementedError, "This method has not been implemented"
410
410
411 def getBlockDimension(self):
411 def getBlockDimension(self):
412
412
413 raise NotImplementedError, "No implemented"
413 raise NotImplementedError, "No implemented"
414
414
415 def __searchFilesOffLine(self,
415 def __searchFilesOffLine(self,
416 path,
416 path,
417 startDate=None,
417 startDate=None,
418 endDate=None,
418 endDate=None,
419 startTime=datetime.time(0,0,0),
419 startTime=datetime.time(0,0,0),
420 endTime=datetime.time(23,59,59),
420 endTime=datetime.time(23,59,59),
421 set=None,
421 set=None,
422 expLabel='',
422 expLabel='',
423 ext='.r',
423 ext='.r',
424 walk=True):
424 walk=True):
425
425
426 self.filenameList = []
426 self.filenameList = []
427 self.datetimeList = []
427 self.datetimeList = []
428
428
429 pathList = []
429 pathList = []
430
430
431 if not walk:
431 if not walk:
432 #pathList.append(path)
432 #pathList.append(path)
433 multi_path = path.split(',')
433 multi_path = path.split(',')
434 for single_path in multi_path:
434 for single_path in multi_path:
435
436 if not os.path.isdir(single_path):
437 continue
438
435 pathList.append(single_path)
439 pathList.append(single_path)
436
440
437 else:
441 else:
438 #dirList = []
442 #dirList = []
439 multi_path = path.split(',')
443 multi_path = path.split(',')
440 for single_path in multi_path:
444 for single_path in multi_path:
445
446 if not os.path.isdir(single_path):
447 continue
448
441 dirList = []
449 dirList = []
442 for thisPath in os.listdir(single_path):
450 for thisPath in os.listdir(single_path):
443 if not os.path.isdir(os.path.join(single_path,thisPath)):
451 if not os.path.isdir(os.path.join(single_path,thisPath)):
444 continue
452 continue
445 if not isRadarFolder(thisPath):
453 if not isRadarFolder(thisPath):
446 continue
454 continue
447
455
448 dirList.append(thisPath)
456 dirList.append(thisPath)
449
457
450 if not(dirList):
458 if not(dirList):
451 return None, None
459 return None, None
452
460
453 if startDate and endDate:
461 if startDate and endDate:
454 thisDate = startDate
462 thisDate = startDate
455
463
456 while(thisDate <= endDate):
464 while(thisDate <= endDate):
457 year = thisDate.timetuple().tm_year
465 year = thisDate.timetuple().tm_year
458 doy = thisDate.timetuple().tm_yday
466 doy = thisDate.timetuple().tm_yday
459
467
460 matchlist = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy) + '*')
468 matchlist = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy) + '*')
461 if len(matchlist) == 0:
469 if len(matchlist) == 0:
462 thisDate += datetime.timedelta(1)
470 thisDate += datetime.timedelta(1)
463 continue
471 continue
464 for match in matchlist:
472 for match in matchlist:
465 pathList.append(os.path.join(single_path,match,expLabel))
473 pathList.append(os.path.join(single_path,match,expLabel))
466
474
467 thisDate += datetime.timedelta(1)
475 thisDate += datetime.timedelta(1)
468 else:
476 else:
469 for thiDir in dirList:
477 for thiDir in dirList:
470 pathList.append(os.path.join(single_path,thiDir,expLabel))
478 pathList.append(os.path.join(single_path,thiDir,expLabel))
471
479
472 if pathList == []:
480 if pathList == []:
473 print "Any folder was found for the date range: %s-%s" %(startDate, endDate)
481 print "Any folder was found for the date range: %s-%s" %(startDate, endDate)
474 return None, None
482 return None, None
475
483
476 print "%d folder(s) was(were) found for the date range: %s - %s" %(len(pathList), startDate, endDate)
484 print "%d folder(s) was(were) found for the date range: %s - %s" %(len(pathList), startDate, endDate)
477
485
478 filenameList = []
486 filenameList = []
479 datetimeList = []
487 datetimeList = []
480 pathDict = {}
488 pathDict = {}
481 filenameList_to_sort = []
489 filenameList_to_sort = []
482
490
483 for i in range(len(pathList)):
491 for i in range(len(pathList)):
484
492
485 thisPath = pathList[i]
493 thisPath = pathList[i]
486
494
487 fileList = glob.glob1(thisPath, "*%s" %ext)
495 fileList = glob.glob1(thisPath, "*%s" %ext)
488 if len(fileList) < 1:
496 if len(fileList) < 1:
489 continue
497 continue
490 fileList.sort()
498 fileList.sort()
491 pathDict.setdefault(fileList[0])
499 pathDict.setdefault(fileList[0])
492 pathDict[fileList[0]] = i
500 pathDict[fileList[0]] = i
493 filenameList_to_sort.append(fileList[0])
501 filenameList_to_sort.append(fileList[0])
494
502
495 filenameList_to_sort.sort()
503 filenameList_to_sort.sort()
496
504
497 for file in filenameList_to_sort:
505 for file in filenameList_to_sort:
498 thisPath = pathList[pathDict[file]]
506 thisPath = pathList[pathDict[file]]
499
507
500 fileList = glob.glob1(thisPath, "*%s" %ext)
508 fileList = glob.glob1(thisPath, "*%s" %ext)
501 fileList.sort()
509 fileList.sort()
502
510
503 for file in fileList:
511 for file in fileList:
504
512
505 filename = os.path.join(thisPath,file)
513 filename = os.path.join(thisPath,file)
506 thisDatetime = isFileinThisTime(filename, startTime, endTime)
514 thisDatetime = isFileinThisTime(filename, startTime, endTime)
507
515
508 if not(thisDatetime):
516 if not(thisDatetime):
509 continue
517 continue
510
518
511 filenameList.append(filename)
519 filenameList.append(filename)
512 datetimeList.append(thisDatetime)
520 datetimeList.append(thisDatetime)
513
521
514 if not(filenameList):
522 if not(filenameList):
515 print "Any file was found for the time range %s - %s" %(startTime, endTime)
523 print "Any file was found for the time range %s - %s" %(startTime, endTime)
516 return None, None
524 return None, None
517
525
518 print "%d file(s) was(were) found for the time range: %s - %s" %(len(filenameList), startTime, endTime)
526 print "%d file(s) was(were) found for the time range: %s - %s" %(len(filenameList), startTime, endTime)
519 print
527 print
520
528
521 for i in range(len(filenameList)):
529 for i in range(len(filenameList)):
522 print "%s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
530 print "%s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
523
531
524 self.filenameList = filenameList
532 self.filenameList = filenameList
525 self.datetimeList = datetimeList
533 self.datetimeList = datetimeList
526
534
527 return pathList, filenameList
535 return pathList, filenameList
528
536
529 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
537 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
530
538
531 """
539 """
532 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
540 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
533 devuelve el archivo encontrado ademas de otros datos.
541 devuelve el archivo encontrado ademas de otros datos.
534
542
535 Input:
543 Input:
536 path : carpeta donde estan contenidos los files que contiene data
544 path : carpeta donde estan contenidos los files que contiene data
537
545
538 expLabel : Nombre del subexperimento (subfolder)
546 expLabel : Nombre del subexperimento (subfolder)
539
547
540 ext : extension de los files
548 ext : extension de los files
541
549
542 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
550 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
543
551
544 Return:
552 Return:
545 directory : eL directorio donde esta el file encontrado
553 directory : eL directorio donde esta el file encontrado
546 filename : el ultimo file de una determinada carpeta
554 filename : el ultimo file de una determinada carpeta
547 year : el anho
555 year : el anho
548 doy : el numero de dia del anho
556 doy : el numero de dia del anho
549 set : el set del archivo
557 set : el set del archivo
550
558
551
559
552 """
560 """
553 dirList = []
561 dirList = []
554
562
555 if not walk:
563 if not walk:
556 fullpath = path
564 fullpath = path
557 foldercounter = 0
565 foldercounter = 0
558 else:
566 else:
559 #Filtra solo los directorios
567 #Filtra solo los directorios
560 for thisPath in os.listdir(path):
568 for thisPath in os.listdir(path):
561 if not os.path.isdir(os.path.join(path,thisPath)):
569 if not os.path.isdir(os.path.join(path,thisPath)):
562 continue
570 continue
563 if not isRadarFolder(thisPath):
571 if not isRadarFolder(thisPath):
564 continue
572 continue
565
573
566 dirList.append(thisPath)
574 dirList.append(thisPath)
567
575
568 if not(dirList):
576 if not(dirList):
569 return None, None, None, None, None, None
577 return None, None, None, None, None, None
570
578
571 dirList = sorted( dirList, key=str.lower )
579 dirList = sorted( dirList, key=str.lower )
572
580
573 doypath = dirList[-1]
581 doypath = dirList[-1]
574 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
582 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
575 fullpath = os.path.join(path, doypath, expLabel)
583 fullpath = os.path.join(path, doypath, expLabel)
576
584
577
585
578 print "%s folder was found: " %(fullpath )
586 print "%s folder was found: " %(fullpath )
579
587
580 if set == None:
588 if set == None:
581 filename = getlastFileFromPath(fullpath, ext)
589 filename = getlastFileFromPath(fullpath, ext)
582 else:
590 else:
583 filename = getFileFromSet(fullpath, ext, set)
591 filename = getFileFromSet(fullpath, ext, set)
584
592
585 if not(filename):
593 if not(filename):
586 return None, None, None, None, None, None
594 return None, None, None, None, None, None
587
595
588 print "%s file was found" %(filename)
596 print "%s file was found" %(filename)
589
597
590 if not(self.__verifyFile(os.path.join(fullpath, filename))):
598 if not(self.__verifyFile(os.path.join(fullpath, filename))):
591 return None, None, None, None, None, None
599 return None, None, None, None, None, None
592
600
593 year = int( filename[1:5] )
601 year = int( filename[1:5] )
594 doy = int( filename[5:8] )
602 doy = int( filename[5:8] )
595 set = int( filename[8:11] )
603 set = int( filename[8:11] )
596
604
597 return fullpath, foldercounter, filename, year, doy, set
605 return fullpath, foldercounter, filename, year, doy, set
598
606
599 def __setNextFileOffline(self):
607 def __setNextFileOffline(self):
600
608
601 idFile = self.fileIndex
609 idFile = self.fileIndex
602
610
603 while (True):
611 while (True):
604 idFile += 1
612 idFile += 1
605 if not(idFile < len(self.filenameList)):
613 if not(idFile < len(self.filenameList)):
606 self.flagNoMoreFiles = 1
614 self.flagNoMoreFiles = 1
607 # print "[Reading] No more Files"
615 # print "[Reading] No more Files"
608 return 0
616 return 0
609
617
610 filename = self.filenameList[idFile]
618 filename = self.filenameList[idFile]
611
619
612 if not(self.__verifyFile(filename)):
620 if not(self.__verifyFile(filename)):
613 continue
621 continue
614
622
615 fileSize = os.path.getsize(filename)
623 fileSize = os.path.getsize(filename)
616 fp = open(filename,'rb')
624 fp = open(filename,'rb')
617 break
625 break
618
626
619 self.flagIsNewFile = 1
627 self.flagIsNewFile = 1
620 self.fileIndex = idFile
628 self.fileIndex = idFile
621 self.filename = filename
629 self.filename = filename
622 self.fileSize = fileSize
630 self.fileSize = fileSize
623 self.fp = fp
631 self.fp = fp
624
632
625 # print "[Reading] Setting the file: %s"%self.filename
633 # print "[Reading] Setting the file: %s"%self.filename
626
634
627 return 1
635 return 1
628
636
629 def __setNextFileOnline(self):
637 def __setNextFileOnline(self):
630 """
638 """
631 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
639 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
632 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
640 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
633 siguientes.
641 siguientes.
634
642
635 Affected:
643 Affected:
636 self.flagIsNewFile
644 self.flagIsNewFile
637 self.filename
645 self.filename
638 self.fileSize
646 self.fileSize
639 self.fp
647 self.fp
640 self.set
648 self.set
641 self.flagNoMoreFiles
649 self.flagNoMoreFiles
642
650
643 Return:
651 Return:
644 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
652 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
645 1 : si el file fue abierto con exito y esta listo a ser leido
653 1 : si el file fue abierto con exito y esta listo a ser leido
646
654
647 Excepciones:
655 Excepciones:
648 Si un determinado file no puede ser abierto
656 Si un determinado file no puede ser abierto
649 """
657 """
650 nFiles = 0
658 nFiles = 0
651 fileOk_flag = False
659 fileOk_flag = False
652 firstTime_flag = True
660 firstTime_flag = True
653
661
654 self.set += 1
662 self.set += 1
655
663
656 if self.set > 999:
664 if self.set > 999:
657 self.set = 0
665 self.set = 0
658 self.foldercounter += 1
666 self.foldercounter += 1
659
667
660 #busca el 1er file disponible
668 #busca el 1er file disponible
661 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
669 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
662 if fullfilename:
670 if fullfilename:
663 if self.__verifyFile(fullfilename, False):
671 if self.__verifyFile(fullfilename, False):
664 fileOk_flag = True
672 fileOk_flag = True
665
673
666 #si no encuentra un file entonces espera y vuelve a buscar
674 #si no encuentra un file entonces espera y vuelve a buscar
667 if not(fileOk_flag):
675 if not(fileOk_flag):
668 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
676 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
669
677
670 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
678 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
671 tries = self.nTries
679 tries = self.nTries
672 else:
680 else:
673 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
681 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
674
682
675 for nTries in range( tries ):
683 for nTries in range( tries ):
676 if firstTime_flag:
684 if firstTime_flag:
677 print "\t[Reading] Waiting %0.2f sec for the file \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
685 print "\t[Reading] Waiting %0.2f sec for the file \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
678 sleep( self.delay )
686 sleep( self.delay )
679 else:
687 else:
680 print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
688 print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
681
689
682 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
690 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
683 if fullfilename:
691 if fullfilename:
684 if self.__verifyFile(fullfilename):
692 if self.__verifyFile(fullfilename):
685 fileOk_flag = True
693 fileOk_flag = True
686 break
694 break
687
695
688 if fileOk_flag:
696 if fileOk_flag:
689 break
697 break
690
698
691 firstTime_flag = False
699 firstTime_flag = False
692
700
693 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
701 print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename
694 self.set += 1
702 self.set += 1
695
703
696 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
704 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
697 self.set = 0
705 self.set = 0
698 self.doy += 1
706 self.doy += 1
699 self.foldercounter = 0
707 self.foldercounter = 0
700
708
701 if fileOk_flag:
709 if fileOk_flag:
702 self.fileSize = os.path.getsize( fullfilename )
710 self.fileSize = os.path.getsize( fullfilename )
703 self.filename = fullfilename
711 self.filename = fullfilename
704 self.flagIsNewFile = 1
712 self.flagIsNewFile = 1
705 if self.fp != None: self.fp.close()
713 if self.fp != None: self.fp.close()
706 self.fp = open(fullfilename, 'rb')
714 self.fp = open(fullfilename, 'rb')
707 self.flagNoMoreFiles = 0
715 self.flagNoMoreFiles = 0
708 # print '[Reading] Setting the file: %s' % fullfilename
716 # print '[Reading] Setting the file: %s' % fullfilename
709 else:
717 else:
710 self.fileSize = 0
718 self.fileSize = 0
711 self.filename = None
719 self.filename = None
712 self.flagIsNewFile = 0
720 self.flagIsNewFile = 0
713 self.fp = None
721 self.fp = None
714 self.flagNoMoreFiles = 1
722 self.flagNoMoreFiles = 1
715 # print '[Reading] No more files to read'
723 # print '[Reading] No more files to read'
716
724
717 return fileOk_flag
725 return fileOk_flag
718
726
719 def setNextFile(self):
727 def setNextFile(self):
720 if self.fp != None:
728 if self.fp != None:
721 self.fp.close()
729 self.fp.close()
722
730
723 if self.online:
731 if self.online:
724 newFile = self.__setNextFileOnline()
732 newFile = self.__setNextFileOnline()
725 else:
733 else:
726 newFile = self.__setNextFileOffline()
734 newFile = self.__setNextFileOffline()
727
735
728 if not(newFile):
736 if not(newFile):
729 print '[Reading] No more files to read'
737 print '[Reading] No more files to read'
730 return 0
738 return 0
731
739
732 print '[Reading] Setting the file: %s' % self.filename
740 print '[Reading] Setting the file: %s' % self.filename
733
741
734 self.__readFirstHeader()
742 self.__readFirstHeader()
735 self.nReadBlocks = 0
743 self.nReadBlocks = 0
736 return 1
744 return 1
737
745
738 def __waitNewBlock(self):
746 def __waitNewBlock(self):
739 """
747 """
740 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
748 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
741
749
742 Si el modo de lectura es OffLine siempre retorn 0
750 Si el modo de lectura es OffLine siempre retorn 0
743 """
751 """
744 if not self.online:
752 if not self.online:
745 return 0
753 return 0
746
754
747 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
755 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
748 return 0
756 return 0
749
757
750 currentPointer = self.fp.tell()
758 currentPointer = self.fp.tell()
751
759
752 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
760 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
753
761
754 for nTries in range( self.nTries ):
762 for nTries in range( self.nTries ):
755
763
756 self.fp.close()
764 self.fp.close()
757 self.fp = open( self.filename, 'rb' )
765 self.fp = open( self.filename, 'rb' )
758 self.fp.seek( currentPointer )
766 self.fp.seek( currentPointer )
759
767
760 self.fileSize = os.path.getsize( self.filename )
768 self.fileSize = os.path.getsize( self.filename )
761 currentSize = self.fileSize - currentPointer
769 currentSize = self.fileSize - currentPointer
762
770
763 if ( currentSize >= neededSize ):
771 if ( currentSize >= neededSize ):
764 self.basicHeaderObj.read(self.fp)
772 self.basicHeaderObj.read(self.fp)
765 return 1
773 return 1
766
774
767 if self.fileSize == self.fileSizeByHeader:
775 if self.fileSize == self.fileSizeByHeader:
768 # self.flagEoF = True
776 # self.flagEoF = True
769 return 0
777 return 0
770
778
771 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
779 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
772 sleep( self.delay )
780 sleep( self.delay )
773
781
774
782
775 return 0
783 return 0
776
784
777 def waitDataBlock(self,pointer_location):
785 def waitDataBlock(self,pointer_location):
778
786
779 currentPointer = pointer_location
787 currentPointer = pointer_location
780
788
781 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
789 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
782
790
783 for nTries in range( self.nTries ):
791 for nTries in range( self.nTries ):
784 self.fp.close()
792 self.fp.close()
785 self.fp = open( self.filename, 'rb' )
793 self.fp = open( self.filename, 'rb' )
786 self.fp.seek( currentPointer )
794 self.fp.seek( currentPointer )
787
795
788 self.fileSize = os.path.getsize( self.filename )
796 self.fileSize = os.path.getsize( self.filename )
789 currentSize = self.fileSize - currentPointer
797 currentSize = self.fileSize - currentPointer
790
798
791 if ( currentSize >= neededSize ):
799 if ( currentSize >= neededSize ):
792 return 1
800 return 1
793
801
794 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
802 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
795 sleep( self.delay )
803 sleep( self.delay )
796
804
797 return 0
805 return 0
798
806
799 def __jumpToLastBlock(self):
807 def __jumpToLastBlock(self):
800
808
801 if not(self.__isFirstTimeOnline):
809 if not(self.__isFirstTimeOnline):
802 return
810 return
803
811
804 csize = self.fileSize - self.fp.tell()
812 csize = self.fileSize - self.fp.tell()
805 blocksize = self.processingHeaderObj.blockSize
813 blocksize = self.processingHeaderObj.blockSize
806
814
807 #salta el primer bloque de datos
815 #salta el primer bloque de datos
808 if csize > self.processingHeaderObj.blockSize:
816 if csize > self.processingHeaderObj.blockSize:
809 self.fp.seek(self.fp.tell() + blocksize)
817 self.fp.seek(self.fp.tell() + blocksize)
810 else:
818 else:
811 return
819 return
812
820
813 csize = self.fileSize - self.fp.tell()
821 csize = self.fileSize - self.fp.tell()
814 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
822 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
815 while True:
823 while True:
816
824
817 if self.fp.tell()<self.fileSize:
825 if self.fp.tell()<self.fileSize:
818 self.fp.seek(self.fp.tell() + neededsize)
826 self.fp.seek(self.fp.tell() + neededsize)
819 else:
827 else:
820 self.fp.seek(self.fp.tell() - neededsize)
828 self.fp.seek(self.fp.tell() - neededsize)
821 break
829 break
822
830
823 # csize = self.fileSize - self.fp.tell()
831 # csize = self.fileSize - self.fp.tell()
824 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
832 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
825 # factor = int(csize/neededsize)
833 # factor = int(csize/neededsize)
826 # if factor > 0:
834 # if factor > 0:
827 # self.fp.seek(self.fp.tell() + factor*neededsize)
835 # self.fp.seek(self.fp.tell() + factor*neededsize)
828
836
829 self.flagIsNewFile = 0
837 self.flagIsNewFile = 0
830 self.__isFirstTimeOnline = 0
838 self.__isFirstTimeOnline = 0
831
839
832 def __setNewBlock(self):
840 def __setNewBlock(self):
833
841
834 if self.fp == None:
842 if self.fp == None:
835 return 0
843 return 0
836
844
837 if self.online:
845 if self.online:
838 self.__jumpToLastBlock()
846 self.__jumpToLastBlock()
839
847
840 if self.flagIsNewFile:
848 if self.flagIsNewFile:
841 return 1
849 return 1
842
850
843 self.lastUTTime = self.basicHeaderObj.utc
851 self.lastUTTime = self.basicHeaderObj.utc
844 currentSize = self.fileSize - self.fp.tell()
852 currentSize = self.fileSize - self.fp.tell()
845 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
853 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
846
854
847 if (currentSize >= neededSize):
855 if (currentSize >= neededSize):
848 self.basicHeaderObj.read(self.fp)
856 self.basicHeaderObj.read(self.fp)
849 return 1
857 return 1
850
858
851 if self.__waitNewBlock():
859 if self.__waitNewBlock():
852 return 1
860 return 1
853
861
854 if not(self.setNextFile()):
862 if not(self.setNextFile()):
855 return 0
863 return 0
856
864
857 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
865 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
858
866
859 self.flagDiscontinuousBlock = 0
867 self.flagDiscontinuousBlock = 0
860
868
861 if deltaTime > self.maxTimeStep:
869 if deltaTime > self.maxTimeStep:
862 self.flagDiscontinuousBlock = 1
870 self.flagDiscontinuousBlock = 1
863
871
864 return 1
872 return 1
865
873
866 def readNextBlock(self):
874 def readNextBlock(self):
867 if not(self.__setNewBlock()):
875 if not(self.__setNewBlock()):
868 return 0
876 return 0
869
877
870 if not(self.readBlock()):
878 if not(self.readBlock()):
871 return 0
879 return 0
872
880
873 return 1
881 return 1
874
882
875 def __readFirstHeader(self):
883 def __readFirstHeader(self):
876
884
877 self.basicHeaderObj.read(self.fp)
885 self.basicHeaderObj.read(self.fp)
878 self.systemHeaderObj.read(self.fp)
886 self.systemHeaderObj.read(self.fp)
879 self.radarControllerHeaderObj.read(self.fp)
887 self.radarControllerHeaderObj.read(self.fp)
880 self.processingHeaderObj.read(self.fp)
888 self.processingHeaderObj.read(self.fp)
881
889
882 self.firstHeaderSize = self.basicHeaderObj.size
890 self.firstHeaderSize = self.basicHeaderObj.size
883
891
884 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
892 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
885 if datatype == 0:
893 if datatype == 0:
886 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
894 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
887 elif datatype == 1:
895 elif datatype == 1:
888 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
896 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
889 elif datatype == 2:
897 elif datatype == 2:
890 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
898 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
891 elif datatype == 3:
899 elif datatype == 3:
892 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
900 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
893 elif datatype == 4:
901 elif datatype == 4:
894 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
902 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
895 elif datatype == 5:
903 elif datatype == 5:
896 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
904 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
897 else:
905 else:
898 raise ValueError, 'Data type was not defined'
906 raise ValueError, 'Data type was not defined'
899
907
900 self.dtype = datatype_str
908 self.dtype = datatype_str
901 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
909 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
902 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
910 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
903 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
911 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
904 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
912 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
905 self.getBlockDimension()
913 self.getBlockDimension()
906
914
907 def __verifyFile(self, filename, msgFlag=True):
915 def __verifyFile(self, filename, msgFlag=True):
908 msg = None
916 msg = None
909 try:
917 try:
910 fp = open(filename, 'rb')
918 fp = open(filename, 'rb')
911 currentPosition = fp.tell()
919 currentPosition = fp.tell()
912 except IOError:
920 except IOError:
913 traceback.print_exc()
921 traceback.print_exc()
914 if msgFlag:
922 if msgFlag:
915 print "[Reading] The file %s can't be opened" % (filename)
923 print "[Reading] The file %s can't be opened" % (filename)
916 return False
924 return False
917
925
918 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
926 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
919
927
920 if neededSize == 0:
928 if neededSize == 0:
921 basicHeaderObj = BasicHeader(LOCALTIME)
929 basicHeaderObj = BasicHeader(LOCALTIME)
922 systemHeaderObj = SystemHeader()
930 systemHeaderObj = SystemHeader()
923 radarControllerHeaderObj = RadarControllerHeader()
931 radarControllerHeaderObj = RadarControllerHeader()
924 processingHeaderObj = ProcessingHeader()
932 processingHeaderObj = ProcessingHeader()
925
933
926 try:
934 try:
927 if not( basicHeaderObj.read(fp) ): raise IOError
935 if not( basicHeaderObj.read(fp) ): raise IOError
928 if not( systemHeaderObj.read(fp) ): raise IOError
936 if not( systemHeaderObj.read(fp) ): raise IOError
929 if not( radarControllerHeaderObj.read(fp) ): raise IOError
937 if not( radarControllerHeaderObj.read(fp) ): raise IOError
930 if not( processingHeaderObj.read(fp) ): raise IOError
938 if not( processingHeaderObj.read(fp) ): raise IOError
931 # data_type = int(numpy.log2((processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
939 # data_type = int(numpy.log2((processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
932
940
933 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
941 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
934
942
935 except IOError:
943 except IOError:
936 traceback.print_exc()
944 traceback.print_exc()
937 if msgFlag:
945 if msgFlag:
938 print "[Reading] The file %s is empty or it hasn't enough data" % filename
946 print "[Reading] The file %s is empty or it hasn't enough data" % filename
939
947
940 fp.close()
948 fp.close()
941 return False
949 return False
942 else:
950 else:
943 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
951 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
944
952
945 fp.close()
953 fp.close()
946 fileSize = os.path.getsize(filename)
954 fileSize = os.path.getsize(filename)
947 currentSize = fileSize - currentPosition
955 currentSize = fileSize - currentPosition
948 if currentSize < neededSize:
956 if currentSize < neededSize:
949 if msgFlag and (msg != None):
957 if msgFlag and (msg != None):
950 print msg #print"\tSkipping the file %s due to it hasn't enough data" %filename
958 print msg #print"\tSkipping the file %s due to it hasn't enough data" %filename
951 return False
959 return False
952
960
953 return True
961 return True
954
962
955 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True):
963 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True):
956
964
957 dateList = []
965 dateList = []
958 pathList = []
966 pathList = []
959
967
960 if not walk:
968 if not walk:
961 #pathList.append(path)
969 #pathList.append(path)
962 multi_path = path.split(',')
970 multi_path = path.split(',')
963 for single_path in multi_path:
971 for single_path in multi_path:
964
972
973 if not os.path.isdir(single_path):
974 continue
975
965 ok = False
976 ok = False
966 fileList = glob.glob1(single_path, "*"+ext)
977 fileList = glob.glob1(single_path, "*"+ext)
967
978
968 for thisFile in fileList:
979 for thisFile in fileList:
969
980
970 if not os.path.isfile(os.path.join(single_path, thisFile)):
981 if not os.path.isfile(os.path.join(single_path, thisFile)):
971 continue
982 continue
972
983
973 if not isRadarFile(thisFile):
984 if not isRadarFile(thisFile):
974 continue
985 continue
975
986
976 ok = True
987 ok = True
977 thisDate = getDateFromRadarFile(thisFile)
988 thisDate = getDateFromRadarFile(thisFile)
978
989
979 if thisDate not in dateList:
990 if thisDate not in dateList:
980 dateList.append(thisDate)
991 dateList.append(thisDate)
981
992
982 if ok:
993 if ok:
983 pathList.append(single_path)
994 pathList.append(single_path)
984
995
985 return dateList
996 return dateList
986
997
987 multi_path = path.split(',')
998 multi_path = path.split(',')
988 for single_path in multi_path:
999 for single_path in multi_path:
989
1000
1001 if not os.path.isdir(single_path):
1002 continue
1003
990 dirList = []
1004 dirList = []
991
1005
992 for thisPath in os.listdir(single_path):
1006 for thisPath in os.listdir(single_path):
993
1007
994 if not os.path.isdir(os.path.join(single_path,thisPath)):
1008 if not os.path.isdir(os.path.join(single_path,thisPath)):
995 continue
1009 continue
996
1010
997 if not isRadarFolder(thisPath):
1011 if not isRadarFolder(thisPath):
998 continue
1012 continue
999
1013
1000 dirList.append(thisPath)
1014 dirList.append(thisPath)
1001
1015
1002 if not dirList:
1016 if not dirList:
1003 return dateList
1017 return dateList
1004
1018
1005 if startDate and endDate:
1019 if startDate and endDate:
1006 thisDate = startDate
1020 thisDate = startDate
1007
1021
1008 while(thisDate <= endDate):
1022 while(thisDate <= endDate):
1009 year = thisDate.timetuple().tm_year
1023 year = thisDate.timetuple().tm_year
1010 doy = thisDate.timetuple().tm_yday
1024 doy = thisDate.timetuple().tm_yday
1011
1025
1012 matchlist = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy) + '*')
1026 matchlist = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy) + '*')
1013 if len(matchlist) == 0:
1027 if len(matchlist) == 0:
1014 thisDate += datetime.timedelta(1)
1028 thisDate += datetime.timedelta(1)
1015 continue
1029 continue
1016
1030
1017 for match in matchlist:
1031 for match in matchlist:
1018 pathList.append(os.path.join(single_path,match,expLabel))
1032 pathList.append(os.path.join(single_path,match,expLabel))
1019 dateList.append(thisDate)
1033 dateList.append(thisDate)
1020
1034
1021 thisDate += datetime.timedelta(1)
1035 thisDate += datetime.timedelta(1)
1022 else:
1036 else:
1023 for thisDir in dirList:
1037 for thisDir in dirList:
1024 year = int(thisDir[1:5])
1038 year = int(thisDir[1:5])
1025 doy = int(thisDir[5:8])
1039 doy = int(thisDir[5:8])
1026 thisDate = datetime.date(year,1,1) + datetime.timedelta(doy-1)
1040 thisDate = datetime.date(year,1,1) + datetime.timedelta(doy-1)
1027
1041
1028 pathList.append(os.path.join(single_path,thisDir,expLabel))
1042 pathList.append(os.path.join(single_path,thisDir,expLabel))
1029 dateList.append(thisDate)
1043 dateList.append(thisDate)
1030
1044
1031 return dateList
1045 return dateList
1032
1046
1033
1047
1034 def setup(self,
1048 def setup(self,
1035 path=None,
1049 path=None,
1036 startDate=None,
1050 startDate=None,
1037 endDate=None,
1051 endDate=None,
1038 startTime=datetime.time(0,0,0),
1052 startTime=datetime.time(0,0,0),
1039 endTime=datetime.time(23,59,59),
1053 endTime=datetime.time(23,59,59),
1040 set=None,
1054 set=None,
1041 expLabel = "",
1055 expLabel = "",
1042 ext = None,
1056 ext = None,
1043 online = False,
1057 online = False,
1044 delay = 60,
1058 delay = 60,
1045 walk = True,
1059 walk = True,
1046 getblock = False,
1060 getblock = False,
1047 nTxs = 1):
1061 nTxs = 1):
1048
1062
1049 if path == None:
1063 if path == None:
1050 raise ValueError, "[Reading] The path is not valid"
1064 raise ValueError, "[Reading] The path is not valid"
1051
1065
1052 if ext == None:
1066 if ext == None:
1053 ext = self.ext
1067 ext = self.ext
1054
1068
1055 if online:
1069 if online:
1056 print "[Reading] Searching files in online mode..."
1070 print "[Reading] Searching files in online mode..."
1057
1071
1058 for nTries in range( self.nTries ):
1072 for nTries in range( self.nTries ):
1059 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1073 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1060
1074
1061 if fullpath:
1075 if fullpath:
1062 break
1076 break
1063
1077
1064 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
1078 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
1065 sleep( self.delay )
1079 sleep( self.delay )
1066
1080
1067 if not(fullpath):
1081 if not(fullpath):
1068 print "[Reading] There 'isn't any valid file in %s" % path
1082 print "[Reading] There 'isn't any valid file in %s" % path
1069 return None
1083 return None
1070
1084
1071 self.year = year
1085 self.year = year
1072 self.doy = doy
1086 self.doy = doy
1073 self.set = set - 1
1087 self.set = set - 1
1074 self.path = path
1088 self.path = path
1075 self.foldercounter = foldercounter
1089 self.foldercounter = foldercounter
1076 last_set = None
1090 last_set = None
1077
1091
1078 else:
1092 else:
1079 print "[Reading] Searching files in offline mode ..."
1093 print "[Reading] Searching files in offline mode ..."
1080 pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1094 pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1081 startTime=startTime, endTime=endTime,
1095 startTime=startTime, endTime=endTime,
1082 set=set, expLabel=expLabel, ext=ext,
1096 set=set, expLabel=expLabel, ext=ext,
1083 walk=walk)
1097 walk=walk)
1084
1098
1085 if not(pathList):
1099 if not(pathList):
1086 print "[Reading] No *%s files into the folder %s \nfor the range: %s - %s"%(ext, path,
1100 print "[Reading] No *%s files into the folder %s \nfor the range: %s - %s"%(ext, path,
1087 datetime.datetime.combine(startDate,startTime).ctime(),
1101 datetime.datetime.combine(startDate,startTime).ctime(),
1088 datetime.datetime.combine(endDate,endTime).ctime())
1102 datetime.datetime.combine(endDate,endTime).ctime())
1089
1103
1090 sys.exit(-1)
1104 sys.exit(-1)
1091
1105
1092
1106
1093 self.fileIndex = -1
1107 self.fileIndex = -1
1094 self.pathList = pathList
1108 self.pathList = pathList
1095 self.filenameList = filenameList
1109 self.filenameList = filenameList
1096 file_name = os.path.basename(filenameList[-1])
1110 file_name = os.path.basename(filenameList[-1])
1097 basename, ext = os.path.splitext(file_name)
1111 basename, ext = os.path.splitext(file_name)
1098 last_set = int(basename[-3:])
1112 last_set = int(basename[-3:])
1099
1113
1100 self.online = online
1114 self.online = online
1101 self.delay = delay
1115 self.delay = delay
1102 ext = ext.lower()
1116 ext = ext.lower()
1103 self.ext = ext
1117 self.ext = ext
1104 self.getByBlock = getblock
1118 self.getByBlock = getblock
1105 self.nTxs = int(nTxs)
1119 self.nTxs = int(nTxs)
1106
1120
1107 if not(self.setNextFile()):
1121 if not(self.setNextFile()):
1108 if (startDate!=None) and (endDate!=None):
1122 if (startDate!=None) and (endDate!=None):
1109 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1123 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1110 elif startDate != None:
1124 elif startDate != None:
1111 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1125 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1112 else:
1126 else:
1113 print "[Reading] No files"
1127 print "[Reading] No files"
1114
1128
1115 sys.exit(-1)
1129 sys.exit(-1)
1116
1130
1117 # self.updateDataHeader()
1131 # self.updateDataHeader()
1118 if last_set != None:
1132 if last_set != None:
1119 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1133 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1120 return
1134 return
1121
1135
1122 def getBasicHeader(self):
1136 def getBasicHeader(self):
1123
1137
1124 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1138 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1125
1139
1126 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1140 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1127
1141
1128 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1142 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1129
1143
1130 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1144 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1131
1145
1132 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1146 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1133
1147
1134 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1148 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1135
1149
1136 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1150 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1137
1151
1138 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1152 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1139
1153
1140
1154
1141 def getFirstHeader(self):
1155 def getFirstHeader(self):
1142
1156
1143 raise ValueError, "This method has not been implemented"
1157 raise ValueError, "This method has not been implemented"
1144
1158
1145 def getData(self):
1159 def getData(self):
1146
1160
1147 raise ValueError, "This method has not been implemented"
1161 raise ValueError, "This method has not been implemented"
1148
1162
1149 def hasNotDataInBuffer(self):
1163 def hasNotDataInBuffer(self):
1150
1164
1151 raise ValueError, "This method has not been implemented"
1165 raise ValueError, "This method has not been implemented"
1152
1166
1153 def readBlock(self):
1167 def readBlock(self):
1154
1168
1155 raise ValueError, "This method has not been implemented"
1169 raise ValueError, "This method has not been implemented"
1156
1170
1157 def isEndProcess(self):
1171 def isEndProcess(self):
1158
1172
1159 return self.flagNoMoreFiles
1173 return self.flagNoMoreFiles
1160
1174
1161 def printReadBlocks(self):
1175 def printReadBlocks(self):
1162
1176
1163 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1177 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1164
1178
1165 def printTotalBlocks(self):
1179 def printTotalBlocks(self):
1166
1180
1167 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1181 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1168
1182
1169 def printNumberOfBlock(self):
1183 def printNumberOfBlock(self):
1170
1184
1171 if self.flagIsNewBlock:
1185 if self.flagIsNewBlock:
1172 print "[Reading] Block No. %04d, Total blocks %04d -> %s" %(self.basicHeaderObj.dataBlock, self.nTotalBlocks, self.dataOut.datatime.ctime())
1186 print "[Reading] Block No. %04d, Total blocks %04d -> %s" %(self.basicHeaderObj.dataBlock, self.nTotalBlocks, self.dataOut.datatime.ctime())
1173 self.dataOut.blocknow = self.basicHeaderObj.dataBlock
1187 self.dataOut.blocknow = self.basicHeaderObj.dataBlock
1174
1188
1175 def printInfo(self):
1189 def printInfo(self):
1176
1190
1177 if self.__printInfo == False:
1191 if self.__printInfo == False:
1178 return
1192 return
1179
1193
1180 self.basicHeaderObj.printInfo()
1194 self.basicHeaderObj.printInfo()
1181 self.systemHeaderObj.printInfo()
1195 self.systemHeaderObj.printInfo()
1182 self.radarControllerHeaderObj.printInfo()
1196 self.radarControllerHeaderObj.printInfo()
1183 self.processingHeaderObj.printInfo()
1197 self.processingHeaderObj.printInfo()
1184
1198
1185 self.__printInfo = False
1199 self.__printInfo = False
1186
1200
1187
1201
1188 def run(self, **kwargs):
1202 def run(self, **kwargs):
1189
1203
1190 if not(self.isConfig):
1204 if not(self.isConfig):
1191
1205
1192 # self.dataOut = dataOut
1206 # self.dataOut = dataOut
1193 self.setup(**kwargs)
1207 self.setup(**kwargs)
1194 self.isConfig = True
1208 self.isConfig = True
1195
1209
1196 self.getData()
1210 self.getData()
1197
1211
1198 class JRODataWriter(JRODataIO):
1212 class JRODataWriter(JRODataIO):
1199
1213
1200 """
1214 """
1201 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1215 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1202 de los datos siempre se realiza por bloques.
1216 de los datos siempre se realiza por bloques.
1203 """
1217 """
1204
1218
1205 blockIndex = 0
1219 blockIndex = 0
1206
1220
1207 path = None
1221 path = None
1208
1222
1209 setFile = None
1223 setFile = None
1210
1224
1211 profilesPerBlock = None
1225 profilesPerBlock = None
1212
1226
1213 blocksPerFile = None
1227 blocksPerFile = None
1214
1228
1215 nWriteBlocks = 0
1229 nWriteBlocks = 0
1216
1230
1217 def __init__(self, dataOut=None):
1231 def __init__(self, dataOut=None):
1218 raise ValueError, "Not implemented"
1232 raise ValueError, "Not implemented"
1219
1233
1220
1234
1221 def hasAllDataInBuffer(self):
1235 def hasAllDataInBuffer(self):
1222 raise ValueError, "Not implemented"
1236 raise ValueError, "Not implemented"
1223
1237
1224
1238
1225 def setBlockDimension(self):
1239 def setBlockDimension(self):
1226 raise ValueError, "Not implemented"
1240 raise ValueError, "Not implemented"
1227
1241
1228
1242
1229 def writeBlock(self):
1243 def writeBlock(self):
1230 raise ValueError, "No implemented"
1244 raise ValueError, "No implemented"
1231
1245
1232
1246
1233 def putData(self):
1247 def putData(self):
1234 raise ValueError, "No implemented"
1248 raise ValueError, "No implemented"
1235
1249
1236
1250
1237 def setBasicHeader(self):
1251 def setBasicHeader(self):
1238
1252
1239 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1253 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1240 self.basicHeaderObj.version = self.versionFile
1254 self.basicHeaderObj.version = self.versionFile
1241 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1255 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1242
1256
1243 utc = numpy.floor(self.dataOut.utctime)
1257 utc = numpy.floor(self.dataOut.utctime)
1244 milisecond = (self.dataOut.utctime - utc)* 1000.0
1258 milisecond = (self.dataOut.utctime - utc)* 1000.0
1245
1259
1246 self.basicHeaderObj.utc = utc
1260 self.basicHeaderObj.utc = utc
1247 self.basicHeaderObj.miliSecond = milisecond
1261 self.basicHeaderObj.miliSecond = milisecond
1248 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1262 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1249 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1263 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1250 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1264 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1251
1265
1252 def setFirstHeader(self):
1266 def setFirstHeader(self):
1253 """
1267 """
1254 Obtiene una copia del First Header
1268 Obtiene una copia del First Header
1255
1269
1256 Affected:
1270 Affected:
1257
1271
1258 self.basicHeaderObj
1272 self.basicHeaderObj
1259 self.systemHeaderObj
1273 self.systemHeaderObj
1260 self.radarControllerHeaderObj
1274 self.radarControllerHeaderObj
1261 self.processingHeaderObj self.
1275 self.processingHeaderObj self.
1262
1276
1263 Return:
1277 Return:
1264 None
1278 None
1265 """
1279 """
1266
1280
1267 raise ValueError, "No implemented"
1281 raise ValueError, "No implemented"
1268
1282
1269 def __writeFirstHeader(self):
1283 def __writeFirstHeader(self):
1270 """
1284 """
1271 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1285 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1272
1286
1273 Affected:
1287 Affected:
1274 __dataType
1288 __dataType
1275
1289
1276 Return:
1290 Return:
1277 None
1291 None
1278 """
1292 """
1279
1293
1280 # CALCULAR PARAMETROS
1294 # CALCULAR PARAMETROS
1281
1295
1282 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1296 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1283 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1297 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1284
1298
1285 self.basicHeaderObj.write(self.fp)
1299 self.basicHeaderObj.write(self.fp)
1286 self.systemHeaderObj.write(self.fp)
1300 self.systemHeaderObj.write(self.fp)
1287 self.radarControllerHeaderObj.write(self.fp)
1301 self.radarControllerHeaderObj.write(self.fp)
1288 self.processingHeaderObj.write(self.fp)
1302 self.processingHeaderObj.write(self.fp)
1289
1303
1290 self.dtype = self.dataOut.dtype
1304 self.dtype = self.dataOut.dtype
1291
1305
1292 def __setNewBlock(self):
1306 def __setNewBlock(self):
1293 """
1307 """
1294 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1308 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1295
1309
1296 Return:
1310 Return:
1297 0 : si no pudo escribir nada
1311 0 : si no pudo escribir nada
1298 1 : Si escribio el Basic el First Header
1312 1 : Si escribio el Basic el First Header
1299 """
1313 """
1300 if self.fp == None:
1314 if self.fp == None:
1301 self.setNextFile()
1315 self.setNextFile()
1302
1316
1303 if self.flagIsNewFile:
1317 if self.flagIsNewFile:
1304 return 1
1318 return 1
1305
1319
1306 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1320 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1307 self.basicHeaderObj.write(self.fp)
1321 self.basicHeaderObj.write(self.fp)
1308 return 1
1322 return 1
1309
1323
1310 if not( self.setNextFile() ):
1324 if not( self.setNextFile() ):
1311 return 0
1325 return 0
1312
1326
1313 return 1
1327 return 1
1314
1328
1315
1329
1316 def writeNextBlock(self):
1330 def writeNextBlock(self):
1317 """
1331 """
1318 Selecciona el bloque siguiente de datos y los escribe en un file
1332 Selecciona el bloque siguiente de datos y los escribe en un file
1319
1333
1320 Return:
1334 Return:
1321 0 : Si no hizo pudo escribir el bloque de datos
1335 0 : Si no hizo pudo escribir el bloque de datos
1322 1 : Si no pudo escribir el bloque de datos
1336 1 : Si no pudo escribir el bloque de datos
1323 """
1337 """
1324 if not( self.__setNewBlock() ):
1338 if not( self.__setNewBlock() ):
1325 return 0
1339 return 0
1326
1340
1327 self.writeBlock()
1341 self.writeBlock()
1328
1342
1329 return 1
1343 return 1
1330
1344
1331 def setNextFile(self):
1345 def setNextFile(self):
1332 """
1346 """
1333 Determina el siguiente file que sera escrito
1347 Determina el siguiente file que sera escrito
1334
1348
1335 Affected:
1349 Affected:
1336 self.filename
1350 self.filename
1337 self.subfolder
1351 self.subfolder
1338 self.fp
1352 self.fp
1339 self.setFile
1353 self.setFile
1340 self.flagIsNewFile
1354 self.flagIsNewFile
1341
1355
1342 Return:
1356 Return:
1343 0 : Si el archivo no puede ser escrito
1357 0 : Si el archivo no puede ser escrito
1344 1 : Si el archivo esta listo para ser escrito
1358 1 : Si el archivo esta listo para ser escrito
1345 """
1359 """
1346 ext = self.ext
1360 ext = self.ext
1347 path = self.path
1361 path = self.path
1348
1362
1349 if self.fp != None:
1363 if self.fp != None:
1350 self.fp.close()
1364 self.fp.close()
1351
1365
1352 timeTuple = time.localtime( self.dataOut.utctime)
1366 timeTuple = time.localtime( self.dataOut.utctime)
1353 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1367 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1354
1368
1355 fullpath = os.path.join( path, subfolder )
1369 fullpath = os.path.join( path, subfolder )
1356 if not( os.path.exists(fullpath) ):
1370 if not( os.path.exists(fullpath) ):
1357 os.mkdir(fullpath)
1371 os.mkdir(fullpath)
1358 self.setFile = -1 #inicializo mi contador de seteo
1372 self.setFile = -1 #inicializo mi contador de seteo
1359 else:
1373 else:
1360 filesList = os.listdir( fullpath )
1374 filesList = os.listdir( fullpath )
1361 if len( filesList ) > 0:
1375 if len( filesList ) > 0:
1362 filesList = sorted( filesList, key=str.lower )
1376 filesList = sorted( filesList, key=str.lower )
1363 filen = filesList[-1]
1377 filen = filesList[-1]
1364 # el filename debera tener el siguiente formato
1378 # el filename debera tener el siguiente formato
1365 # 0 1234 567 89A BCDE (hex)
1379 # 0 1234 567 89A BCDE (hex)
1366 # x YYYY DDD SSS .ext
1380 # x YYYY DDD SSS .ext
1367 if isNumber( filen[8:11] ):
1381 if isNumber( filen[8:11] ):
1368 self.setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1382 self.setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1369 else:
1383 else:
1370 self.setFile = -1
1384 self.setFile = -1
1371 else:
1385 else:
1372 self.setFile = -1 #inicializo mi contador de seteo
1386 self.setFile = -1 #inicializo mi contador de seteo
1373
1387
1374 setFile = self.setFile
1388 setFile = self.setFile
1375 setFile += 1
1389 setFile += 1
1376
1390
1377 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar,
1391 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar,
1378 timeTuple.tm_year,
1392 timeTuple.tm_year,
1379 timeTuple.tm_yday,
1393 timeTuple.tm_yday,
1380 setFile,
1394 setFile,
1381 ext )
1395 ext )
1382
1396
1383 filename = os.path.join( path, subfolder, filen )
1397 filename = os.path.join( path, subfolder, filen )
1384
1398
1385 fp = open( filename,'wb' )
1399 fp = open( filename,'wb' )
1386
1400
1387 self.blockIndex = 0
1401 self.blockIndex = 0
1388
1402
1389 #guardando atributos
1403 #guardando atributos
1390 self.filename = filename
1404 self.filename = filename
1391 self.subfolder = subfolder
1405 self.subfolder = subfolder
1392 self.fp = fp
1406 self.fp = fp
1393 self.setFile = setFile
1407 self.setFile = setFile
1394 self.flagIsNewFile = 1
1408 self.flagIsNewFile = 1
1395
1409
1396 self.setFirstHeader()
1410 self.setFirstHeader()
1397
1411
1398 print '[Writing] file: %s'%self.filename
1412 print '[Writing] file: %s'%self.filename
1399
1413
1400 self.__writeFirstHeader()
1414 self.__writeFirstHeader()
1401
1415
1402 return 1
1416 return 1
1403
1417
1404 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=0, ext=None):
1418 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=0, ext=None):
1405 """
1419 """
1406 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1420 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1407
1421
1408 Inputs:
1422 Inputs:
1409 path : el path destino en el cual se escribiran los files a crear
1423 path : el path destino en el cual se escribiran los files a crear
1410 format : formato en el cual sera salvado un file
1424 format : formato en el cual sera salvado un file
1411 set : el setebo del file
1425 set : el setebo del file
1412
1426
1413 Return:
1427 Return:
1414 0 : Si no realizo un buen seteo
1428 0 : Si no realizo un buen seteo
1415 1 : Si realizo un buen seteo
1429 1 : Si realizo un buen seteo
1416 """
1430 """
1417
1431
1418 if ext == None:
1432 if ext == None:
1419 ext = self.ext
1433 ext = self.ext
1420
1434
1421 ext = ext.lower()
1435 ext = ext.lower()
1422
1436
1423 self.ext = ext
1437 self.ext = ext
1424
1438
1425 self.path = path
1439 self.path = path
1426
1440
1427 self.setFile = set - 1
1441 self.setFile = set - 1
1428
1442
1429 self.blocksPerFile = blocksPerFile
1443 self.blocksPerFile = blocksPerFile
1430
1444
1431 self.profilesPerBlock = profilesPerBlock
1445 self.profilesPerBlock = profilesPerBlock
1432
1446
1433 self.dataOut = dataOut
1447 self.dataOut = dataOut
1434
1448
1435 if not(self.setNextFile()):
1449 if not(self.setNextFile()):
1436 print "[Writing] There isn't a next file"
1450 print "[Writing] There isn't a next file"
1437 return 0
1451 return 0
1438
1452
1439 self.setBlockDimension()
1453 self.setBlockDimension()
1440
1454
1441 return 1
1455 return 1
1442
1456
1443 def run(self, dataOut, **kwargs):
1457 def run(self, dataOut, **kwargs):
1444
1458
1445 if not(self.isConfig):
1459 if not(self.isConfig):
1446
1460
1447 self.setup(dataOut, **kwargs)
1461 self.setup(dataOut, **kwargs)
1448 self.isConfig = True
1462 self.isConfig = True
1449
1463
1450 self.putData()
1464 self.putData()
1451
1465
@@ -1,583 +1,590
1 '''
1 '''
2 Created on Jul 3, 2014
2 Created on Jul 3, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import datetime
7 import datetime
7 import numpy
8 import numpy
8
9
9 try:
10 try:
10 from gevent import sleep
11 from gevent import sleep
11 except:
12 except:
12 from time import sleep
13 from time import sleep
13
14
14 from schainpy.model.data.jroheaderIO import RadarControllerHeader, SystemHeader
15 from schainpy.model.data.jroheaderIO import RadarControllerHeader, SystemHeader
15 from schainpy.model.data.jrodata import Voltage
16 from schainpy.model.data.jrodata import Voltage
16 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
17 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
17
18
18 try:
19 try:
19 import digital_rf_hdf5
20 import digital_rf_hdf5
20 except:
21 except:
21 print 'You should install "digital_rf_hdf5" module if you want to read USRP data'
22 print 'You should install "digital_rf_hdf5" module if you want to read USRP data'
22
23
23 class USRPReader(ProcessingUnit):
24 class USRPReader(ProcessingUnit):
24 '''
25 '''
25 classdocs
26 classdocs
26 '''
27 '''
27
28
28 def __init__(self):
29 def __init__(self):
29 '''
30 '''
30 Constructor
31 Constructor
31 '''
32 '''
32
33
33 ProcessingUnit.__init__(self)
34 ProcessingUnit.__init__(self)
34
35
35 self.dataOut = Voltage()
36 self.dataOut = Voltage()
36 self.__printInfo = True
37 self.__printInfo = True
37 self.__flagDiscontinuousBlock = False
38 self.__flagDiscontinuousBlock = False
38 self.__bufferIndex = 9999999
39 self.__bufferIndex = 9999999
39
40
40 self.__ippKm = None
41 self.__ippKm = None
41 self.__codeType = 0
42 self.__codeType = 0
42 self.__nCode = None
43 self.__nCode = None
43 self.__nBaud = None
44 self.__nBaud = None
44 self.__code = None
45 self.__code = None
45
46
46 def __getCurrentSecond(self):
47 def __getCurrentSecond(self):
47
48
48 return self.__thisUnixSample/self.__sample_rate
49 return self.__thisUnixSample/self.__sample_rate
49
50
50 thisSecond = property(__getCurrentSecond, "I'm the 'thisSecond' property.")
51 thisSecond = property(__getCurrentSecond, "I'm the 'thisSecond' property.")
51
52
52 def __setFileHeader(self):
53 def __setFileHeader(self):
53 '''
54 '''
54 In this method will be initialized every parameter of dataOut object (header, no data)
55 In this method will be initialized every parameter of dataOut object (header, no data)
55 '''
56 '''
56 nProfiles = self.__sample_rate #Number of profiles by second
57 nProfiles = self.__sample_rate #Number of profiles by second
57
58
58 self.dataOut.radarControllerHeaderObj = RadarControllerHeader(ippKm=self.__ippKm,
59 self.dataOut.radarControllerHeaderObj = RadarControllerHeader(ippKm=self.__ippKm,
59 txA=0,
60 txA=0,
60 txB=0,
61 txB=0,
61 nWindows=1,
62 nWindows=1,
62 nHeights=self.__nSamples,
63 nHeights=self.__nSamples,
63 firstHeight=self.__firstHeigth,
64 firstHeight=self.__firstHeigth,
64 deltaHeight=self.__deltaHeigth,
65 deltaHeight=self.__deltaHeigth,
65 codeType=self.__codeType,
66 codeType=self.__codeType,
66 nCode=self.__nCode, nBaud=self.__nBaud,
67 nCode=self.__nCode, nBaud=self.__nBaud,
67 code = self.__code)
68 code = self.__code)
68
69
69 self.dataOut.systemHeaderObj = SystemHeader(nSamples=self.__nSamples,
70 self.dataOut.systemHeaderObj = SystemHeader(nSamples=self.__nSamples,
70 nProfiles=nProfiles,
71 nProfiles=nProfiles,
71 nChannels=len(self.__channelList),
72 nChannels=len(self.__channelList),
72 adcResolution=14)
73 adcResolution=14)
73
74
74 self.dataOut.type = "Voltage"
75 self.dataOut.type = "Voltage"
75
76
76 self.dataOut.data = None
77 self.dataOut.data = None
77
78
78 self.dataOut.dtype = numpy.dtype([('real','<i8'),('imag','<i8')])
79 self.dataOut.dtype = numpy.dtype([('real','<i8'),('imag','<i8')])
79
80
80 # self.dataOut.nChannels = 0
81 # self.dataOut.nChannels = 0
81
82
82 # self.dataOut.nHeights = 0
83 # self.dataOut.nHeights = 0
83
84
84 self.dataOut.nProfiles = nProfiles
85 self.dataOut.nProfiles = nProfiles
85
86
86 self.dataOut.heightList = self.__firstHeigth + numpy.arange(self.__nSamples, dtype = numpy.float)*self.__deltaHeigth
87 self.dataOut.heightList = self.__firstHeigth + numpy.arange(self.__nSamples, dtype = numpy.float)*self.__deltaHeigth
87
88
88 self.dataOut.channelList = self.__channelList
89 self.dataOut.channelList = self.__channelList
89
90
90 self.dataOut.blocksize = self.dataOut.getNChannels() * self.dataOut.getNHeights()
91 self.dataOut.blocksize = self.dataOut.getNChannels() * self.dataOut.getNHeights()
91
92
92 # self.dataOut.channelIndexList = None
93 # self.dataOut.channelIndexList = None
93
94
94 self.dataOut.flagNoData = True
95 self.dataOut.flagNoData = True
95
96
96 #Set to TRUE if the data is discontinuous
97 #Set to TRUE if the data is discontinuous
97 self.dataOut.flagDiscontinuousBlock = False
98 self.dataOut.flagDiscontinuousBlock = False
98
99
99 self.dataOut.utctime = None
100 self.dataOut.utctime = None
100
101
101 self.dataOut.timeZone = self.__timezone/60 #timezone like jroheader, difference in minutes between UTC and localtime
102 self.dataOut.timeZone = self.__timezone/60 #timezone like jroheader, difference in minutes between UTC and localtime
102
103
103 self.dataOut.dstFlag = 0
104 self.dataOut.dstFlag = 0
104
105
105 self.dataOut.errorCount = 0
106 self.dataOut.errorCount = 0
106
107
107 self.dataOut.nCohInt = 1
108 self.dataOut.nCohInt = 1
108
109
109 self.dataOut.flagDecodeData = False #asumo que la data esta decodificada
110 self.dataOut.flagDecodeData = False #asumo que la data esta decodificada
110
111
111 self.dataOut.flagDeflipData = False #asumo que la data esta sin flip
112 self.dataOut.flagDeflipData = False #asumo que la data esta sin flip
112
113
113 self.dataOut.flagShiftFFT = False
114 self.dataOut.flagShiftFFT = False
114
115
115 self.dataOut.ippSeconds = 1.0*self.__nSamples/self.__sample_rate
116 self.dataOut.ippSeconds = 1.0*self.__nSamples/self.__sample_rate
116
117
117 #Time interval between profiles
118 #Time interval between profiles
118 #self.dataOut.timeInterval = self.dataOut.ippSeconds * self.dataOut.nCohInt
119 #self.dataOut.timeInterval = self.dataOut.ippSeconds * self.dataOut.nCohInt
119
120
120 self.dataOut.frequency = self.__frequency
121 self.dataOut.frequency = self.__frequency
121
122
122 self.dataOut.realtime = self.__online
123 self.dataOut.realtime = self.__online
123
124
124 def findDatafiles(self, path, startDate=None, endDate=None):
125 def findDatafiles(self, path, startDate=None, endDate=None):
125
126
127 if not os.path.isdir(path):
128 return []
129
126 try:
130 try:
127 digitalReadObj = digital_rf_hdf5.read_hdf5(path, load_all_metadata=True)
131 digitalReadObj = digital_rf_hdf5.read_hdf5(path, load_all_metadata=True)
128 except:
132 except:
129 digitalReadObj = digital_rf_hdf5.read_hdf5(path)
133 digitalReadObj = digital_rf_hdf5.read_hdf5(path)
130
134
131 channelNameList = digitalReadObj.get_channels()
135 channelNameList = digitalReadObj.get_channels()
132
136
133 if not channelNameList:
137 if not channelNameList:
134 return []
138 return []
135
139
136 metadata_dict = digitalReadObj.get_rf_file_metadata(channelNameList[0])
140 metadata_dict = digitalReadObj.get_rf_file_metadata(channelNameList[0])
137
141
138 sample_rate = metadata_dict['sample_rate'][0]
142 sample_rate = metadata_dict['sample_rate'][0]
139
143
140 this_metadata_file = digitalReadObj.get_metadata(channelNameList[0])
144 this_metadata_file = digitalReadObj.get_metadata(channelNameList[0])
141
145
142 try:
146 try:
143 timezone = this_metadata_file['timezone'].value
147 timezone = this_metadata_file['timezone'].value
144 except:
148 except:
145 timezone = 0
149 timezone = 0
146
150
147 startUTCSecond, endUTCSecond = digitalReadObj.get_bounds(channelNameList[0])/sample_rate - timezone
151 startUTCSecond, endUTCSecond = digitalReadObj.get_bounds(channelNameList[0])/sample_rate - timezone
148
152
149 startDatetime = datetime.datetime.utcfromtimestamp(startUTCSecond)
153 startDatetime = datetime.datetime.utcfromtimestamp(startUTCSecond)
150 endDatatime = datetime.datetime.utcfromtimestamp(endUTCSecond)
154 endDatatime = datetime.datetime.utcfromtimestamp(endUTCSecond)
151
155
152 if not startDate:
156 if not startDate:
153 startDate = startDatetime.date()
157 startDate = startDatetime.date()
154
158
155 if not endDate:
159 if not endDate:
156 endDate = endDatatime.date()
160 endDate = endDatatime.date()
157
161
158 dateList = []
162 dateList = []
159
163
160 thisDatetime = startDatetime
164 thisDatetime = startDatetime
161
165
162 while(thisDatetime<=endDatatime):
166 while(thisDatetime<=endDatatime):
163
167
164 thisDate = thisDatetime.date()
168 thisDate = thisDatetime.date()
165
169
166 if thisDate < startDate:
170 if thisDate < startDate:
167 continue
171 continue
168
172
169 if thisDate > endDate:
173 if thisDate > endDate:
170 break
174 break
171
175
172 dateList.append(thisDate)
176 dateList.append(thisDate)
173 thisDatetime += datetime.timedelta(1)
177 thisDatetime += datetime.timedelta(1)
174
178
175 return dateList
179 return dateList
176
180
177 def setup(self, path = None,
181 def setup(self, path = None,
178 startDate = None,
182 startDate = None,
179 endDate = None,
183 endDate = None,
180 startTime = datetime.time(0,0,0),
184 startTime = datetime.time(0,0,0),
181 endTime = datetime.time(23,59,59),
185 endTime = datetime.time(23,59,59),
182 channelList = None,
186 channelList = None,
183 nSamples = None,
187 nSamples = None,
184 ippKm = 60,
188 ippKm = 60,
185 online = False,
189 online = False,
186 delay = 60,
190 delay = 60,
187 buffer_size = None,
191 buffer_size = None,
188 nbuffer = 1024,
192 nbuffer = 1024,
189 **kwargs):
193 **kwargs):
190 '''
194 '''
191 In this method we should set all initial parameters.
195 In this method we should set all initial parameters.
192
196
193 Inputs:
197 Inputs:
194 path
198 path
195 startDate
199 startDate
196 endDate
200 endDate
197 startTime
201 startTime
198 endTime
202 endTime
199 set
203 set
200 expLabel
204 expLabel
201 ext
205 ext
202 online
206 online
203 delay
207 delay
204 '''
208 '''
205
209
206 if not buffer_size:
210 if not buffer_size:
207 buffer_size = nbuffer
211 buffer_size = nbuffer
208
212
213 if not os.path.isdir(path):
214 raise ValueError, "[Reading] This path %s does not exist" %path
215
209 try:
216 try:
210 self.digitalReadObj = digital_rf_hdf5.read_hdf5(path, load_all_metadata=True)
217 self.digitalReadObj = digital_rf_hdf5.read_hdf5(path, load_all_metadata=True)
211 except:
218 except:
212 self.digitalReadObj = digital_rf_hdf5.read_hdf5(path)
219 self.digitalReadObj = digital_rf_hdf5.read_hdf5(path)
213
220
214 channelNameList = self.digitalReadObj.get_channels()
221 channelNameList = self.digitalReadObj.get_channels()
215
222
216 if not channelNameList:
223 if not channelNameList:
217 raise IOError, "[Reading] The path doesn,t have any files .. "
224 raise IOError, "[Reading] The path doesn,t have any files .. "
218
225
219 if not channelList:
226 if not channelList:
220 channelList = range(len(channelNameList))
227 channelList = range(len(channelNameList))
221
228
222 ########## Reading metadata ######################
229 ########## Reading metadata ######################
223
230
224 metadata_dict = self.digitalReadObj.get_rf_file_metadata(channelNameList[channelList[0]])
231 metadata_dict = self.digitalReadObj.get_rf_file_metadata(channelNameList[channelList[0]])
225
232
226 self.__sample_rate = metadata_dict['sample_rate'][0]
233 self.__sample_rate = metadata_dict['sample_rate'][0]
227 self.__samples_per_file = metadata_dict['samples_per_file'][0]
234 self.__samples_per_file = metadata_dict['samples_per_file'][0]
228 self.__deltaHeigth = 1e6*0.15/self.__sample_rate
235 self.__deltaHeigth = 1e6*0.15/self.__sample_rate
229
236
230 this_metadata_file = self.digitalReadObj.get_metadata(channelNameList[channelList[0]])
237 this_metadata_file = self.digitalReadObj.get_metadata(channelNameList[channelList[0]])
231
238
232 self.__frequency = this_metadata_file['center_frequencies'].value
239 self.__frequency = this_metadata_file['center_frequencies'].value
233 try:
240 try:
234 self.__timezone = this_metadata_file['timezone'].value
241 self.__timezone = this_metadata_file['timezone'].value
235 except:
242 except:
236 self.__timezone = 0
243 self.__timezone = 0
237
244
238 self.__firstHeigth = 0
245 self.__firstHeigth = 0
239
246
240 try:
247 try:
241 codeType = this_metadata_file['codeType'].value
248 codeType = this_metadata_file['codeType'].value
242 except:
249 except:
243 codeType = 0
250 codeType = 0
244
251
245 nCode = 0
252 nCode = 0
246 nBaud = 0
253 nBaud = 0
247 code = None
254 code = None
248
255
249 if codeType:
256 if codeType:
250 nCode = this_metadata_file['nCode'].value
257 nCode = this_metadata_file['nCode'].value
251 nBaud = this_metadata_file['nBaud'].value
258 nBaud = this_metadata_file['nBaud'].value
252 code = this_metadata_file['code'].value
259 code = this_metadata_file['code'].value
253
260
254 if not ippKm:
261 if not ippKm:
255 try:
262 try:
256 #seconds to km
263 #seconds to km
257 ippKm = 1e6*0.15*this_metadata_file['ipp'].value
264 ippKm = 1e6*0.15*this_metadata_file['ipp'].value
258 except:
265 except:
259 ippKm = None
266 ippKm = None
260
267
261 ####################################################
268 ####################################################
262 startUTCSecond = None
269 startUTCSecond = None
263 endUTCSecond = None
270 endUTCSecond = None
264
271
265 if startDate:
272 if startDate:
266 startDatetime = datetime.datetime.combine(startDate, startTime)
273 startDatetime = datetime.datetime.combine(startDate, startTime)
267 startUTCSecond = (startDatetime-datetime.datetime(1970,1,1)).total_seconds() + self.__timezone
274 startUTCSecond = (startDatetime-datetime.datetime(1970,1,1)).total_seconds() + self.__timezone
268
275
269 if endDate:
276 if endDate:
270 endDatetime = datetime.datetime.combine(endDate, endTime)
277 endDatetime = datetime.datetime.combine(endDate, endTime)
271 endUTCSecond = (endDatetime-datetime.datetime(1970,1,1)).total_seconds() + self.__timezone
278 endUTCSecond = (endDatetime-datetime.datetime(1970,1,1)).total_seconds() + self.__timezone
272
279
273 start_index, end_index = self.digitalReadObj.get_bounds(channelNameList[channelList[0]])
280 start_index, end_index = self.digitalReadObj.get_bounds(channelNameList[channelList[0]])
274
281
275 if not startUTCSecond:
282 if not startUTCSecond:
276 startUTCSecond = start_index/self.__sample_rate
283 startUTCSecond = start_index/self.__sample_rate
277
284
278 if start_index > startUTCSecond*self.__sample_rate:
285 if start_index > startUTCSecond*self.__sample_rate:
279 startUTCSecond = start_index/self.__sample_rate
286 startUTCSecond = start_index/self.__sample_rate
280
287
281 if not endUTCSecond:
288 if not endUTCSecond:
282 endUTCSecond = end_index/self.__sample_rate
289 endUTCSecond = end_index/self.__sample_rate
283
290
284 if end_index < endUTCSecond*self.__sample_rate:
291 if end_index < endUTCSecond*self.__sample_rate:
285 endUTCSecond = end_index/self.__sample_rate
292 endUTCSecond = end_index/self.__sample_rate
286
293
287 if not nSamples:
294 if not nSamples:
288 if not ippKm:
295 if not ippKm:
289 raise ValueError, "[Reading] nSamples or ippKm should be defined"
296 raise ValueError, "[Reading] nSamples or ippKm should be defined"
290
297
291 nSamples = ippKm / (1e6*0.15/self.__sample_rate)
298 nSamples = ippKm / (1e6*0.15/self.__sample_rate)
292
299
293 channelBoundList = []
300 channelBoundList = []
294 channelNameListFiltered = []
301 channelNameListFiltered = []
295
302
296 for thisIndexChannel in channelList:
303 for thisIndexChannel in channelList:
297 thisChannelName = channelNameList[thisIndexChannel]
304 thisChannelName = channelNameList[thisIndexChannel]
298 start_index, end_index = self.digitalReadObj.get_bounds(thisChannelName)
305 start_index, end_index = self.digitalReadObj.get_bounds(thisChannelName)
299 channelBoundList.append((start_index, end_index))
306 channelBoundList.append((start_index, end_index))
300 channelNameListFiltered.append(thisChannelName)
307 channelNameListFiltered.append(thisChannelName)
301
308
302 self.profileIndex = 0
309 self.profileIndex = 0
303
310
304 self.__delay = delay
311 self.__delay = delay
305 self.__ippKm = ippKm
312 self.__ippKm = ippKm
306 self.__codeType = codeType
313 self.__codeType = codeType
307 self.__nCode = nCode
314 self.__nCode = nCode
308 self.__nBaud = nBaud
315 self.__nBaud = nBaud
309 self.__code = code
316 self.__code = code
310
317
311 self.__datapath = path
318 self.__datapath = path
312 self.__online = online
319 self.__online = online
313 self.__channelList = channelList
320 self.__channelList = channelList
314 self.__channelNameList = channelNameListFiltered
321 self.__channelNameList = channelNameListFiltered
315 self.__channelBoundList = channelBoundList
322 self.__channelBoundList = channelBoundList
316 self.__nSamples = nSamples
323 self.__nSamples = nSamples
317 self.__samples_to_read = buffer_size*nSamples
324 self.__samples_to_read = buffer_size*nSamples
318 self.__nChannels = len(self.__channelList)
325 self.__nChannels = len(self.__channelList)
319
326
320 self.__startUTCSecond = startUTCSecond
327 self.__startUTCSecond = startUTCSecond
321 self.__endUTCSecond = endUTCSecond
328 self.__endUTCSecond = endUTCSecond
322
329
323 self.__timeInterval = 1.0 * self.__samples_to_read/self.__sample_rate #Time interval
330 self.__timeInterval = 1.0 * self.__samples_to_read/self.__sample_rate #Time interval
324
331
325 if online:
332 if online:
326 # self.__thisUnixSample = int(endUTCSecond*self.__sample_rate - 4*self.__samples_to_read)
333 # self.__thisUnixSample = int(endUTCSecond*self.__sample_rate - 4*self.__samples_to_read)
327 startUTCSecond = numpy.floor(endUTCSecond)
334 startUTCSecond = numpy.floor(endUTCSecond)
328
335
329 self.__thisUnixSample = int(startUTCSecond*self.__sample_rate) - self.__samples_to_read
336 self.__thisUnixSample = int(startUTCSecond*self.__sample_rate) - self.__samples_to_read
330
337
331 self.__data_buffer = numpy.zeros((self.__nChannels, self.__samples_to_read), dtype = numpy.complex)
338 self.__data_buffer = numpy.zeros((self.__nChannels, self.__samples_to_read), dtype = numpy.complex)
332
339
333 self.__setFileHeader()
340 self.__setFileHeader()
334 self.isConfig = True
341 self.isConfig = True
335
342
336 print "[Reading] USRP Data was found from %s to %s " %(
343 print "[Reading] USRP Data was found from %s to %s " %(
337 datetime.datetime.utcfromtimestamp(self.__startUTCSecond - self.__timezone),
344 datetime.datetime.utcfromtimestamp(self.__startUTCSecond - self.__timezone),
338 datetime.datetime.utcfromtimestamp(self.__endUTCSecond - self.__timezone)
345 datetime.datetime.utcfromtimestamp(self.__endUTCSecond - self.__timezone)
339 )
346 )
340
347
341 print "[Reading] Starting process from %s to %s" %(datetime.datetime.utcfromtimestamp(startUTCSecond - self.__timezone),
348 print "[Reading] Starting process from %s to %s" %(datetime.datetime.utcfromtimestamp(startUTCSecond - self.__timezone),
342 datetime.datetime.utcfromtimestamp(endUTCSecond - self.__timezone)
349 datetime.datetime.utcfromtimestamp(endUTCSecond - self.__timezone)
343 )
350 )
344
351
345 def __reload(self):
352 def __reload(self):
346
353
347 if not self.__online:
354 if not self.__online:
348 return
355 return
349
356
350 # print
357 # print
351 # print "%s not in range [%s, %s]" %(
358 # print "%s not in range [%s, %s]" %(
352 # datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
359 # datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
353 # datetime.datetime.utcfromtimestamp(self.__startUTCSecond - self.__timezone),
360 # datetime.datetime.utcfromtimestamp(self.__startUTCSecond - self.__timezone),
354 # datetime.datetime.utcfromtimestamp(self.__endUTCSecond - self.__timezone)
361 # datetime.datetime.utcfromtimestamp(self.__endUTCSecond - self.__timezone)
355 # )
362 # )
356 print "[Reading] reloading metadata ..."
363 print "[Reading] reloading metadata ..."
357
364
358 try:
365 try:
359 self.digitalReadObj.reload(complete_update=True)
366 self.digitalReadObj.reload(complete_update=True)
360 except:
367 except:
361 self.digitalReadObj.reload()
368 self.digitalReadObj.reload()
362
369
363 start_index, end_index = self.digitalReadObj.get_bounds(self.__channelNameList[self.__channelList[0]])
370 start_index, end_index = self.digitalReadObj.get_bounds(self.__channelNameList[self.__channelList[0]])
364
371
365 if start_index > self.__startUTCSecond*self.__sample_rate:
372 if start_index > self.__startUTCSecond*self.__sample_rate:
366 self.__startUTCSecond = 1.0*start_index/self.__sample_rate
373 self.__startUTCSecond = 1.0*start_index/self.__sample_rate
367
374
368 if end_index > self.__endUTCSecond*self.__sample_rate:
375 if end_index > self.__endUTCSecond*self.__sample_rate:
369 self.__endUTCSecond = 1.0*end_index/self.__sample_rate
376 self.__endUTCSecond = 1.0*end_index/self.__sample_rate
370 print
377 print
371 print "[Reading] New timerange found [%s, %s] " %(
378 print "[Reading] New timerange found [%s, %s] " %(
372 datetime.datetime.utcfromtimestamp(self.__startUTCSecond - self.__timezone),
379 datetime.datetime.utcfromtimestamp(self.__startUTCSecond - self.__timezone),
373 datetime.datetime.utcfromtimestamp(self.__endUTCSecond - self.__timezone)
380 datetime.datetime.utcfromtimestamp(self.__endUTCSecond - self.__timezone)
374 )
381 )
375
382
376 return True
383 return True
377
384
378 return False
385 return False
379
386
380 def __readNextBlock(self, seconds=30, volt_scale = 218776):
387 def __readNextBlock(self, seconds=30, volt_scale = 218776):
381 '''
388 '''
382 '''
389 '''
383
390
384 #Set the next data
391 #Set the next data
385 self.__flagDiscontinuousBlock = False
392 self.__flagDiscontinuousBlock = False
386 self.__thisUnixSample += self.__samples_to_read
393 self.__thisUnixSample += self.__samples_to_read
387
394
388 if self.__thisUnixSample + 2*self.__samples_to_read > self.__endUTCSecond*self.__sample_rate:
395 if self.__thisUnixSample + 2*self.__samples_to_read > self.__endUTCSecond*self.__sample_rate:
389 print "[Reading] There are no more data into selected timerange"
396 print "[Reading] There are no more data into selected timerange"
390
397
391 self.__reload()
398 self.__reload()
392
399
393 if self.__thisUnixSample + 2*self.__samples_to_read > self.__endUTCSecond*self.__sample_rate:
400 if self.__thisUnixSample + 2*self.__samples_to_read > self.__endUTCSecond*self.__sample_rate:
394 self.__thisUnixSample -= self.__samples_to_read
401 self.__thisUnixSample -= self.__samples_to_read
395 return False
402 return False
396
403
397 indexChannel = 0
404 indexChannel = 0
398
405
399 dataOk = False
406 dataOk = False
400
407
401 for thisChannelName in self.__channelNameList:
408 for thisChannelName in self.__channelNameList:
402
409
403 try:
410 try:
404 result = self.digitalReadObj.read_vector_c81d(self.__thisUnixSample,
411 result = self.digitalReadObj.read_vector_c81d(self.__thisUnixSample,
405 self.__samples_to_read,
412 self.__samples_to_read,
406 thisChannelName)
413 thisChannelName)
407
414
408 except IOError, e:
415 except IOError, e:
409 #read next profile
416 #read next profile
410 self.__flagDiscontinuousBlock = True
417 self.__flagDiscontinuousBlock = True
411 print e
418 print e
412 break
419 break
413
420
414 if result.shape[0] != self.__samples_to_read:
421 if result.shape[0] != self.__samples_to_read:
415 self.__flagDiscontinuousBlock = True
422 self.__flagDiscontinuousBlock = True
416 print "[Reading] %s: Too few samples were found, just %d samples" %(datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
423 print "[Reading] %s: Too few samples were found, just %d samples" %(datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
417 result.shape[0])
424 result.shape[0])
418 break
425 break
419
426
420 self.__data_buffer[indexChannel,:] = result*volt_scale
427 self.__data_buffer[indexChannel,:] = result*volt_scale
421
428
422 indexChannel += 1
429 indexChannel += 1
423
430
424 dataOk = True
431 dataOk = True
425
432
426 self.__utctime = self.__thisUnixSample/self.__sample_rate
433 self.__utctime = self.__thisUnixSample/self.__sample_rate
427
434
428 if not dataOk:
435 if not dataOk:
429 return False
436 return False
430
437
431 print "[Reading] %s: %d samples <> %f sec" %(datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
438 print "[Reading] %s: %d samples <> %f sec" %(datetime.datetime.utcfromtimestamp(self.thisSecond - self.__timezone),
432 self.__samples_to_read,
439 self.__samples_to_read,
433 self.__timeInterval)
440 self.__timeInterval)
434
441
435 self.__bufferIndex = 0
442 self.__bufferIndex = 0
436
443
437 return True
444 return True
438
445
439 def __isBufferEmpty(self):
446 def __isBufferEmpty(self):
440
447
441 if self.__bufferIndex <= self.__samples_to_read - self.__nSamples:
448 if self.__bufferIndex <= self.__samples_to_read - self.__nSamples:
442 return False
449 return False
443
450
444 return True
451 return True
445
452
446 def getData(self, seconds=30, nTries=5):
453 def getData(self, seconds=30, nTries=5):
447
454
448 '''
455 '''
449 This method gets the data from files and put the data into the dataOut object
456 This method gets the data from files and put the data into the dataOut object
450
457
451 In addition, increase el the buffer counter in one.
458 In addition, increase el the buffer counter in one.
452
459
453 Return:
460 Return:
454 data : retorna un perfil de voltages (alturas * canales) copiados desde el
461 data : retorna un perfil de voltages (alturas * canales) copiados desde el
455 buffer. Si no hay mas archivos a leer retorna None.
462 buffer. Si no hay mas archivos a leer retorna None.
456
463
457 Affected:
464 Affected:
458 self.dataOut
465 self.dataOut
459 self.profileIndex
466 self.profileIndex
460 self.flagDiscontinuousBlock
467 self.flagDiscontinuousBlock
461 self.flagIsNewBlock
468 self.flagIsNewBlock
462 '''
469 '''
463
470
464 err_counter = 0
471 err_counter = 0
465 self.dataOut.flagNoData = True
472 self.dataOut.flagNoData = True
466
473
467 if self.__isBufferEmpty():
474 if self.__isBufferEmpty():
468
475
469 self.__flagDiscontinuousBlock = False
476 self.__flagDiscontinuousBlock = False
470
477
471 while True:
478 while True:
472 if self.__readNextBlock():
479 if self.__readNextBlock():
473 break
480 break
474
481
475 if self.__thisUnixSample > self.__endUTCSecond*self.__sample_rate:
482 if self.__thisUnixSample > self.__endUTCSecond*self.__sample_rate:
476 return False
483 return False
477
484
478 if self.__flagDiscontinuousBlock:
485 if self.__flagDiscontinuousBlock:
479 print '[Reading] discontinuous block found ... continue with the next block'
486 print '[Reading] discontinuous block found ... continue with the next block'
480 continue
487 continue
481
488
482 if not self.__online:
489 if not self.__online:
483 return False
490 return False
484
491
485 err_counter += 1
492 err_counter += 1
486 if err_counter > nTries:
493 if err_counter > nTries:
487 return False
494 return False
488
495
489 print '[Reading] waiting %d seconds to read a new block' %seconds
496 print '[Reading] waiting %d seconds to read a new block' %seconds
490 sleep(seconds)
497 sleep(seconds)
491
498
492 self.dataOut.data = self.__data_buffer[:,self.__bufferIndex:self.__bufferIndex+self.__nSamples]
499 self.dataOut.data = self.__data_buffer[:,self.__bufferIndex:self.__bufferIndex+self.__nSamples]
493 self.dataOut.utctime = (self.__thisUnixSample + self.__bufferIndex)/self.__sample_rate
500 self.dataOut.utctime = (self.__thisUnixSample + self.__bufferIndex)/self.__sample_rate
494 self.dataOut.flagNoData = False
501 self.dataOut.flagNoData = False
495 self.dataOut.flagDiscontinuousBlock = self.__flagDiscontinuousBlock
502 self.dataOut.flagDiscontinuousBlock = self.__flagDiscontinuousBlock
496
503
497 self.__bufferIndex += self.__nSamples
504 self.__bufferIndex += self.__nSamples
498 self.profileIndex += 1
505 self.profileIndex += 1
499
506
500 return True
507 return True
501
508
502 def printInfo(self):
509 def printInfo(self):
503 '''
510 '''
504 '''
511 '''
505 if self.__printInfo == False:
512 if self.__printInfo == False:
506 return
513 return
507
514
508 # self.systemHeaderObj.printInfo()
515 # self.systemHeaderObj.printInfo()
509 # self.radarControllerHeaderObj.printInfo()
516 # self.radarControllerHeaderObj.printInfo()
510
517
511 self.__printInfo = False
518 self.__printInfo = False
512
519
513 def printNumberOfBlock(self):
520 def printNumberOfBlock(self):
514 '''
521 '''
515 '''
522 '''
516
523
517 print self.profileIndex
524 print self.profileIndex
518
525
519 def run(self, **kwargs):
526 def run(self, **kwargs):
520 '''
527 '''
521 This method will be called many times so here you should put all your code
528 This method will be called many times so here you should put all your code
522 '''
529 '''
523
530
524 if not self.isConfig:
531 if not self.isConfig:
525 self.setup(**kwargs)
532 self.setup(**kwargs)
526
533
527 self.getData(seconds=self.__delay)
534 self.getData(seconds=self.__delay)
528
535
529 return
536 return
530
537
531 class USRPWriter(Operation):
538 class USRPWriter(Operation):
532 '''
539 '''
533 classdocs
540 classdocs
534 '''
541 '''
535
542
536 def __init__(self):
543 def __init__(self):
537 '''
544 '''
538 Constructor
545 Constructor
539 '''
546 '''
540 self.dataOut = None
547 self.dataOut = None
541
548
542 def setup(self, dataIn, path, blocksPerFile, set=0, ext=None):
549 def setup(self, dataIn, path, blocksPerFile, set=0, ext=None):
543 '''
550 '''
544 In this method we should set all initial parameters.
551 In this method we should set all initial parameters.
545
552
546 Input:
553 Input:
547 dataIn : Input data will also be outputa data
554 dataIn : Input data will also be outputa data
548
555
549 '''
556 '''
550 self.dataOut = dataIn
557 self.dataOut = dataIn
551
558
552
559
553
560
554
561
555
562
556 self.isConfig = True
563 self.isConfig = True
557
564
558 return
565 return
559
566
560 def run(self, dataIn, **kwargs):
567 def run(self, dataIn, **kwargs):
561 '''
568 '''
562 This method will be called many times so here you should put all your code
569 This method will be called many times so here you should put all your code
563
570
564 Inputs:
571 Inputs:
565
572
566 dataIn : object with the data
573 dataIn : object with the data
567
574
568 '''
575 '''
569
576
570 if not self.isConfig:
577 if not self.isConfig:
571 self.setup(dataIn, **kwargs)
578 self.setup(dataIn, **kwargs)
572
579
573
580
574 if __name__ == '__main__':
581 if __name__ == '__main__':
575
582
576 readObj = USRPReader()
583 readObj = USRPReader()
577
584
578 while True:
585 while True:
579 readObj.run(path='/Volumes/DATA/haystack/passive_radar/')
586 readObj.run(path='/Volumes/DATA/haystack/passive_radar/')
580 # readObj.printInfo()
587 # readObj.printInfo()
581 readObj.printNumberOfBlock()
588 readObj.printNumberOfBlock()
582
589
583 No newline at end of file
590
General Comments 0
You need to be logged in to leave comments. Login now