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