@@ -1,1332 +1,1333 | |||||
1 | ''' |
|
1 | ''' | |
2 | Updated on January , 2018, for multiprocessing purposes |
|
2 | Updated on January , 2018, for multiprocessing purposes | |
3 | Author: Sergio Cortez |
|
3 | Author: Sergio Cortez | |
4 | Created on September , 2012 |
|
4 | Created on September , 2012 | |
5 | ''' |
|
5 | ''' | |
6 | from platform import python_version |
|
6 | from platform import python_version | |
7 | import sys |
|
7 | import sys | |
8 | import ast |
|
8 | import ast | |
9 | import datetime |
|
9 | import datetime | |
10 | import traceback |
|
10 | import traceback | |
11 | import math |
|
11 | import math | |
12 | import time |
|
12 | import time | |
13 | import zmq |
|
13 | import zmq | |
14 | from multiprocessing import Process, cpu_count |
|
14 | from multiprocessing import Process, cpu_count | |
15 |
|
15 | |||
16 | from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring |
|
16 | from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring | |
17 | from xml.dom import minidom |
|
17 | from xml.dom import minidom | |
18 |
|
18 | |||
19 |
|
19 | |||
20 | from schainpy.admin import Alarm, SchainWarning |
|
20 | from schainpy.admin import Alarm, SchainWarning | |
21 |
|
21 | |||
22 | ### Temporary imports!!! |
|
22 | ### Temporary imports!!! | |
23 | # from schainpy.model import * |
|
23 | # from schainpy.model import * | |
24 | from schainpy.model.io import * |
|
24 | from schainpy.model.io import * | |
25 | from schainpy.model.graphics import * |
|
25 | from schainpy.model.graphics import * | |
26 | from schainpy.model.proc.jroproc_base import * |
|
26 | from schainpy.model.proc.jroproc_base import * | |
27 | from schainpy.model.proc.bltrproc_parameters import * |
|
27 | from schainpy.model.proc.bltrproc_parameters import * | |
28 | from schainpy.model.proc.jroproc_spectra import * |
|
28 | from schainpy.model.proc.jroproc_spectra import * | |
|
29 | from schainpy.model.proc.jroproc_voltage import * | |||
29 | from schainpy.model.proc.jroproc_parameters import * |
|
30 | from schainpy.model.proc.jroproc_parameters import * | |
30 | from schainpy.model.utils.jroutils_publish import * |
|
31 | from schainpy.model.utils.jroutils_publish import * | |
31 | from schainpy.utils import log |
|
32 | from schainpy.utils import log | |
32 | ### |
|
33 | ### | |
33 |
|
34 | |||
34 | DTYPES = { |
|
35 | DTYPES = { | |
35 | 'Voltage': '.r', |
|
36 | 'Voltage': '.r', | |
36 | 'Spectra': '.pdata' |
|
37 | 'Spectra': '.pdata' | |
37 | } |
|
38 | } | |
38 |
|
39 | |||
39 |
|
40 | |||
40 | def MPProject(project, n=cpu_count()): |
|
41 | def MPProject(project, n=cpu_count()): | |
41 | ''' |
|
42 | ''' | |
42 | Project wrapper to run schain in n processes |
|
43 | Project wrapper to run schain in n processes | |
43 | ''' |
|
44 | ''' | |
44 |
|
45 | |||
45 | rconf = project.getReadUnitObj() |
|
46 | rconf = project.getReadUnitObj() | |
46 | op = rconf.getOperationObj('run') |
|
47 | op = rconf.getOperationObj('run') | |
47 | dt1 = op.getParameterValue('startDate') |
|
48 | dt1 = op.getParameterValue('startDate') | |
48 | dt2 = op.getParameterValue('endDate') |
|
49 | dt2 = op.getParameterValue('endDate') | |
49 | tm1 = op.getParameterValue('startTime') |
|
50 | tm1 = op.getParameterValue('startTime') | |
50 | tm2 = op.getParameterValue('endTime') |
|
51 | tm2 = op.getParameterValue('endTime') | |
51 | days = (dt2 - dt1).days |
|
52 | days = (dt2 - dt1).days | |
52 |
|
53 | |||
53 | for day in range(days + 1): |
|
54 | for day in range(days + 1): | |
54 | skip = 0 |
|
55 | skip = 0 | |
55 | cursor = 0 |
|
56 | cursor = 0 | |
56 | processes = [] |
|
57 | processes = [] | |
57 | dt = dt1 + datetime.timedelta(day) |
|
58 | dt = dt1 + datetime.timedelta(day) | |
58 | dt_str = dt.strftime('%Y/%m/%d') |
|
59 | dt_str = dt.strftime('%Y/%m/%d') | |
59 | reader = JRODataReader() |
|
60 | reader = JRODataReader() | |
60 | paths, files = reader.searchFilesOffLine(path=rconf.path, |
|
61 | paths, files = reader.searchFilesOffLine(path=rconf.path, | |
61 | startDate=dt, |
|
62 | startDate=dt, | |
62 | endDate=dt, |
|
63 | endDate=dt, | |
63 | startTime=tm1, |
|
64 | startTime=tm1, | |
64 | endTime=tm2, |
|
65 | endTime=tm2, | |
65 | ext=DTYPES[rconf.datatype]) |
|
66 | ext=DTYPES[rconf.datatype]) | |
66 | nFiles = len(files) |
|
67 | nFiles = len(files) | |
67 | if nFiles == 0: |
|
68 | if nFiles == 0: | |
68 | continue |
|
69 | continue | |
69 | skip = int(math.ceil(nFiles / n)) |
|
70 | skip = int(math.ceil(nFiles / n)) | |
70 | while nFiles > cursor * skip: |
|
71 | while nFiles > cursor * skip: | |
71 | rconf.update(startDate=dt_str, endDate=dt_str, cursor=cursor, |
|
72 | rconf.update(startDate=dt_str, endDate=dt_str, cursor=cursor, | |
72 | skip=skip) |
|
73 | skip=skip) | |
73 | p = project.clone() |
|
74 | p = project.clone() | |
74 | p.start() |
|
75 | p.start() | |
75 | processes.append(p) |
|
76 | processes.append(p) | |
76 | cursor += 1 |
|
77 | cursor += 1 | |
77 |
|
78 | |||
78 | def beforeExit(exctype, value, trace): |
|
79 | def beforeExit(exctype, value, trace): | |
79 | for process in processes: |
|
80 | for process in processes: | |
80 | process.terminate() |
|
81 | process.terminate() | |
81 | process.join() |
|
82 | process.join() | |
82 | print(traceback.print_tb(trace)) |
|
83 | print(traceback.print_tb(trace)) | |
83 |
|
84 | |||
84 | sys.excepthook = beforeExit |
|
85 | sys.excepthook = beforeExit | |
85 |
|
86 | |||
86 | for process in processes: |
|
87 | for process in processes: | |
87 | process.join() |
|
88 | process.join() | |
88 | process.terminate() |
|
89 | process.terminate() | |
89 |
|
90 | |||
90 | time.sleep(3) |
|
91 | time.sleep(3) | |
91 |
|
92 | |||
92 | class ParameterConf(): |
|
93 | class ParameterConf(): | |
93 |
|
94 | |||
94 | id = None |
|
95 | id = None | |
95 | name = None |
|
96 | name = None | |
96 | value = None |
|
97 | value = None | |
97 | format = None |
|
98 | format = None | |
98 |
|
99 | |||
99 | __formated_value = None |
|
100 | __formated_value = None | |
100 |
|
101 | |||
101 | ELEMENTNAME = 'Parameter' |
|
102 | ELEMENTNAME = 'Parameter' | |
102 |
|
103 | |||
103 | def __init__(self): |
|
104 | def __init__(self): | |
104 |
|
105 | |||
105 | self.format = 'str' |
|
106 | self.format = 'str' | |
106 |
|
107 | |||
107 | def getElementName(self): |
|
108 | def getElementName(self): | |
108 |
|
109 | |||
109 | return self.ELEMENTNAME |
|
110 | return self.ELEMENTNAME | |
110 |
|
111 | |||
111 | def getValue(self): |
|
112 | def getValue(self): | |
112 |
|
113 | |||
113 | value = self.value |
|
114 | value = self.value | |
114 | format = self.format |
|
115 | format = self.format | |
115 |
|
116 | |||
116 | if self.__formated_value != None: |
|
117 | if self.__formated_value != None: | |
117 |
|
118 | |||
118 | return self.__formated_value |
|
119 | return self.__formated_value | |
119 |
|
120 | |||
120 | if format == 'obj': |
|
121 | if format == 'obj': | |
121 | return value |
|
122 | return value | |
122 |
|
123 | |||
123 | if format == 'str': |
|
124 | if format == 'str': | |
124 | self.__formated_value = str(value) |
|
125 | self.__formated_value = str(value) | |
125 | return self.__formated_value |
|
126 | return self.__formated_value | |
126 |
|
127 | |||
127 | if value == '': |
|
128 | if value == '': | |
128 | raise ValueError('%s: This parameter value is empty' % self.name) |
|
129 | raise ValueError('%s: This parameter value is empty' % self.name) | |
129 |
|
130 | |||
130 | if format == 'list': |
|
131 | if format == 'list': | |
131 | strList = value.split(',') |
|
132 | strList = value.split(',') | |
132 |
|
133 | |||
133 | self.__formated_value = strList |
|
134 | self.__formated_value = strList | |
134 |
|
135 | |||
135 | return self.__formated_value |
|
136 | return self.__formated_value | |
136 |
|
137 | |||
137 | if format == 'intlist': |
|
138 | if format == 'intlist': | |
138 | ''' |
|
139 | ''' | |
139 | Example: |
|
140 | Example: | |
140 | value = (0,1,2) |
|
141 | value = (0,1,2) | |
141 | ''' |
|
142 | ''' | |
142 |
|
143 | |||
143 | new_value = ast.literal_eval(value) |
|
144 | new_value = ast.literal_eval(value) | |
144 |
|
145 | |||
145 | if type(new_value) not in (tuple, list): |
|
146 | if type(new_value) not in (tuple, list): | |
146 | new_value = [int(new_value)] |
|
147 | new_value = [int(new_value)] | |
147 |
|
148 | |||
148 | self.__formated_value = new_value |
|
149 | self.__formated_value = new_value | |
149 |
|
150 | |||
150 | return self.__formated_value |
|
151 | return self.__formated_value | |
151 |
|
152 | |||
152 | if format == 'floatlist': |
|
153 | if format == 'floatlist': | |
153 | ''' |
|
154 | ''' | |
154 | Example: |
|
155 | Example: | |
155 | value = (0.5, 1.4, 2.7) |
|
156 | value = (0.5, 1.4, 2.7) | |
156 | ''' |
|
157 | ''' | |
157 |
|
158 | |||
158 | new_value = ast.literal_eval(value) |
|
159 | new_value = ast.literal_eval(value) | |
159 |
|
160 | |||
160 | if type(new_value) not in (tuple, list): |
|
161 | if type(new_value) not in (tuple, list): | |
161 | new_value = [float(new_value)] |
|
162 | new_value = [float(new_value)] | |
162 |
|
163 | |||
163 | self.__formated_value = new_value |
|
164 | self.__formated_value = new_value | |
164 |
|
165 | |||
165 | return self.__formated_value |
|
166 | return self.__formated_value | |
166 |
|
167 | |||
167 | if format == 'date': |
|
168 | if format == 'date': | |
168 | strList = value.split('/') |
|
169 | strList = value.split('/') | |
169 | intList = [int(x) for x in strList] |
|
170 | intList = [int(x) for x in strList] | |
170 | date = datetime.date(intList[0], intList[1], intList[2]) |
|
171 | date = datetime.date(intList[0], intList[1], intList[2]) | |
171 |
|
172 | |||
172 | self.__formated_value = date |
|
173 | self.__formated_value = date | |
173 |
|
174 | |||
174 | return self.__formated_value |
|
175 | return self.__formated_value | |
175 |
|
176 | |||
176 | if format == 'time': |
|
177 | if format == 'time': | |
177 | strList = value.split(':') |
|
178 | strList = value.split(':') | |
178 | intList = [int(x) for x in strList] |
|
179 | intList = [int(x) for x in strList] | |
179 | time = datetime.time(intList[0], intList[1], intList[2]) |
|
180 | time = datetime.time(intList[0], intList[1], intList[2]) | |
180 |
|
181 | |||
181 | self.__formated_value = time |
|
182 | self.__formated_value = time | |
182 |
|
183 | |||
183 | return self.__formated_value |
|
184 | return self.__formated_value | |
184 |
|
185 | |||
185 | if format == 'pairslist': |
|
186 | if format == 'pairslist': | |
186 | ''' |
|
187 | ''' | |
187 | Example: |
|
188 | Example: | |
188 | value = (0,1),(1,2) |
|
189 | value = (0,1),(1,2) | |
189 | ''' |
|
190 | ''' | |
190 |
|
191 | |||
191 | new_value = ast.literal_eval(value) |
|
192 | new_value = ast.literal_eval(value) | |
192 |
|
193 | |||
193 | if type(new_value) not in (tuple, list): |
|
194 | if type(new_value) not in (tuple, list): | |
194 | raise ValueError('%s has to be a tuple or list of pairs' % value) |
|
195 | raise ValueError('%s has to be a tuple or list of pairs' % value) | |
195 |
|
196 | |||
196 | if type(new_value[0]) not in (tuple, list): |
|
197 | if type(new_value[0]) not in (tuple, list): | |
197 | if len(new_value) != 2: |
|
198 | if len(new_value) != 2: | |
198 | raise ValueError('%s has to be a tuple or list of pairs' % value) |
|
199 | raise ValueError('%s has to be a tuple or list of pairs' % value) | |
199 | new_value = [new_value] |
|
200 | new_value = [new_value] | |
200 |
|
201 | |||
201 | for thisPair in new_value: |
|
202 | for thisPair in new_value: | |
202 | if len(thisPair) != 2: |
|
203 | if len(thisPair) != 2: | |
203 | raise ValueError('%s has to be a tuple or list of pairs' % value) |
|
204 | raise ValueError('%s has to be a tuple or list of pairs' % value) | |
204 |
|
205 | |||
205 | self.__formated_value = new_value |
|
206 | self.__formated_value = new_value | |
206 |
|
207 | |||
207 | return self.__formated_value |
|
208 | return self.__formated_value | |
208 |
|
209 | |||
209 | if format == 'multilist': |
|
210 | if format == 'multilist': | |
210 | ''' |
|
211 | ''' | |
211 | Example: |
|
212 | Example: | |
212 | value = (0,1,2),(3,4,5) |
|
213 | value = (0,1,2),(3,4,5) | |
213 | ''' |
|
214 | ''' | |
214 | multiList = ast.literal_eval(value) |
|
215 | multiList = ast.literal_eval(value) | |
215 |
|
216 | |||
216 | if type(multiList[0]) == int: |
|
217 | if type(multiList[0]) == int: | |
217 | multiList = ast.literal_eval('(' + value + ')') |
|
218 | multiList = ast.literal_eval('(' + value + ')') | |
218 |
|
219 | |||
219 | self.__formated_value = multiList |
|
220 | self.__formated_value = multiList | |
220 |
|
221 | |||
221 | return self.__formated_value |
|
222 | return self.__formated_value | |
222 |
|
223 | |||
223 | if format == 'bool': |
|
224 | if format == 'bool': | |
224 | value = int(value) |
|
225 | value = int(value) | |
225 |
|
226 | |||
226 | if format == 'int': |
|
227 | if format == 'int': | |
227 | value = float(value) |
|
228 | value = float(value) | |
228 |
|
229 | |||
229 | format_func = eval(format) |
|
230 | format_func = eval(format) | |
230 |
|
231 | |||
231 | self.__formated_value = format_func(value) |
|
232 | self.__formated_value = format_func(value) | |
232 |
|
233 | |||
233 | return self.__formated_value |
|
234 | return self.__formated_value | |
234 |
|
235 | |||
235 | def updateId(self, new_id): |
|
236 | def updateId(self, new_id): | |
236 |
|
237 | |||
237 | self.id = str(new_id) |
|
238 | self.id = str(new_id) | |
238 |
|
239 | |||
239 | def setup(self, id, name, value, format='str'): |
|
240 | def setup(self, id, name, value, format='str'): | |
240 | self.id = str(id) |
|
241 | self.id = str(id) | |
241 | self.name = name |
|
242 | self.name = name | |
242 | if format == 'obj': |
|
243 | if format == 'obj': | |
243 | self.value = value |
|
244 | self.value = value | |
244 | else: |
|
245 | else: | |
245 | self.value = str(value) |
|
246 | self.value = str(value) | |
246 | self.format = str.lower(format) |
|
247 | self.format = str.lower(format) | |
247 |
|
248 | |||
248 | self.getValue() |
|
249 | self.getValue() | |
249 |
|
250 | |||
250 | return 1 |
|
251 | return 1 | |
251 |
|
252 | |||
252 | def update(self, name, value, format='str'): |
|
253 | def update(self, name, value, format='str'): | |
253 |
|
254 | |||
254 | self.name = name |
|
255 | self.name = name | |
255 | self.value = str(value) |
|
256 | self.value = str(value) | |
256 | self.format = format |
|
257 | self.format = format | |
257 |
|
258 | |||
258 | def makeXml(self, opElement): |
|
259 | def makeXml(self, opElement): | |
259 | if self.name not in ('queue',): |
|
260 | if self.name not in ('queue',): | |
260 | parmElement = SubElement(opElement, self.ELEMENTNAME) |
|
261 | parmElement = SubElement(opElement, self.ELEMENTNAME) | |
261 | parmElement.set('id', str(self.id)) |
|
262 | parmElement.set('id', str(self.id)) | |
262 | parmElement.set('name', self.name) |
|
263 | parmElement.set('name', self.name) | |
263 | parmElement.set('value', self.value) |
|
264 | parmElement.set('value', self.value) | |
264 | parmElement.set('format', self.format) |
|
265 | parmElement.set('format', self.format) | |
265 |
|
266 | |||
266 | def readXml(self, parmElement): |
|
267 | def readXml(self, parmElement): | |
267 |
|
268 | |||
268 | self.id = parmElement.get('id') |
|
269 | self.id = parmElement.get('id') | |
269 | self.name = parmElement.get('name') |
|
270 | self.name = parmElement.get('name') | |
270 | self.value = parmElement.get('value') |
|
271 | self.value = parmElement.get('value') | |
271 | self.format = str.lower(parmElement.get('format')) |
|
272 | self.format = str.lower(parmElement.get('format')) | |
272 |
|
273 | |||
273 | # Compatible with old signal chain version |
|
274 | # Compatible with old signal chain version | |
274 | if self.format == 'int' and self.name == 'idfigure': |
|
275 | if self.format == 'int' and self.name == 'idfigure': | |
275 | self.name = 'id' |
|
276 | self.name = 'id' | |
276 |
|
277 | |||
277 | def printattr(self): |
|
278 | def printattr(self): | |
278 |
|
279 | |||
279 | print('Parameter[%s]: name = %s, value = %s, format = %s' % (self.id, self.name, self.value, self.format)) |
|
280 | print('Parameter[%s]: name = %s, value = %s, format = %s' % (self.id, self.name, self.value, self.format)) | |
280 |
|
281 | |||
281 | class OperationConf(): |
|
282 | class OperationConf(): | |
282 |
|
283 | |||
283 | id = None |
|
284 | id = None | |
284 | name = None |
|
285 | name = None | |
285 | priority = None |
|
286 | priority = None | |
286 | type = None |
|
287 | type = None | |
287 |
|
288 | |||
288 | parmConfObjList = [] |
|
289 | parmConfObjList = [] | |
289 |
|
290 | |||
290 | ELEMENTNAME = 'Operation' |
|
291 | ELEMENTNAME = 'Operation' | |
291 |
|
292 | |||
292 | def __init__(self): |
|
293 | def __init__(self): | |
293 |
|
294 | |||
294 | self.id = '0' |
|
295 | self.id = '0' | |
295 | self.name = None |
|
296 | self.name = None | |
296 | self.priority = None |
|
297 | self.priority = None | |
297 | self.topic = None |
|
298 | self.topic = None | |
298 |
|
299 | |||
299 | def __getNewId(self): |
|
300 | def __getNewId(self): | |
300 |
|
301 | |||
301 | return int(self.id) * 10 + len(self.parmConfObjList) + 1 |
|
302 | return int(self.id) * 10 + len(self.parmConfObjList) + 1 | |
302 |
|
303 | |||
303 | def getId(self): |
|
304 | def getId(self): | |
304 | return self.id |
|
305 | return self.id | |
305 |
|
306 | |||
306 | def updateId(self, new_id): |
|
307 | def updateId(self, new_id): | |
307 |
|
308 | |||
308 | self.id = str(new_id) |
|
309 | self.id = str(new_id) | |
309 |
|
310 | |||
310 | n = 1 |
|
311 | n = 1 | |
311 | for parmObj in self.parmConfObjList: |
|
312 | for parmObj in self.parmConfObjList: | |
312 |
|
313 | |||
313 | idParm = str(int(new_id) * 10 + n) |
|
314 | idParm = str(int(new_id) * 10 + n) | |
314 | parmObj.updateId(idParm) |
|
315 | parmObj.updateId(idParm) | |
315 |
|
316 | |||
316 | n += 1 |
|
317 | n += 1 | |
317 |
|
318 | |||
318 | def getElementName(self): |
|
319 | def getElementName(self): | |
319 |
|
320 | |||
320 | return self.ELEMENTNAME |
|
321 | return self.ELEMENTNAME | |
321 |
|
322 | |||
322 | def getParameterObjList(self): |
|
323 | def getParameterObjList(self): | |
323 |
|
324 | |||
324 | return self.parmConfObjList |
|
325 | return self.parmConfObjList | |
325 |
|
326 | |||
326 | def getParameterObj(self, parameterName): |
|
327 | def getParameterObj(self, parameterName): | |
327 |
|
328 | |||
328 | for parmConfObj in self.parmConfObjList: |
|
329 | for parmConfObj in self.parmConfObjList: | |
329 |
|
330 | |||
330 | if parmConfObj.name != parameterName: |
|
331 | if parmConfObj.name != parameterName: | |
331 | continue |
|
332 | continue | |
332 |
|
333 | |||
333 | return parmConfObj |
|
334 | return parmConfObj | |
334 |
|
335 | |||
335 | return None |
|
336 | return None | |
336 |
|
337 | |||
337 | def getParameterObjfromValue(self, parameterValue): |
|
338 | def getParameterObjfromValue(self, parameterValue): | |
338 |
|
339 | |||
339 | for parmConfObj in self.parmConfObjList: |
|
340 | for parmConfObj in self.parmConfObjList: | |
340 |
|
341 | |||
341 | if parmConfObj.getValue() != parameterValue: |
|
342 | if parmConfObj.getValue() != parameterValue: | |
342 | continue |
|
343 | continue | |
343 |
|
344 | |||
344 | return parmConfObj.getValue() |
|
345 | return parmConfObj.getValue() | |
345 |
|
346 | |||
346 | return None |
|
347 | return None | |
347 |
|
348 | |||
348 | def getParameterValue(self, parameterName): |
|
349 | def getParameterValue(self, parameterName): | |
349 |
|
350 | |||
350 | parameterObj = self.getParameterObj(parameterName) |
|
351 | parameterObj = self.getParameterObj(parameterName) | |
351 |
|
352 | |||
352 | # if not parameterObj: |
|
353 | # if not parameterObj: | |
353 | # return None |
|
354 | # return None | |
354 |
|
355 | |||
355 | value = parameterObj.getValue() |
|
356 | value = parameterObj.getValue() | |
356 |
|
357 | |||
357 | return value |
|
358 | return value | |
358 |
|
359 | |||
359 | def getKwargs(self): |
|
360 | def getKwargs(self): | |
360 |
|
361 | |||
361 | kwargs = {} |
|
362 | kwargs = {} | |
362 |
|
363 | |||
363 | for parmConfObj in self.parmConfObjList: |
|
364 | for parmConfObj in self.parmConfObjList: | |
364 | if self.name == 'run' and parmConfObj.name == 'datatype': |
|
365 | if self.name == 'run' and parmConfObj.name == 'datatype': | |
365 | continue |
|
366 | continue | |
366 |
|
367 | |||
367 | kwargs[parmConfObj.name] = parmConfObj.getValue() |
|
368 | kwargs[parmConfObj.name] = parmConfObj.getValue() | |
368 |
|
369 | |||
369 | return kwargs |
|
370 | return kwargs | |
370 |
|
371 | |||
371 | def setup(self, id, name, priority, type): |
|
372 | def setup(self, id, name, priority, type): | |
372 |
|
373 | |||
373 | self.id = str(id) |
|
374 | self.id = str(id) | |
374 | self.name = name |
|
375 | self.name = name | |
375 | self.type = type |
|
376 | self.type = type | |
376 | self.priority = priority |
|
377 | self.priority = priority | |
377 | self.parmConfObjList = [] |
|
378 | self.parmConfObjList = [] | |
378 |
|
379 | |||
379 | def removeParameters(self): |
|
380 | def removeParameters(self): | |
380 |
|
381 | |||
381 | for obj in self.parmConfObjList: |
|
382 | for obj in self.parmConfObjList: | |
382 | del obj |
|
383 | del obj | |
383 |
|
384 | |||
384 | self.parmConfObjList = [] |
|
385 | self.parmConfObjList = [] | |
385 |
|
386 | |||
386 | def addParameter(self, name, value, format='str'): |
|
387 | def addParameter(self, name, value, format='str'): | |
387 |
|
388 | |||
388 | if value is None: |
|
389 | if value is None: | |
389 | return None |
|
390 | return None | |
390 | id = self.__getNewId() |
|
391 | id = self.__getNewId() | |
391 |
|
392 | |||
392 | parmConfObj = ParameterConf() |
|
393 | parmConfObj = ParameterConf() | |
393 | if not parmConfObj.setup(id, name, value, format): |
|
394 | if not parmConfObj.setup(id, name, value, format): | |
394 | return None |
|
395 | return None | |
395 |
|
396 | |||
396 | self.parmConfObjList.append(parmConfObj) |
|
397 | self.parmConfObjList.append(parmConfObj) | |
397 |
|
398 | |||
398 | return parmConfObj |
|
399 | return parmConfObj | |
399 |
|
400 | |||
400 | def changeParameter(self, name, value, format='str'): |
|
401 | def changeParameter(self, name, value, format='str'): | |
401 |
|
402 | |||
402 | parmConfObj = self.getParameterObj(name) |
|
403 | parmConfObj = self.getParameterObj(name) | |
403 | parmConfObj.update(name, value, format) |
|
404 | parmConfObj.update(name, value, format) | |
404 |
|
405 | |||
405 | return parmConfObj |
|
406 | return parmConfObj | |
406 |
|
407 | |||
407 | def makeXml(self, procUnitElement): |
|
408 | def makeXml(self, procUnitElement): | |
408 |
|
409 | |||
409 | opElement = SubElement(procUnitElement, self.ELEMENTNAME) |
|
410 | opElement = SubElement(procUnitElement, self.ELEMENTNAME) | |
410 | opElement.set('id', str(self.id)) |
|
411 | opElement.set('id', str(self.id)) | |
411 | opElement.set('name', self.name) |
|
412 | opElement.set('name', self.name) | |
412 | opElement.set('type', self.type) |
|
413 | opElement.set('type', self.type) | |
413 | opElement.set('priority', str(self.priority)) |
|
414 | opElement.set('priority', str(self.priority)) | |
414 |
|
415 | |||
415 | for parmConfObj in self.parmConfObjList: |
|
416 | for parmConfObj in self.parmConfObjList: | |
416 | parmConfObj.makeXml(opElement) |
|
417 | parmConfObj.makeXml(opElement) | |
417 |
|
418 | |||
418 | def readXml(self, opElement): |
|
419 | def readXml(self, opElement): | |
419 |
|
420 | |||
420 | self.id = opElement.get('id') |
|
421 | self.id = opElement.get('id') | |
421 | self.name = opElement.get('name') |
|
422 | self.name = opElement.get('name') | |
422 | self.type = opElement.get('type') |
|
423 | self.type = opElement.get('type') | |
423 | self.priority = opElement.get('priority') |
|
424 | self.priority = opElement.get('priority') | |
424 |
|
425 | |||
425 | # Compatible with old signal chain version |
|
426 | # Compatible with old signal chain version | |
426 | # Use of 'run' method instead 'init' |
|
427 | # Use of 'run' method instead 'init' | |
427 | if self.type == 'self' and self.name == 'init': |
|
428 | if self.type == 'self' and self.name == 'init': | |
428 | self.name = 'run' |
|
429 | self.name = 'run' | |
429 |
|
430 | |||
430 | self.parmConfObjList = [] |
|
431 | self.parmConfObjList = [] | |
431 |
|
432 | |||
432 | parmElementList = opElement.iter(ParameterConf().getElementName()) |
|
433 | parmElementList = opElement.iter(ParameterConf().getElementName()) | |
433 |
|
434 | |||
434 | for parmElement in parmElementList: |
|
435 | for parmElement in parmElementList: | |
435 | parmConfObj = ParameterConf() |
|
436 | parmConfObj = ParameterConf() | |
436 | parmConfObj.readXml(parmElement) |
|
437 | parmConfObj.readXml(parmElement) | |
437 |
|
438 | |||
438 | # Compatible with old signal chain version |
|
439 | # Compatible with old signal chain version | |
439 | # If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER |
|
440 | # If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER | |
440 | if self.type != 'self' and self.name == 'Plot': |
|
441 | if self.type != 'self' and self.name == 'Plot': | |
441 | if parmConfObj.format == 'str' and parmConfObj.name == 'type': |
|
442 | if parmConfObj.format == 'str' and parmConfObj.name == 'type': | |
442 | self.name = parmConfObj.value |
|
443 | self.name = parmConfObj.value | |
443 | continue |
|
444 | continue | |
444 |
|
445 | |||
445 | self.parmConfObjList.append(parmConfObj) |
|
446 | self.parmConfObjList.append(parmConfObj) | |
446 |
|
447 | |||
447 | def printattr(self): |
|
448 | def printattr(self): | |
448 |
|
449 | |||
449 | print('%s[%s]: name = %s, type = %s, priority = %s' % (self.ELEMENTNAME, |
|
450 | print('%s[%s]: name = %s, type = %s, priority = %s' % (self.ELEMENTNAME, | |
450 | self.id, |
|
451 | self.id, | |
451 | self.name, |
|
452 | self.name, | |
452 | self.type, |
|
453 | self.type, | |
453 | self.priority)) |
|
454 | self.priority)) | |
454 |
|
455 | |||
455 | for parmConfObj in self.parmConfObjList: |
|
456 | for parmConfObj in self.parmConfObjList: | |
456 | parmConfObj.printattr() |
|
457 | parmConfObj.printattr() | |
457 |
|
458 | |||
458 | def createObject(self): |
|
459 | def createObject(self): | |
459 |
|
460 | |||
460 | className = eval(self.name) |
|
461 | className = eval(self.name) | |
461 | kwargs = self.getKwargs() |
|
462 | kwargs = self.getKwargs() | |
462 |
|
463 | |||
463 | opObj = className(self.id, **kwargs) |
|
464 | opObj = className(self.id, **kwargs) | |
464 |
|
465 | |||
465 | opObj.start() |
|
466 | opObj.start() | |
466 |
|
467 | |||
467 | print(' Operation created') |
|
468 | print(' Operation created') | |
468 |
|
469 | |||
469 | return opObj |
|
470 | return opObj | |
470 |
|
471 | |||
471 | class ProcUnitConf(): |
|
472 | class ProcUnitConf(): | |
472 |
|
473 | |||
473 | id = None |
|
474 | id = None | |
474 | name = None |
|
475 | name = None | |
475 | datatype = None |
|
476 | datatype = None | |
476 | inputId = None |
|
477 | inputId = None | |
477 | parentId = None |
|
478 | parentId = None | |
478 |
|
479 | |||
479 | opConfObjList = [] |
|
480 | opConfObjList = [] | |
480 |
|
481 | |||
481 | procUnitObj = None |
|
482 | procUnitObj = None | |
482 | opObjList = [] |
|
483 | opObjList = [] | |
483 |
|
484 | |||
484 | ELEMENTNAME = 'ProcUnit' |
|
485 | ELEMENTNAME = 'ProcUnit' | |
485 |
|
486 | |||
486 | def __init__(self): |
|
487 | def __init__(self): | |
487 |
|
488 | |||
488 | self.id = None |
|
489 | self.id = None | |
489 | self.datatype = None |
|
490 | self.datatype = None | |
490 | self.name = None |
|
491 | self.name = None | |
491 | self.inputId = None |
|
492 | self.inputId = None | |
492 |
|
493 | |||
493 | self.opConfObjList = [] |
|
494 | self.opConfObjList = [] | |
494 |
|
495 | |||
495 | self.procUnitObj = None |
|
496 | self.procUnitObj = None | |
496 | self.opObjDict = {} |
|
497 | self.opObjDict = {} | |
497 |
|
498 | |||
498 | def __getPriority(self): |
|
499 | def __getPriority(self): | |
499 |
|
500 | |||
500 | return len(self.opConfObjList) + 1 |
|
501 | return len(self.opConfObjList) + 1 | |
501 |
|
502 | |||
502 | def __getNewId(self): |
|
503 | def __getNewId(self): | |
503 |
|
504 | |||
504 | return int(self.id) * 10 + len(self.opConfObjList) + 1 |
|
505 | return int(self.id) * 10 + len(self.opConfObjList) + 1 | |
505 |
|
506 | |||
506 | def getElementName(self): |
|
507 | def getElementName(self): | |
507 |
|
508 | |||
508 | return self.ELEMENTNAME |
|
509 | return self.ELEMENTNAME | |
509 |
|
510 | |||
510 | def getId(self): |
|
511 | def getId(self): | |
511 |
|
512 | |||
512 | return self.id |
|
513 | return self.id | |
513 |
|
514 | |||
514 | def updateId(self, new_id, parentId=parentId): |
|
515 | def updateId(self, new_id, parentId=parentId): | |
515 | ''' |
|
516 | ''' | |
516 | new_id = int(parentId) * 10 + (int(self.id) % 10) |
|
517 | new_id = int(parentId) * 10 + (int(self.id) % 10) | |
517 | new_inputId = int(parentId) * 10 + (int(self.inputId) % 10) |
|
518 | new_inputId = int(parentId) * 10 + (int(self.inputId) % 10) | |
518 |
|
519 | |||
519 | # If this proc unit has not inputs |
|
520 | # If this proc unit has not inputs | |
520 | #if self.inputId == '0': |
|
521 | #if self.inputId == '0': | |
521 | #new_inputId = 0 |
|
522 | #new_inputId = 0 | |
522 |
|
523 | |||
523 | n = 1 |
|
524 | n = 1 | |
524 | for opConfObj in self.opConfObjList: |
|
525 | for opConfObj in self.opConfObjList: | |
525 |
|
526 | |||
526 | idOp = str(int(new_id) * 10 + n) |
|
527 | idOp = str(int(new_id) * 10 + n) | |
527 | opConfObj.updateId(idOp) |
|
528 | opConfObj.updateId(idOp) | |
528 |
|
529 | |||
529 | n += 1 |
|
530 | n += 1 | |
530 |
|
531 | |||
531 | self.parentId = str(parentId) |
|
532 | self.parentId = str(parentId) | |
532 | self.id = str(new_id) |
|
533 | self.id = str(new_id) | |
533 | #self.inputId = str(new_inputId) |
|
534 | #self.inputId = str(new_inputId) | |
534 | ''' |
|
535 | ''' | |
535 | n = 1 |
|
536 | n = 1 | |
536 | def getInputId(self): |
|
537 | def getInputId(self): | |
537 |
|
538 | |||
538 | return self.inputId |
|
539 | return self.inputId | |
539 |
|
540 | |||
540 | def getOperationObjList(self): |
|
541 | def getOperationObjList(self): | |
541 |
|
542 | |||
542 | return self.opConfObjList |
|
543 | return self.opConfObjList | |
543 |
|
544 | |||
544 | def getOperationObj(self, name=None): |
|
545 | def getOperationObj(self, name=None): | |
545 |
|
546 | |||
546 | for opConfObj in self.opConfObjList: |
|
547 | for opConfObj in self.opConfObjList: | |
547 |
|
548 | |||
548 | if opConfObj.name != name: |
|
549 | if opConfObj.name != name: | |
549 | continue |
|
550 | continue | |
550 |
|
551 | |||
551 | return opConfObj |
|
552 | return opConfObj | |
552 |
|
553 | |||
553 | return None |
|
554 | return None | |
554 |
|
555 | |||
555 | def getOpObjfromParamValue(self, value=None): |
|
556 | def getOpObjfromParamValue(self, value=None): | |
556 |
|
557 | |||
557 | for opConfObj in self.opConfObjList: |
|
558 | for opConfObj in self.opConfObjList: | |
558 | if opConfObj.getParameterObjfromValue(parameterValue=value) != value: |
|
559 | if opConfObj.getParameterObjfromValue(parameterValue=value) != value: | |
559 | continue |
|
560 | continue | |
560 | return opConfObj |
|
561 | return opConfObj | |
561 | return None |
|
562 | return None | |
562 |
|
563 | |||
563 | def getProcUnitObj(self): |
|
564 | def getProcUnitObj(self): | |
564 |
|
565 | |||
565 | return self.procUnitObj |
|
566 | return self.procUnitObj | |
566 |
|
567 | |||
567 | def setup(self, id, name, datatype, inputId, parentId=None): |
|
568 | def setup(self, id, name, datatype, inputId, parentId=None): | |
568 | ''' |
|
569 | ''' | |
569 | id sera el topico a publicar |
|
570 | id sera el topico a publicar | |
570 | inputId sera el topico a subscribirse |
|
571 | inputId sera el topico a subscribirse | |
571 | ''' |
|
572 | ''' | |
572 |
|
573 | |||
573 | # Compatible with old signal chain version |
|
574 | # Compatible with old signal chain version | |
574 | if datatype == None and name == None: |
|
575 | if datatype == None and name == None: | |
575 | raise ValueError('datatype or name should be defined') |
|
576 | raise ValueError('datatype or name should be defined') | |
576 |
|
577 | |||
577 | #Definir una condicion para inputId cuando sea 0 |
|
578 | #Definir una condicion para inputId cuando sea 0 | |
578 |
|
579 | |||
579 | if name == None: |
|
580 | if name == None: | |
580 | if 'Proc' in datatype: |
|
581 | if 'Proc' in datatype: | |
581 | name = datatype |
|
582 | name = datatype | |
582 | else: |
|
583 | else: | |
583 | name = '%sProc' % (datatype) |
|
584 | name = '%sProc' % (datatype) | |
584 |
|
585 | |||
585 | if datatype == None: |
|
586 | if datatype == None: | |
586 | datatype = name.replace('Proc', '') |
|
587 | datatype = name.replace('Proc', '') | |
587 |
|
588 | |||
588 | self.id = str(id) |
|
589 | self.id = str(id) | |
589 | self.name = name |
|
590 | self.name = name | |
590 | self.datatype = datatype |
|
591 | self.datatype = datatype | |
591 | self.inputId = inputId |
|
592 | self.inputId = inputId | |
592 | self.parentId = parentId |
|
593 | self.parentId = parentId | |
593 | self.opConfObjList = [] |
|
594 | self.opConfObjList = [] | |
594 |
|
595 | |||
595 | self.addOperation(name='run', optype='self') |
|
596 | self.addOperation(name='run', optype='self') | |
596 |
|
597 | |||
597 | def removeOperations(self): |
|
598 | def removeOperations(self): | |
598 |
|
599 | |||
599 | for obj in self.opConfObjList: |
|
600 | for obj in self.opConfObjList: | |
600 | del obj |
|
601 | del obj | |
601 |
|
602 | |||
602 | self.opConfObjList = [] |
|
603 | self.opConfObjList = [] | |
603 | self.addOperation(name='run') |
|
604 | self.addOperation(name='run') | |
604 |
|
605 | |||
605 | def addParameter(self, **kwargs): |
|
606 | def addParameter(self, **kwargs): | |
606 | ''' |
|
607 | ''' | |
607 | Add parameters to 'run' operation |
|
608 | Add parameters to 'run' operation | |
608 | ''' |
|
609 | ''' | |
609 | opObj = self.opConfObjList[0] |
|
610 | opObj = self.opConfObjList[0] | |
610 |
|
611 | |||
611 | opObj.addParameter(**kwargs) |
|
612 | opObj.addParameter(**kwargs) | |
612 |
|
613 | |||
613 | return opObj |
|
614 | return opObj | |
614 |
|
615 | |||
615 | def addOperation(self, name, optype = 'self'): |
|
616 | def addOperation(self, name, optype = 'self'): | |
616 | ''' |
|
617 | ''' | |
617 | Actualizacion - > proceso comunicacion |
|
618 | Actualizacion - > proceso comunicacion | |
618 | En el caso de optype='self', elminar. DEfinir comuncacion IPC -> Topic |
|
619 | En el caso de optype='self', elminar. DEfinir comuncacion IPC -> Topic | |
619 | definir el tipoc de socket o comunicacion ipc++ |
|
620 | definir el tipoc de socket o comunicacion ipc++ | |
620 |
|
621 | |||
621 | ''' |
|
622 | ''' | |
622 |
|
623 | |||
623 | id = self.__getNewId() |
|
624 | id = self.__getNewId() | |
624 | priority = self.__getPriority() # Sin mucho sentido, pero puede usarse |
|
625 | priority = self.__getPriority() # Sin mucho sentido, pero puede usarse | |
625 |
|
626 | |||
626 | opConfObj = OperationConf() |
|
627 | opConfObj = OperationConf() | |
627 | opConfObj.setup(id, name=name, priority=priority, type=optype) |
|
628 | opConfObj.setup(id, name=name, priority=priority, type=optype) | |
628 |
|
629 | |||
629 | self.opConfObjList.append(opConfObj) |
|
630 | self.opConfObjList.append(opConfObj) | |
630 |
|
631 | |||
631 | return opConfObj |
|
632 | return opConfObj | |
632 |
|
633 | |||
633 | def makeXml(self, projectElement): |
|
634 | def makeXml(self, projectElement): | |
634 |
|
635 | |||
635 | procUnitElement = SubElement(projectElement, self.ELEMENTNAME) |
|
636 | procUnitElement = SubElement(projectElement, self.ELEMENTNAME) | |
636 | procUnitElement.set('id', str(self.id)) |
|
637 | procUnitElement.set('id', str(self.id)) | |
637 | procUnitElement.set('name', self.name) |
|
638 | procUnitElement.set('name', self.name) | |
638 | procUnitElement.set('datatype', self.datatype) |
|
639 | procUnitElement.set('datatype', self.datatype) | |
639 | procUnitElement.set('inputId', str(self.inputId)) |
|
640 | procUnitElement.set('inputId', str(self.inputId)) | |
640 |
|
641 | |||
641 | for opConfObj in self.opConfObjList: |
|
642 | for opConfObj in self.opConfObjList: | |
642 | opConfObj.makeXml(procUnitElement) |
|
643 | opConfObj.makeXml(procUnitElement) | |
643 |
|
644 | |||
644 | def readXml(self, upElement): |
|
645 | def readXml(self, upElement): | |
645 |
|
646 | |||
646 | self.id = upElement.get('id') |
|
647 | self.id = upElement.get('id') | |
647 | self.name = upElement.get('name') |
|
648 | self.name = upElement.get('name') | |
648 | self.datatype = upElement.get('datatype') |
|
649 | self.datatype = upElement.get('datatype') | |
649 | self.inputId = upElement.get('inputId') |
|
650 | self.inputId = upElement.get('inputId') | |
650 |
|
651 | |||
651 | if self.ELEMENTNAME == 'ReadUnit': |
|
652 | if self.ELEMENTNAME == 'ReadUnit': | |
652 | self.datatype = self.datatype.replace('Reader', '') |
|
653 | self.datatype = self.datatype.replace('Reader', '') | |
653 |
|
654 | |||
654 | if self.ELEMENTNAME == 'ProcUnit': |
|
655 | if self.ELEMENTNAME == 'ProcUnit': | |
655 | self.datatype = self.datatype.replace('Proc', '') |
|
656 | self.datatype = self.datatype.replace('Proc', '') | |
656 |
|
657 | |||
657 | if self.inputId == 'None': |
|
658 | if self.inputId == 'None': | |
658 | self.inputId = '0' |
|
659 | self.inputId = '0' | |
659 |
|
660 | |||
660 | self.opConfObjList = [] |
|
661 | self.opConfObjList = [] | |
661 |
|
662 | |||
662 | opElementList = upElement.iter(OperationConf().getElementName()) |
|
663 | opElementList = upElement.iter(OperationConf().getElementName()) | |
663 |
|
664 | |||
664 | for opElement in opElementList: |
|
665 | for opElement in opElementList: | |
665 | opConfObj = OperationConf() |
|
666 | opConfObj = OperationConf() | |
666 | opConfObj.readXml(opElement) |
|
667 | opConfObj.readXml(opElement) | |
667 | self.opConfObjList.append(opConfObj) |
|
668 | self.opConfObjList.append(opConfObj) | |
668 |
|
669 | |||
669 | def printattr(self): |
|
670 | def printattr(self): | |
670 |
|
671 | |||
671 | print('%s[%s]: name = %s, datatype = %s, inputId = %s' % (self.ELEMENTNAME, |
|
672 | print('%s[%s]: name = %s, datatype = %s, inputId = %s' % (self.ELEMENTNAME, | |
672 | self.id, |
|
673 | self.id, | |
673 | self.name, |
|
674 | self.name, | |
674 | self.datatype, |
|
675 | self.datatype, | |
675 | self.inputId)) |
|
676 | self.inputId)) | |
676 |
|
677 | |||
677 | for opConfObj in self.opConfObjList: |
|
678 | for opConfObj in self.opConfObjList: | |
678 | opConfObj.printattr() |
|
679 | opConfObj.printattr() | |
679 |
|
680 | |||
680 | def getKwargs(self): |
|
681 | def getKwargs(self): | |
681 |
|
682 | |||
682 | opObj = self.opConfObjList[0] |
|
683 | opObj = self.opConfObjList[0] | |
683 | kwargs = opObj.getKwargs() |
|
684 | kwargs = opObj.getKwargs() | |
684 |
|
685 | |||
685 | return kwargs |
|
686 | return kwargs | |
686 |
|
687 | |||
687 | def createObjects(self, dictUnits): |
|
688 | def createObjects(self, dictUnits): | |
688 | ''' |
|
689 | ''' | |
689 | Instancia de unidades de procesamiento. |
|
690 | Instancia de unidades de procesamiento. | |
690 |
|
691 | |||
691 | ''' |
|
692 | ''' | |
692 | className = eval(self.name) |
|
693 | className = eval(self.name) | |
693 | kwargs = self.getKwargs() |
|
694 | kwargs = self.getKwargs() | |
694 | procUnitObj = className(self.id, self.inputId, dictUnits, **kwargs) # necesitan saber su id y su entrada por fines de ipc |
|
695 | procUnitObj = className(self.id, self.inputId, dictUnits, **kwargs) # necesitan saber su id y su entrada por fines de ipc | |
695 |
|
696 | |||
696 |
|
697 | |||
697 | for opConfObj in self.opConfObjList: |
|
698 | for opConfObj in self.opConfObjList: | |
698 |
|
699 | |||
699 | if opConfObj.type == 'self' and self.name == 'run': |
|
700 | if opConfObj.type == 'self' and self.name == 'run': | |
700 | continue |
|
701 | continue | |
701 | elif opConfObj.type == 'self': |
|
702 | elif opConfObj.type == 'self': | |
702 | procUnitObj.addOperationKwargs( |
|
703 | procUnitObj.addOperationKwargs( | |
703 | opConfObj.id, **opConfObj.getKwargs()) |
|
704 | opConfObj.id, **opConfObj.getKwargs()) | |
704 | continue |
|
705 | continue | |
705 | print("Creating operation process:", opConfObj.name, "for", self.name) |
|
706 | print("Creating operation process:", opConfObj.name, "for", self.name) | |
706 | opObj = opConfObj.createObject() |
|
707 | opObj = opConfObj.createObject() | |
707 |
|
708 | |||
708 |
|
709 | |||
709 | #self.opObjDict[opConfObj.id] = opObj.name |
|
710 | #self.opObjDict[opConfObj.id] = opObj.name | |
710 |
|
711 | |||
711 | procUnitObj.addOperation(opConfObj.name, opConfObj.id) |
|
712 | procUnitObj.addOperation(opConfObj.name, opConfObj.id) | |
712 |
|
713 | |||
713 | procUnitObj.start() |
|
714 | procUnitObj.start() | |
714 |
|
715 | |||
715 | self.procUnitObj = procUnitObj |
|
716 | self.procUnitObj = procUnitObj | |
716 |
|
717 | |||
717 |
|
718 | |||
718 | return procUnitObj |
|
719 | return procUnitObj | |
719 |
|
720 | |||
720 | def run(self): |
|
721 | def run(self): | |
721 |
|
722 | |||
722 | is_ok = True |
|
723 | is_ok = True | |
723 | """ |
|
724 | """ | |
724 | for opConfObj in self.opConfObjList: |
|
725 | for opConfObj in self.opConfObjList: | |
725 |
|
726 | |||
726 | kwargs = {} |
|
727 | kwargs = {} | |
727 | for parmConfObj in opConfObj.getParameterObjList(): |
|
728 | for parmConfObj in opConfObj.getParameterObjList(): | |
728 | if opConfObj.name == 'run' and parmConfObj.name == 'datatype': |
|
729 | if opConfObj.name == 'run' and parmConfObj.name == 'datatype': | |
729 | continue |
|
730 | continue | |
730 |
|
731 | |||
731 | kwargs[parmConfObj.name] = parmConfObj.getValue() |
|
732 | kwargs[parmConfObj.name] = parmConfObj.getValue() | |
732 |
|
733 | |||
733 | sts = self.procUnitObj.call(opType=opConfObj.type, |
|
734 | sts = self.procUnitObj.call(opType=opConfObj.type, | |
734 | opName=opConfObj.name, |
|
735 | opName=opConfObj.name, | |
735 | opId=opConfObj.id) |
|
736 | opId=opConfObj.id) | |
736 |
|
737 | |||
737 | is_ok = is_ok or sts |
|
738 | is_ok = is_ok or sts | |
738 |
|
739 | |||
739 | """ |
|
740 | """ | |
740 | return is_ok |
|
741 | return is_ok | |
741 |
|
742 | |||
742 |
|
743 | |||
743 | def close(self): |
|
744 | def close(self): | |
744 |
|
745 | |||
745 | for opConfObj in self.opConfObjList: |
|
746 | for opConfObj in self.opConfObjList: | |
746 | if opConfObj.type == 'self': |
|
747 | if opConfObj.type == 'self': | |
747 | continue |
|
748 | continue | |
748 |
|
749 | |||
749 | opObj = self.procUnitObj.getOperationObj(opConfObj.id) |
|
750 | opObj = self.procUnitObj.getOperationObj(opConfObj.id) | |
750 | opObj.close() |
|
751 | opObj.close() | |
751 |
|
752 | |||
752 | self.procUnitObj.close() |
|
753 | self.procUnitObj.close() | |
753 |
|
754 | |||
754 | return |
|
755 | return | |
755 |
|
756 | |||
756 |
|
757 | |||
757 | class ReadUnitConf(ProcUnitConf): |
|
758 | class ReadUnitConf(ProcUnitConf): | |
758 |
|
759 | |||
759 | path = None |
|
760 | path = None | |
760 | startDate = None |
|
761 | startDate = None | |
761 | endDate = None |
|
762 | endDate = None | |
762 | startTime = None |
|
763 | startTime = None | |
763 | endTime = None |
|
764 | endTime = None | |
764 |
|
765 | |||
765 | ELEMENTNAME = 'ReadUnit' |
|
766 | ELEMENTNAME = 'ReadUnit' | |
766 |
|
767 | |||
767 | def __init__(self): |
|
768 | def __init__(self): | |
768 |
|
769 | |||
769 | self.id = None |
|
770 | self.id = None | |
770 | self.datatype = None |
|
771 | self.datatype = None | |
771 | self.name = None |
|
772 | self.name = None | |
772 | self.inputId = None |
|
773 | self.inputId = None | |
773 |
|
774 | |||
774 | self.parentId = None |
|
775 | self.parentId = None | |
775 |
|
776 | |||
776 | self.opConfObjList = [] |
|
777 | self.opConfObjList = [] | |
777 | self.opObjList = [] |
|
778 | self.opObjList = [] | |
778 |
|
779 | |||
779 | def getElementName(self): |
|
780 | def getElementName(self): | |
780 |
|
781 | |||
781 | return self.ELEMENTNAME |
|
782 | return self.ELEMENTNAME | |
782 |
|
783 | |||
783 | def setup(self, id, name, datatype, path='', startDate='', endDate='', |
|
784 | def setup(self, id, name, datatype, path='', startDate='', endDate='', | |
784 | startTime='', endTime='', parentId=None, server=None, **kwargs): |
|
785 | startTime='', endTime='', parentId=None, server=None, **kwargs): | |
785 |
|
786 | |||
786 |
|
787 | |||
787 | ''' |
|
788 | ''' | |
788 | *****el id del proceso sera el Topico |
|
789 | *****el id del proceso sera el Topico | |
789 |
|
790 | |||
790 | Adicion de {topic}, si no esta presente -> error |
|
791 | Adicion de {topic}, si no esta presente -> error | |
791 | kwargs deben ser trasmitidos en la instanciacion |
|
792 | kwargs deben ser trasmitidos en la instanciacion | |
792 |
|
793 | |||
793 | ''' |
|
794 | ''' | |
794 |
|
795 | |||
795 | # Compatible with old signal chain version |
|
796 | # Compatible with old signal chain version | |
796 | if datatype == None and name == None: |
|
797 | if datatype == None and name == None: | |
797 | raise ValueError('datatype or name should be defined') |
|
798 | raise ValueError('datatype or name should be defined') | |
798 | if name == None: |
|
799 | if name == None: | |
799 | if 'Reader' in datatype: |
|
800 | if 'Reader' in datatype: | |
800 | name = datatype |
|
801 | name = datatype | |
801 | datatype = name.replace('Reader','') |
|
802 | datatype = name.replace('Reader','') | |
802 | else: |
|
803 | else: | |
803 | name = '{}Reader'.format(datatype) |
|
804 | name = '{}Reader'.format(datatype) | |
804 | if datatype == None: |
|
805 | if datatype == None: | |
805 | if 'Reader' in name: |
|
806 | if 'Reader' in name: | |
806 | datatype = name.replace('Reader','') |
|
807 | datatype = name.replace('Reader','') | |
807 | else: |
|
808 | else: | |
808 | datatype = name |
|
809 | datatype = name | |
809 | name = '{}Reader'.format(name) |
|
810 | name = '{}Reader'.format(name) | |
810 |
|
811 | |||
811 | self.id = id |
|
812 | self.id = id | |
812 | self.name = name |
|
813 | self.name = name | |
813 | self.datatype = datatype |
|
814 | self.datatype = datatype | |
814 | if path != '': |
|
815 | if path != '': | |
815 | self.path = os.path.abspath(path) |
|
816 | self.path = os.path.abspath(path) | |
816 | self.startDate = startDate |
|
817 | self.startDate = startDate | |
817 | self.endDate = endDate |
|
818 | self.endDate = endDate | |
818 | self.startTime = startTime |
|
819 | self.startTime = startTime | |
819 | self.endTime = endTime |
|
820 | self.endTime = endTime | |
820 | self.inputId = '0' |
|
821 | self.inputId = '0' | |
821 | self.parentId = parentId |
|
822 | self.parentId = parentId | |
822 | self.server = server |
|
823 | self.server = server | |
823 | self.addRunOperation(**kwargs) |
|
824 | self.addRunOperation(**kwargs) | |
824 |
|
825 | |||
825 | def update(self, **kwargs): |
|
826 | def update(self, **kwargs): | |
826 |
|
827 | |||
827 | if 'datatype' in kwargs: |
|
828 | if 'datatype' in kwargs: | |
828 | datatype = kwargs.pop('datatype') |
|
829 | datatype = kwargs.pop('datatype') | |
829 | if 'Reader' in datatype: |
|
830 | if 'Reader' in datatype: | |
830 | self.name = datatype |
|
831 | self.name = datatype | |
831 | else: |
|
832 | else: | |
832 | self.name = '%sReader' % (datatype) |
|
833 | self.name = '%sReader' % (datatype) | |
833 | self.datatype = self.name.replace('Reader', '') |
|
834 | self.datatype = self.name.replace('Reader', '') | |
834 |
|
835 | |||
835 | attrs = ('path', 'startDate', 'endDate', |
|
836 | attrs = ('path', 'startDate', 'endDate', | |
836 | 'startTime', 'endTime', 'parentId') |
|
837 | 'startTime', 'endTime', 'parentId') | |
837 |
|
838 | |||
838 | for attr in attrs: |
|
839 | for attr in attrs: | |
839 | if attr in kwargs: |
|
840 | if attr in kwargs: | |
840 | setattr(self, attr, kwargs.pop(attr)) |
|
841 | setattr(self, attr, kwargs.pop(attr)) | |
841 |
|
842 | |||
842 | self.inputId = '0' |
|
843 | self.inputId = '0' | |
843 | self.updateRunOperation(**kwargs) |
|
844 | self.updateRunOperation(**kwargs) | |
844 |
|
845 | |||
845 | def removeOperations(self): |
|
846 | def removeOperations(self): | |
846 |
|
847 | |||
847 | for obj in self.opConfObjList: |
|
848 | for obj in self.opConfObjList: | |
848 | del obj |
|
849 | del obj | |
849 |
|
850 | |||
850 | self.opConfObjList = [] |
|
851 | self.opConfObjList = [] | |
851 |
|
852 | |||
852 | def addRunOperation(self, **kwargs): |
|
853 | def addRunOperation(self, **kwargs): | |
853 |
|
854 | |||
854 | opObj = self.addOperation(name='run', optype='self') |
|
855 | opObj = self.addOperation(name='run', optype='self') | |
855 |
|
856 | |||
856 | if self.server is None: |
|
857 | if self.server is None: | |
857 | opObj.addParameter( |
|
858 | opObj.addParameter( | |
858 | name='datatype', value=self.datatype, format='str') |
|
859 | name='datatype', value=self.datatype, format='str') | |
859 | opObj.addParameter(name='path', value=self.path, format='str') |
|
860 | opObj.addParameter(name='path', value=self.path, format='str') | |
860 | opObj.addParameter( |
|
861 | opObj.addParameter( | |
861 | name='startDate', value=self.startDate, format='date') |
|
862 | name='startDate', value=self.startDate, format='date') | |
862 | opObj.addParameter( |
|
863 | opObj.addParameter( | |
863 | name='endDate', value=self.endDate, format='date') |
|
864 | name='endDate', value=self.endDate, format='date') | |
864 | opObj.addParameter( |
|
865 | opObj.addParameter( | |
865 | name='startTime', value=self.startTime, format='time') |
|
866 | name='startTime', value=self.startTime, format='time') | |
866 | opObj.addParameter( |
|
867 | opObj.addParameter( | |
867 | name='endTime', value=self.endTime, format='time') |
|
868 | name='endTime', value=self.endTime, format='time') | |
868 |
|
869 | |||
869 | for key, value in list(kwargs.items()): |
|
870 | for key, value in list(kwargs.items()): | |
870 | opObj.addParameter(name=key, value=value, |
|
871 | opObj.addParameter(name=key, value=value, | |
871 | format=type(value).__name__) |
|
872 | format=type(value).__name__) | |
872 | else: |
|
873 | else: | |
873 | opObj.addParameter(name='server', value=self.server, format='str') |
|
874 | opObj.addParameter(name='server', value=self.server, format='str') | |
874 |
|
875 | |||
875 | return opObj |
|
876 | return opObj | |
876 |
|
877 | |||
877 | def updateRunOperation(self, **kwargs): |
|
878 | def updateRunOperation(self, **kwargs): | |
878 |
|
879 | |||
879 | opObj = self.getOperationObj(name='run') |
|
880 | opObj = self.getOperationObj(name='run') | |
880 | opObj.removeParameters() |
|
881 | opObj.removeParameters() | |
881 |
|
882 | |||
882 | opObj.addParameter(name='datatype', value=self.datatype, format='str') |
|
883 | opObj.addParameter(name='datatype', value=self.datatype, format='str') | |
883 | opObj.addParameter(name='path', value=self.path, format='str') |
|
884 | opObj.addParameter(name='path', value=self.path, format='str') | |
884 | opObj.addParameter( |
|
885 | opObj.addParameter( | |
885 | name='startDate', value=self.startDate, format='date') |
|
886 | name='startDate', value=self.startDate, format='date') | |
886 | opObj.addParameter(name='endDate', value=self.endDate, format='date') |
|
887 | opObj.addParameter(name='endDate', value=self.endDate, format='date') | |
887 | opObj.addParameter( |
|
888 | opObj.addParameter( | |
888 | name='startTime', value=self.startTime, format='time') |
|
889 | name='startTime', value=self.startTime, format='time') | |
889 | opObj.addParameter(name='endTime', value=self.endTime, format='time') |
|
890 | opObj.addParameter(name='endTime', value=self.endTime, format='time') | |
890 |
|
891 | |||
891 | for key, value in list(kwargs.items()): |
|
892 | for key, value in list(kwargs.items()): | |
892 | opObj.addParameter(name=key, value=value, |
|
893 | opObj.addParameter(name=key, value=value, | |
893 | format=type(value).__name__) |
|
894 | format=type(value).__name__) | |
894 |
|
895 | |||
895 | return opObj |
|
896 | return opObj | |
896 |
|
897 | |||
897 | def readXml(self, upElement): |
|
898 | def readXml(self, upElement): | |
898 |
|
899 | |||
899 | self.id = upElement.get('id') |
|
900 | self.id = upElement.get('id') | |
900 | self.name = upElement.get('name') |
|
901 | self.name = upElement.get('name') | |
901 | self.datatype = upElement.get('datatype') |
|
902 | self.datatype = upElement.get('datatype') | |
902 | self.inputId = upElement.get('inputId') |
|
903 | self.inputId = upElement.get('inputId') | |
903 |
|
904 | |||
904 | if self.ELEMENTNAME == 'ReadUnit': |
|
905 | if self.ELEMENTNAME == 'ReadUnit': | |
905 | self.datatype = self.datatype.replace('Reader', '') |
|
906 | self.datatype = self.datatype.replace('Reader', '') | |
906 |
|
907 | |||
907 | if self.inputId == 'None': |
|
908 | if self.inputId == 'None': | |
908 | self.inputId = '0' |
|
909 | self.inputId = '0' | |
909 |
|
910 | |||
910 | self.opConfObjList = [] |
|
911 | self.opConfObjList = [] | |
911 |
|
912 | |||
912 | opElementList = upElement.iter(OperationConf().getElementName()) |
|
913 | opElementList = upElement.iter(OperationConf().getElementName()) | |
913 |
|
914 | |||
914 | for opElement in opElementList: |
|
915 | for opElement in opElementList: | |
915 | opConfObj = OperationConf() |
|
916 | opConfObj = OperationConf() | |
916 | opConfObj.readXml(opElement) |
|
917 | opConfObj.readXml(opElement) | |
917 | self.opConfObjList.append(opConfObj) |
|
918 | self.opConfObjList.append(opConfObj) | |
918 |
|
919 | |||
919 | if opConfObj.name == 'run': |
|
920 | if opConfObj.name == 'run': | |
920 | self.path = opConfObj.getParameterValue('path') |
|
921 | self.path = opConfObj.getParameterValue('path') | |
921 | self.startDate = opConfObj.getParameterValue('startDate') |
|
922 | self.startDate = opConfObj.getParameterValue('startDate') | |
922 | self.endDate = opConfObj.getParameterValue('endDate') |
|
923 | self.endDate = opConfObj.getParameterValue('endDate') | |
923 | self.startTime = opConfObj.getParameterValue('startTime') |
|
924 | self.startTime = opConfObj.getParameterValue('startTime') | |
924 | self.endTime = opConfObj.getParameterValue('endTime') |
|
925 | self.endTime = opConfObj.getParameterValue('endTime') | |
925 |
|
926 | |||
926 |
|
927 | |||
927 | class Project(Process): |
|
928 | class Project(Process): | |
928 |
|
929 | |||
929 | id = None |
|
930 | id = None | |
930 | description = None |
|
931 | description = None | |
931 | filename = None |
|
932 | filename = None | |
932 |
|
933 | |||
933 | procUnitConfObjDict = None |
|
934 | procUnitConfObjDict = None | |
934 |
|
935 | |||
935 | ELEMENTNAME = 'Project' |
|
936 | ELEMENTNAME = 'Project' | |
936 |
|
937 | |||
937 |
|
938 | |||
938 |
|
939 | |||
939 | def __init__(self): |
|
940 | def __init__(self): | |
940 |
|
941 | |||
941 | Process.__init__(self) |
|
942 | Process.__init__(self) | |
942 | self.id = None |
|
943 | self.id = None | |
943 | self.description = None |
|
944 | self.description = None | |
944 | self.email = None |
|
945 | self.email = None | |
945 | self.alarm = None |
|
946 | self.alarm = None | |
946 | self.procUnitConfObjDict = {} |
|
947 | self.procUnitConfObjDict = {} | |
947 |
|
948 | |||
948 | def __getNewId(self): |
|
949 | def __getNewId(self): | |
949 |
|
950 | |||
950 | idList = list(self.procUnitConfObjDict.keys()) |
|
951 | idList = list(self.procUnitConfObjDict.keys()) | |
951 |
|
952 | |||
952 | id = int(self.id) * 10 |
|
953 | id = int(self.id) * 10 | |
953 |
|
954 | |||
954 | while True: |
|
955 | while True: | |
955 | id += 1 |
|
956 | id += 1 | |
956 |
|
957 | |||
957 | if str(id) in idList: |
|
958 | if str(id) in idList: | |
958 | continue |
|
959 | continue | |
959 |
|
960 | |||
960 | break |
|
961 | break | |
961 |
|
962 | |||
962 | return str(id) |
|
963 | return str(id) | |
963 |
|
964 | |||
964 | def getElementName(self): |
|
965 | def getElementName(self): | |
965 |
|
966 | |||
966 | return self.ELEMENTNAME |
|
967 | return self.ELEMENTNAME | |
967 |
|
968 | |||
968 | def getId(self): |
|
969 | def getId(self): | |
969 |
|
970 | |||
970 | return self.id |
|
971 | return self.id | |
971 |
|
972 | |||
972 | def updateId(self, new_id): |
|
973 | def updateId(self, new_id): | |
973 |
|
974 | |||
974 | self.id = str(new_id) |
|
975 | self.id = str(new_id) | |
975 |
|
976 | |||
976 | keyList = list(self.procUnitConfObjDict.keys()) |
|
977 | keyList = list(self.procUnitConfObjDict.keys()) | |
977 | keyList.sort() |
|
978 | keyList.sort() | |
978 |
|
979 | |||
979 | n = 1 |
|
980 | n = 1 | |
980 | newProcUnitConfObjDict = {} |
|
981 | newProcUnitConfObjDict = {} | |
981 |
|
982 | |||
982 | for procKey in keyList: |
|
983 | for procKey in keyList: | |
983 |
|
984 | |||
984 | procUnitConfObj = self.procUnitConfObjDict[procKey] |
|
985 | procUnitConfObj = self.procUnitConfObjDict[procKey] | |
985 | idProcUnit = str(int(self.id) * 10 + n) |
|
986 | idProcUnit = str(int(self.id) * 10 + n) | |
986 | procUnitConfObj.updateId(idProcUnit, parentId=self.id) |
|
987 | procUnitConfObj.updateId(idProcUnit, parentId=self.id) | |
987 | newProcUnitConfObjDict[idProcUnit] = procUnitConfObj |
|
988 | newProcUnitConfObjDict[idProcUnit] = procUnitConfObj | |
988 | n += 1 |
|
989 | n += 1 | |
989 |
|
990 | |||
990 | self.procUnitConfObjDict = newProcUnitConfObjDict |
|
991 | self.procUnitConfObjDict = newProcUnitConfObjDict | |
991 |
|
992 | |||
992 | def setup(self, id, name='', description='', email=None, alarm=[]): |
|
993 | def setup(self, id, name='', description='', email=None, alarm=[]): | |
993 |
|
994 | |||
994 | print(' ') |
|
995 | print(' ') | |
995 | print('*' * 60) |
|
996 | print('*' * 60) | |
996 | print('* Starting SIGNAL CHAIN PROCESSING (Multiprocessing) v%s *' % schainpy.__version__) |
|
997 | print('* Starting SIGNAL CHAIN PROCESSING (Multiprocessing) v%s *' % schainpy.__version__) | |
997 | print('*' * 60) |
|
998 | print('*' * 60) | |
998 | print("* Python " + python_version() + " *") |
|
999 | print("* Python " + python_version() + " *") | |
999 | print('*' * 19) |
|
1000 | print('*' * 19) | |
1000 | print(' ') |
|
1001 | print(' ') | |
1001 | self.id = str(id) |
|
1002 | self.id = str(id) | |
1002 | self.description = description |
|
1003 | self.description = description | |
1003 | self.email = email |
|
1004 | self.email = email | |
1004 | self.alarm = alarm |
|
1005 | self.alarm = alarm | |
1005 |
|
1006 | |||
1006 | def update(self, **kwargs): |
|
1007 | def update(self, **kwargs): | |
1007 |
|
1008 | |||
1008 | for key, value in list(kwargs.items()): |
|
1009 | for key, value in list(kwargs.items()): | |
1009 | setattr(self, key, value) |
|
1010 | setattr(self, key, value) | |
1010 |
|
1011 | |||
1011 | def clone(self): |
|
1012 | def clone(self): | |
1012 |
|
1013 | |||
1013 | p = Project() |
|
1014 | p = Project() | |
1014 | p.procUnitConfObjDict = self.procUnitConfObjDict |
|
1015 | p.procUnitConfObjDict = self.procUnitConfObjDict | |
1015 | return p |
|
1016 | return p | |
1016 |
|
1017 | |||
1017 | def addReadUnit(self, id=None, datatype=None, name=None, **kwargs): |
|
1018 | def addReadUnit(self, id=None, datatype=None, name=None, **kwargs): | |
1018 |
|
1019 | |||
1019 | ''' |
|
1020 | ''' | |
1020 | Actualizacion: |
|
1021 | Actualizacion: | |
1021 | Se agrego un nuevo argumento: topic -relativo a la forma de comunicar los procesos simultaneos |
|
1022 | Se agrego un nuevo argumento: topic -relativo a la forma de comunicar los procesos simultaneos | |
1022 |
|
1023 | |||
1023 | * El id del proceso sera el topico al que se deben subscribir los procUnits para recibir la informacion(data) |
|
1024 | * El id del proceso sera el topico al que se deben subscribir los procUnits para recibir la informacion(data) | |
1024 |
|
1025 | |||
1025 | ''' |
|
1026 | ''' | |
1026 |
|
1027 | |||
1027 | if id is None: |
|
1028 | if id is None: | |
1028 | idReadUnit = self.__getNewId() |
|
1029 | idReadUnit = self.__getNewId() | |
1029 | else: |
|
1030 | else: | |
1030 | idReadUnit = str(id) |
|
1031 | idReadUnit = str(id) | |
1031 |
|
1032 | |||
1032 | readUnitConfObj = ReadUnitConf() |
|
1033 | readUnitConfObj = ReadUnitConf() | |
1033 | readUnitConfObj.setup(idReadUnit, name, datatype, |
|
1034 | readUnitConfObj.setup(idReadUnit, name, datatype, | |
1034 | parentId=self.id, **kwargs) |
|
1035 | parentId=self.id, **kwargs) | |
1035 |
|
1036 | |||
1036 | self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj |
|
1037 | self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj | |
1037 |
|
1038 | |||
1038 | return readUnitConfObj |
|
1039 | return readUnitConfObj | |
1039 |
|
1040 | |||
1040 | def addProcUnit(self, inputId='0', datatype=None, name=None): |
|
1041 | def addProcUnit(self, inputId='0', datatype=None, name=None): | |
1041 |
|
1042 | |||
1042 | ''' |
|
1043 | ''' | |
1043 | Actualizacion: |
|
1044 | Actualizacion: | |
1044 | Se agrego dos nuevos argumentos: topic_read (lee data de otro procUnit) y topic_write(escribe o envia data a otro procUnit) |
|
1045 | Se agrego dos nuevos argumentos: topic_read (lee data de otro procUnit) y topic_write(escribe o envia data a otro procUnit) | |
1045 | Deberia reemplazar a "inputId" |
|
1046 | Deberia reemplazar a "inputId" | |
1046 |
|
1047 | |||
1047 | ** A fin de mantener el inputID, este sera la representaacion del topicoal que deben subscribirse. El ID propio de la intancia |
|
1048 | ** A fin de mantener el inputID, este sera la representaacion del topicoal que deben subscribirse. El ID propio de la intancia | |
1048 | (proceso) sera el topico de la publicacion, todo sera asignado de manera dinamica. |
|
1049 | (proceso) sera el topico de la publicacion, todo sera asignado de manera dinamica. | |
1049 |
|
1050 | |||
1050 | ''' |
|
1051 | ''' | |
1051 |
|
1052 | |||
1052 | idProcUnit = self.__getNewId() #Topico para subscripcion |
|
1053 | idProcUnit = self.__getNewId() #Topico para subscripcion | |
1053 |
|
1054 | |||
1054 | procUnitConfObj = ProcUnitConf() |
|
1055 | procUnitConfObj = ProcUnitConf() | |
1055 | procUnitConfObj.setup(idProcUnit, name, datatype, inputId, #topic_read, topic_write, |
|
1056 | procUnitConfObj.setup(idProcUnit, name, datatype, inputId, #topic_read, topic_write, | |
1056 | parentId=self.id) |
|
1057 | parentId=self.id) | |
1057 |
|
1058 | |||
1058 | self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj |
|
1059 | self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj | |
1059 |
|
1060 | |||
1060 | return procUnitConfObj |
|
1061 | return procUnitConfObj | |
1061 |
|
1062 | |||
1062 | def removeProcUnit(self, id): |
|
1063 | def removeProcUnit(self, id): | |
1063 |
|
1064 | |||
1064 | if id in list(self.procUnitConfObjDict.keys()): |
|
1065 | if id in list(self.procUnitConfObjDict.keys()): | |
1065 | self.procUnitConfObjDict.pop(id) |
|
1066 | self.procUnitConfObjDict.pop(id) | |
1066 |
|
1067 | |||
1067 | def getReadUnitId(self): |
|
1068 | def getReadUnitId(self): | |
1068 |
|
1069 | |||
1069 | readUnitConfObj = self.getReadUnitObj() |
|
1070 | readUnitConfObj = self.getReadUnitObj() | |
1070 |
|
1071 | |||
1071 | return readUnitConfObj.id |
|
1072 | return readUnitConfObj.id | |
1072 |
|
1073 | |||
1073 | def getReadUnitObj(self): |
|
1074 | def getReadUnitObj(self): | |
1074 |
|
1075 | |||
1075 | for obj in list(self.procUnitConfObjDict.values()): |
|
1076 | for obj in list(self.procUnitConfObjDict.values()): | |
1076 | if obj.getElementName() == 'ReadUnit': |
|
1077 | if obj.getElementName() == 'ReadUnit': | |
1077 | return obj |
|
1078 | return obj | |
1078 |
|
1079 | |||
1079 | return None |
|
1080 | return None | |
1080 |
|
1081 | |||
1081 | def getProcUnitObj(self, id=None, name=None): |
|
1082 | def getProcUnitObj(self, id=None, name=None): | |
1082 |
|
1083 | |||
1083 | if id != None: |
|
1084 | if id != None: | |
1084 | return self.procUnitConfObjDict[id] |
|
1085 | return self.procUnitConfObjDict[id] | |
1085 |
|
1086 | |||
1086 | if name != None: |
|
1087 | if name != None: | |
1087 | return self.getProcUnitObjByName(name) |
|
1088 | return self.getProcUnitObjByName(name) | |
1088 |
|
1089 | |||
1089 | return None |
|
1090 | return None | |
1090 |
|
1091 | |||
1091 | def getProcUnitObjByName(self, name): |
|
1092 | def getProcUnitObjByName(self, name): | |
1092 |
|
1093 | |||
1093 | for obj in list(self.procUnitConfObjDict.values()): |
|
1094 | for obj in list(self.procUnitConfObjDict.values()): | |
1094 | if obj.name == name: |
|
1095 | if obj.name == name: | |
1095 | return obj |
|
1096 | return obj | |
1096 |
|
1097 | |||
1097 | return None |
|
1098 | return None | |
1098 |
|
1099 | |||
1099 | def procUnitItems(self): |
|
1100 | def procUnitItems(self): | |
1100 |
|
1101 | |||
1101 | return list(self.procUnitConfObjDict.items()) |
|
1102 | return list(self.procUnitConfObjDict.items()) | |
1102 |
|
1103 | |||
1103 | def makeXml(self): |
|
1104 | def makeXml(self): | |
1104 |
|
1105 | |||
1105 | projectElement = Element('Project') |
|
1106 | projectElement = Element('Project') | |
1106 | projectElement.set('id', str(self.id)) |
|
1107 | projectElement.set('id', str(self.id)) | |
1107 | projectElement.set('name', self.name) |
|
1108 | projectElement.set('name', self.name) | |
1108 | projectElement.set('description', self.description) |
|
1109 | projectElement.set('description', self.description) | |
1109 |
|
1110 | |||
1110 | for procUnitConfObj in list(self.procUnitConfObjDict.values()): |
|
1111 | for procUnitConfObj in list(self.procUnitConfObjDict.values()): | |
1111 | procUnitConfObj.makeXml(projectElement) |
|
1112 | procUnitConfObj.makeXml(projectElement) | |
1112 |
|
1113 | |||
1113 | self.projectElement = projectElement |
|
1114 | self.projectElement = projectElement | |
1114 |
|
1115 | |||
1115 | def writeXml(self, filename=None): |
|
1116 | def writeXml(self, filename=None): | |
1116 |
|
1117 | |||
1117 | if filename == None: |
|
1118 | if filename == None: | |
1118 | if self.filename: |
|
1119 | if self.filename: | |
1119 | filename = self.filename |
|
1120 | filename = self.filename | |
1120 | else: |
|
1121 | else: | |
1121 | filename = 'schain.xml' |
|
1122 | filename = 'schain.xml' | |
1122 |
|
1123 | |||
1123 | if not filename: |
|
1124 | if not filename: | |
1124 | print('filename has not been defined. Use setFilename(filename) for do it.') |
|
1125 | print('filename has not been defined. Use setFilename(filename) for do it.') | |
1125 | return 0 |
|
1126 | return 0 | |
1126 |
|
1127 | |||
1127 | abs_file = os.path.abspath(filename) |
|
1128 | abs_file = os.path.abspath(filename) | |
1128 |
|
1129 | |||
1129 | if not os.access(os.path.dirname(abs_file), os.W_OK): |
|
1130 | if not os.access(os.path.dirname(abs_file), os.W_OK): | |
1130 | print('No write permission on %s' % os.path.dirname(abs_file)) |
|
1131 | print('No write permission on %s' % os.path.dirname(abs_file)) | |
1131 | return 0 |
|
1132 | return 0 | |
1132 |
|
1133 | |||
1133 | if os.path.isfile(abs_file) and not(os.access(abs_file, os.W_OK)): |
|
1134 | if os.path.isfile(abs_file) and not(os.access(abs_file, os.W_OK)): | |
1134 | print('File %s already exists and it could not be overwriten' % abs_file) |
|
1135 | print('File %s already exists and it could not be overwriten' % abs_file) | |
1135 | return 0 |
|
1136 | return 0 | |
1136 |
|
1137 | |||
1137 | self.makeXml() |
|
1138 | self.makeXml() | |
1138 |
|
1139 | |||
1139 | ElementTree(self.projectElement).write(abs_file, method='xml') |
|
1140 | ElementTree(self.projectElement).write(abs_file, method='xml') | |
1140 |
|
1141 | |||
1141 | self.filename = abs_file |
|
1142 | self.filename = abs_file | |
1142 |
|
1143 | |||
1143 | return 1 |
|
1144 | return 1 | |
1144 |
|
1145 | |||
1145 | def readXml(self, filename=None): |
|
1146 | def readXml(self, filename=None): | |
1146 |
|
1147 | |||
1147 | if not filename: |
|
1148 | if not filename: | |
1148 | print('filename is not defined') |
|
1149 | print('filename is not defined') | |
1149 | return 0 |
|
1150 | return 0 | |
1150 |
|
1151 | |||
1151 | abs_file = os.path.abspath(filename) |
|
1152 | abs_file = os.path.abspath(filename) | |
1152 |
|
1153 | |||
1153 | if not os.path.isfile(abs_file): |
|
1154 | if not os.path.isfile(abs_file): | |
1154 | print('%s file does not exist' % abs_file) |
|
1155 | print('%s file does not exist' % abs_file) | |
1155 | return 0 |
|
1156 | return 0 | |
1156 |
|
1157 | |||
1157 | self.projectElement = None |
|
1158 | self.projectElement = None | |
1158 | self.procUnitConfObjDict = {} |
|
1159 | self.procUnitConfObjDict = {} | |
1159 |
|
1160 | |||
1160 | try: |
|
1161 | try: | |
1161 | self.projectElement = ElementTree().parse(abs_file) |
|
1162 | self.projectElement = ElementTree().parse(abs_file) | |
1162 | except: |
|
1163 | except: | |
1163 | print('Error reading %s, verify file format' % filename) |
|
1164 | print('Error reading %s, verify file format' % filename) | |
1164 | return 0 |
|
1165 | return 0 | |
1165 |
|
1166 | |||
1166 | self.project = self.projectElement.tag |
|
1167 | self.project = self.projectElement.tag | |
1167 |
|
1168 | |||
1168 | self.id = self.projectElement.get('id') |
|
1169 | self.id = self.projectElement.get('id') | |
1169 | self.name = self.projectElement.get('name') |
|
1170 | self.name = self.projectElement.get('name') | |
1170 | self.description = self.projectElement.get('description') |
|
1171 | self.description = self.projectElement.get('description') | |
1171 |
|
1172 | |||
1172 | readUnitElementList = self.projectElement.iter( |
|
1173 | readUnitElementList = self.projectElement.iter( | |
1173 | ReadUnitConf().getElementName()) |
|
1174 | ReadUnitConf().getElementName()) | |
1174 |
|
1175 | |||
1175 | for readUnitElement in readUnitElementList: |
|
1176 | for readUnitElement in readUnitElementList: | |
1176 | readUnitConfObj = ReadUnitConf() |
|
1177 | readUnitConfObj = ReadUnitConf() | |
1177 | readUnitConfObj.readXml(readUnitElement) |
|
1178 | readUnitConfObj.readXml(readUnitElement) | |
1178 |
|
1179 | |||
1179 | if readUnitConfObj.parentId == None: |
|
1180 | if readUnitConfObj.parentId == None: | |
1180 | readUnitConfObj.parentId = self.id |
|
1181 | readUnitConfObj.parentId = self.id | |
1181 |
|
1182 | |||
1182 | self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj |
|
1183 | self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj | |
1183 |
|
1184 | |||
1184 | procUnitElementList = self.projectElement.iter( |
|
1185 | procUnitElementList = self.projectElement.iter( | |
1185 | ProcUnitConf().getElementName()) |
|
1186 | ProcUnitConf().getElementName()) | |
1186 |
|
1187 | |||
1187 | for procUnitElement in procUnitElementList: |
|
1188 | for procUnitElement in procUnitElementList: | |
1188 | procUnitConfObj = ProcUnitConf() |
|
1189 | procUnitConfObj = ProcUnitConf() | |
1189 | procUnitConfObj.readXml(procUnitElement) |
|
1190 | procUnitConfObj.readXml(procUnitElement) | |
1190 |
|
1191 | |||
1191 | if procUnitConfObj.parentId == None: |
|
1192 | if procUnitConfObj.parentId == None: | |
1192 | procUnitConfObj.parentId = self.id |
|
1193 | procUnitConfObj.parentId = self.id | |
1193 |
|
1194 | |||
1194 | self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj |
|
1195 | self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj | |
1195 |
|
1196 | |||
1196 | self.filename = abs_file |
|
1197 | self.filename = abs_file | |
1197 |
|
1198 | |||
1198 | return 1 |
|
1199 | return 1 | |
1199 |
|
1200 | |||
1200 | def printattr(self): |
|
1201 | def printattr(self): | |
1201 |
|
1202 | |||
1202 | print('Project[%s]: name = %s, description = %s' % (self.id, |
|
1203 | print('Project[%s]: name = %s, description = %s' % (self.id, | |
1203 | self.name, |
|
1204 | self.name, | |
1204 | self.description)) |
|
1205 | self.description)) | |
1205 |
|
1206 | |||
1206 | for procUnitConfObj in list(self.procUnitConfObjDict.values()): |
|
1207 | for procUnitConfObj in list(self.procUnitConfObjDict.values()): | |
1207 | procUnitConfObj.printattr() |
|
1208 | procUnitConfObj.printattr() | |
1208 |
|
1209 | |||
1209 | def createObjects(self): |
|
1210 | def createObjects(self): | |
1210 |
|
1211 | |||
1211 | for procUnitConfObj in list(self.procUnitConfObjDict.values()): |
|
1212 | for procUnitConfObj in list(self.procUnitConfObjDict.values()): | |
1212 | print("Creating process:", procUnitConfObj.name) |
|
1213 | print("Creating process:", procUnitConfObj.name) | |
1213 | procUnitConfObj.createObjects(self.procUnitConfObjDict) |
|
1214 | procUnitConfObj.createObjects(self.procUnitConfObjDict) | |
1214 |
|
1215 | |||
1215 |
|
1216 | |||
1216 | print('All processes were created') |
|
1217 | print('All processes were created') | |
1217 |
|
1218 | |||
1218 | def __handleError(self, procUnitConfObj, modes=None, stdout=True): |
|
1219 | def __handleError(self, procUnitConfObj, modes=None, stdout=True): | |
1219 |
|
1220 | |||
1220 | import socket |
|
1221 | import socket | |
1221 |
|
1222 | |||
1222 | if modes is None: |
|
1223 | if modes is None: | |
1223 | modes = self.alarm |
|
1224 | modes = self.alarm | |
1224 |
|
1225 | |||
1225 | if not self.alarm: |
|
1226 | if not self.alarm: | |
1226 | modes = [] |
|
1227 | modes = [] | |
1227 |
|
1228 | |||
1228 | err = traceback.format_exception(sys.exc_info()[0], |
|
1229 | err = traceback.format_exception(sys.exc_info()[0], | |
1229 | sys.exc_info()[1], |
|
1230 | sys.exc_info()[1], | |
1230 | sys.exc_info()[2]) |
|
1231 | sys.exc_info()[2]) | |
1231 |
|
1232 | |||
1232 | log.error('{}'.format(err[-1]), procUnitConfObj.name) |
|
1233 | log.error('{}'.format(err[-1]), procUnitConfObj.name) | |
1233 |
|
1234 | |||
1234 | message = ''.join(err) |
|
1235 | message = ''.join(err) | |
1235 |
|
1236 | |||
1236 | if stdout: |
|
1237 | if stdout: | |
1237 | sys.stderr.write(message) |
|
1238 | sys.stderr.write(message) | |
1238 |
|
1239 | |||
1239 | subject = 'SChain v%s: Error running %s\n' % ( |
|
1240 | subject = 'SChain v%s: Error running %s\n' % ( | |
1240 | schainpy.__version__, procUnitConfObj.name) |
|
1241 | schainpy.__version__, procUnitConfObj.name) | |
1241 |
|
1242 | |||
1242 | subtitle = '%s: %s\n' % ( |
|
1243 | subtitle = '%s: %s\n' % ( | |
1243 | procUnitConfObj.getElementName(), procUnitConfObj.name) |
|
1244 | procUnitConfObj.getElementName(), procUnitConfObj.name) | |
1244 | subtitle += 'Hostname: %s\n' % socket.gethostbyname( |
|
1245 | subtitle += 'Hostname: %s\n' % socket.gethostbyname( | |
1245 | socket.gethostname()) |
|
1246 | socket.gethostname()) | |
1246 | subtitle += 'Working directory: %s\n' % os.path.abspath('./') |
|
1247 | subtitle += 'Working directory: %s\n' % os.path.abspath('./') | |
1247 | subtitle += 'Configuration file: %s\n' % self.filename |
|
1248 | subtitle += 'Configuration file: %s\n' % self.filename | |
1248 | subtitle += 'Time: %s\n' % str(datetime.datetime.now()) |
|
1249 | subtitle += 'Time: %s\n' % str(datetime.datetime.now()) | |
1249 |
|
1250 | |||
1250 | readUnitConfObj = self.getReadUnitObj() |
|
1251 | readUnitConfObj = self.getReadUnitObj() | |
1251 | if readUnitConfObj: |
|
1252 | if readUnitConfObj: | |
1252 | subtitle += '\nInput parameters:\n' |
|
1253 | subtitle += '\nInput parameters:\n' | |
1253 | subtitle += '[Data path = %s]\n' % readUnitConfObj.path |
|
1254 | subtitle += '[Data path = %s]\n' % readUnitConfObj.path | |
1254 | subtitle += '[Data type = %s]\n' % readUnitConfObj.datatype |
|
1255 | subtitle += '[Data type = %s]\n' % readUnitConfObj.datatype | |
1255 | subtitle += '[Start date = %s]\n' % readUnitConfObj.startDate |
|
1256 | subtitle += '[Start date = %s]\n' % readUnitConfObj.startDate | |
1256 | subtitle += '[End date = %s]\n' % readUnitConfObj.endDate |
|
1257 | subtitle += '[End date = %s]\n' % readUnitConfObj.endDate | |
1257 | subtitle += '[Start time = %s]\n' % readUnitConfObj.startTime |
|
1258 | subtitle += '[Start time = %s]\n' % readUnitConfObj.startTime | |
1258 | subtitle += '[End time = %s]\n' % readUnitConfObj.endTime |
|
1259 | subtitle += '[End time = %s]\n' % readUnitConfObj.endTime | |
1259 |
|
1260 | |||
1260 | a = Alarm( |
|
1261 | a = Alarm( | |
1261 | modes=modes, |
|
1262 | modes=modes, | |
1262 | email=self.email, |
|
1263 | email=self.email, | |
1263 | message=message, |
|
1264 | message=message, | |
1264 | subject=subject, |
|
1265 | subject=subject, | |
1265 | subtitle=subtitle, |
|
1266 | subtitle=subtitle, | |
1266 | filename=self.filename |
|
1267 | filename=self.filename | |
1267 | ) |
|
1268 | ) | |
1268 |
|
1269 | |||
1269 | return a |
|
1270 | return a | |
1270 |
|
1271 | |||
1271 | def isPaused(self): |
|
1272 | def isPaused(self): | |
1272 | return 0 |
|
1273 | return 0 | |
1273 |
|
1274 | |||
1274 | def isStopped(self): |
|
1275 | def isStopped(self): | |
1275 | return 0 |
|
1276 | return 0 | |
1276 |
|
1277 | |||
1277 | def runController(self): |
|
1278 | def runController(self): | |
1278 | ''' |
|
1279 | ''' | |
1279 | returns 0 when this process has been stopped, 1 otherwise |
|
1280 | returns 0 when this process has been stopped, 1 otherwise | |
1280 | ''' |
|
1281 | ''' | |
1281 |
|
1282 | |||
1282 | if self.isPaused(): |
|
1283 | if self.isPaused(): | |
1283 | print('Process suspended') |
|
1284 | print('Process suspended') | |
1284 |
|
1285 | |||
1285 | while True: |
|
1286 | while True: | |
1286 | time.sleep(0.1) |
|
1287 | time.sleep(0.1) | |
1287 |
|
1288 | |||
1288 | if not self.isPaused(): |
|
1289 | if not self.isPaused(): | |
1289 | break |
|
1290 | break | |
1290 |
|
1291 | |||
1291 | if self.isStopped(): |
|
1292 | if self.isStopped(): | |
1292 | break |
|
1293 | break | |
1293 |
|
1294 | |||
1294 | print('Process reinitialized') |
|
1295 | print('Process reinitialized') | |
1295 |
|
1296 | |||
1296 | if self.isStopped(): |
|
1297 | if self.isStopped(): | |
1297 | print('Process stopped') |
|
1298 | print('Process stopped') | |
1298 | return 0 |
|
1299 | return 0 | |
1299 |
|
1300 | |||
1300 | return 1 |
|
1301 | return 1 | |
1301 |
|
1302 | |||
1302 | def setFilename(self, filename): |
|
1303 | def setFilename(self, filename): | |
1303 |
|
1304 | |||
1304 | self.filename = filename |
|
1305 | self.filename = filename | |
1305 |
|
1306 | |||
1306 | def setProxyCom(self): |
|
1307 | def setProxyCom(self): | |
1307 |
|
1308 | |||
1308 | ctx = zmq.Context() |
|
1309 | ctx = zmq.Context() | |
1309 | if not os.path.exists('/tmp/socketTmp'): os.mkdir('/tmp/socketTmp') |
|
1310 | if not os.path.exists('/tmp/socketTmp'): os.mkdir('/tmp/socketTmp') | |
1310 | xsub = ctx.socket(zmq.XSUB) |
|
1311 | xsub = ctx.socket(zmq.XSUB) | |
1311 | xsub.bind('ipc:///tmp/socketTmp/a') |
|
1312 | xsub.bind('ipc:///tmp/socketTmp/a') | |
1312 | xpub = ctx.socket(zmq.XPUB) |
|
1313 | xpub = ctx.socket(zmq.XPUB) | |
1313 | xpub.bind('ipc:///tmp/socketTmp/b') |
|
1314 | xpub.bind('ipc:///tmp/socketTmp/b') | |
1314 |
|
1315 | |||
1315 | print("Controller Ready: Processes and proxy created") |
|
1316 | print("Controller Ready: Processes and proxy created") | |
1316 | zmq.proxy(xsub, xpub) |
|
1317 | zmq.proxy(xsub, xpub) | |
1317 |
|
1318 | |||
1318 |
|
1319 | |||
1319 |
|
1320 | |||
1320 | def run(self): |
|
1321 | def run(self): | |
1321 |
|
1322 | |||
1322 | log.success('Starting {}'.format(self.name), tag='') |
|
1323 | log.success('Starting {}'.format(self.name), tag='') | |
1323 | self.start_time = time.time() |
|
1324 | self.start_time = time.time() | |
1324 | self.createObjects() |
|
1325 | self.createObjects() | |
1325 | self.setProxyCom() |
|
1326 | self.setProxyCom() | |
1326 |
|
1327 | |||
1327 | # Iniciar todos los procesos .start(), monitoreo de procesos. ELiminar lo de abajo |
|
1328 | # Iniciar todos los procesos .start(), monitoreo de procesos. ELiminar lo de abajo | |
1328 |
|
1329 | |||
1329 | # Closing every process |
|
1330 | # Closing every process | |
1330 | log.success('{} finished (time: {}s)'.format( |
|
1331 | log.success('{} finished (time: {}s)'.format( | |
1331 | self.name, |
|
1332 | self.name, | |
1332 | time.time()-self.start_time)) No newline at end of file |
|
1333 | time.time()-self.start_time)) |
@@ -1,225 +1,232 | |||||
1 | ''' |
|
1 | ''' | |
2 | Created on Jul 9, 2014 |
|
2 | Created on Jul 9, 2014 | |
3 |
|
3 | |||
4 | @author: roj-idl71 |
|
4 | @author: roj-idl71 | |
5 | ''' |
|
5 | ''' | |
6 | import os |
|
6 | import os | |
7 | import datetime |
|
7 | import datetime | |
8 | import numpy |
|
8 | import numpy | |
9 |
|
9 | from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator #YONG | ||
|
10 | from schainpy.utils import log | |||
10 | from .figure import Figure |
|
11 | from .figure import Figure | |
11 |
|
12 | |||
|
13 | ||||
|
14 | @MPDecorator | |||
12 | class Scope(Figure): |
|
15 | class Scope(Figure): | |
13 |
|
16 | |||
14 | isConfig = None |
|
17 | isConfig = None | |
15 |
|
18 | |||
16 |
def __init__(self |
|
19 | def __init__(self):#, **kwargs): #YONG | |
17 |
Figure.__init__(self |
|
20 | Figure.__init__(self)#, **kwargs) | |
18 | self.isConfig = False |
|
21 | self.isConfig = False | |
19 | self.WIDTH = 300 |
|
22 | self.WIDTH = 300 | |
20 | self.HEIGHT = 200 |
|
23 | self.HEIGHT = 200 | |
21 | self.counter_imagwr = 0 |
|
24 | self.counter_imagwr = 0 | |
22 |
|
25 | |||
23 | def getSubplots(self): |
|
26 | def getSubplots(self): | |
24 |
|
27 | |||
25 | nrow = self.nplots |
|
28 | nrow = self.nplots | |
26 | ncol = 3 |
|
29 | ncol = 3 | |
27 | return nrow, ncol |
|
30 | return nrow, ncol | |
28 |
|
31 | |||
29 | def setup(self, id, nplots, wintitle, show): |
|
32 | def setup(self, id, nplots, wintitle, show): | |
30 |
|
33 | |||
31 | self.nplots = nplots |
|
34 | self.nplots = nplots | |
32 |
|
35 | |||
33 | self.createFigure(id=id, |
|
36 | self.createFigure(id=id, | |
34 | wintitle=wintitle, |
|
37 | wintitle=wintitle, | |
35 | show=show) |
|
38 | show=show) | |
36 |
|
39 | |||
37 | nrow,ncol = self.getSubplots() |
|
40 | nrow,ncol = self.getSubplots() | |
38 | colspan = 3 |
|
41 | colspan = 3 | |
39 | rowspan = 1 |
|
42 | rowspan = 1 | |
40 |
|
43 | |||
41 | for i in range(nplots): |
|
44 | for i in range(nplots): | |
42 | self.addAxes(nrow, ncol, i, 0, colspan, rowspan) |
|
45 | self.addAxes(nrow, ncol, i, 0, colspan, rowspan) | |
43 |
|
46 | |||
44 | def plot_iq(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax): |
|
47 | def plot_iq(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax): | |
45 | yreal = y[channelIndexList,:].real |
|
48 | yreal = y[channelIndexList,:].real | |
46 | yimag = y[channelIndexList,:].imag |
|
49 | yimag = y[channelIndexList,:].imag | |
47 |
|
50 | |||
48 | title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S")) |
|
51 | title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S")) | |
49 | xlabel = "Range (Km)" |
|
52 | xlabel = "Range (Km)" | |
50 | ylabel = "Intensity - IQ" |
|
53 | ylabel = "Intensity - IQ" | |
51 |
|
54 | |||
52 | if not self.isConfig: |
|
55 | if not self.isConfig: | |
53 | nplots = len(channelIndexList) |
|
56 | nplots = len(channelIndexList) | |
54 |
|
57 | |||
55 | self.setup(id=id, |
|
58 | self.setup(id=id, | |
56 | nplots=nplots, |
|
59 | nplots=nplots, | |
57 | wintitle='', |
|
60 | wintitle='', | |
58 | show=show) |
|
61 | show=show) | |
59 |
|
62 | |||
60 | if xmin == None: xmin = numpy.nanmin(x) |
|
63 | if xmin == None: xmin = numpy.nanmin(x) | |
61 | if xmax == None: xmax = numpy.nanmax(x) |
|
64 | if xmax == None: xmax = numpy.nanmax(x) | |
62 | if ymin == None: ymin = min(numpy.nanmin(yreal),numpy.nanmin(yimag)) |
|
65 | if ymin == None: ymin = min(numpy.nanmin(yreal),numpy.nanmin(yimag)) | |
63 | if ymax == None: ymax = max(numpy.nanmax(yreal),numpy.nanmax(yimag)) |
|
66 | if ymax == None: ymax = max(numpy.nanmax(yreal),numpy.nanmax(yimag)) | |
64 |
|
67 | |||
65 | self.isConfig = True |
|
68 | self.isConfig = True | |
66 |
|
69 | |||
67 | self.setWinTitle(title) |
|
70 | self.setWinTitle(title) | |
68 |
|
71 | |||
69 | for i in range(len(self.axesList)): |
|
72 | for i in range(len(self.axesList)): | |
70 | title = "Channel %d" %(i) |
|
73 | title = "Channel %d" %(i) | |
71 | axes = self.axesList[i] |
|
74 | axes = self.axesList[i] | |
72 |
|
75 | |||
73 | axes.pline(x, yreal[i,:], |
|
76 | axes.pline(x, yreal[i,:], | |
74 | xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, |
|
77 | xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, | |
75 | xlabel=xlabel, ylabel=ylabel, title=title) |
|
78 | xlabel=xlabel, ylabel=ylabel, title=title) | |
76 |
|
79 | |||
77 | axes.addpline(x, yimag[i,:], idline=1, color="red", linestyle="solid", lw=2) |
|
80 | axes.addpline(x, yimag[i,:], idline=1, color="red", linestyle="solid", lw=2) | |
78 |
|
81 | |||
79 | def plot_power(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax): |
|
82 | def plot_power(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax): | |
80 | y = y[channelIndexList,:] * numpy.conjugate(y[channelIndexList,:]) |
|
83 | y = y[channelIndexList,:] * numpy.conjugate(y[channelIndexList,:]) | |
81 | yreal = y.real |
|
84 | yreal = y.real | |
82 |
|
85 | |||
83 | title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S")) |
|
86 | title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S")) | |
84 | xlabel = "Range (Km)" |
|
87 | xlabel = "Range (Km)" | |
85 | ylabel = "Intensity" |
|
88 | ylabel = "Intensity" | |
86 |
|
89 | |||
87 | if not self.isConfig: |
|
90 | if not self.isConfig: | |
88 | nplots = len(channelIndexList) |
|
91 | nplots = len(channelIndexList) | |
89 |
|
92 | |||
90 | self.setup(id=id, |
|
93 | self.setup(id=id, | |
91 | nplots=nplots, |
|
94 | nplots=nplots, | |
92 | wintitle='', |
|
95 | wintitle='', | |
93 | show=show) |
|
96 | show=show) | |
94 |
|
97 | |||
95 | if xmin == None: xmin = numpy.nanmin(x) |
|
98 | if xmin == None: xmin = numpy.nanmin(x) | |
96 | if xmax == None: xmax = numpy.nanmax(x) |
|
99 | if xmax == None: xmax = numpy.nanmax(x) | |
97 | if ymin == None: ymin = numpy.nanmin(yreal) |
|
100 | if ymin == None: ymin = numpy.nanmin(yreal) | |
98 | if ymax == None: ymax = numpy.nanmax(yreal) |
|
101 | if ymax == None: ymax = numpy.nanmax(yreal) | |
99 |
|
102 | |||
100 | self.isConfig = True |
|
103 | self.isConfig = True | |
101 |
|
104 | |||
102 | self.setWinTitle(title) |
|
105 | self.setWinTitle(title) | |
103 |
|
106 | |||
104 | for i in range(len(self.axesList)): |
|
107 | for i in range(len(self.axesList)): | |
105 | title = "Channel %d" %(i) |
|
108 | title = "Channel %d" %(i) | |
106 | axes = self.axesList[i] |
|
109 | axes = self.axesList[i] | |
107 | ychannel = yreal[i,:] |
|
110 | ychannel = yreal[i,:] | |
108 | axes.pline(x, ychannel, |
|
111 | axes.pline(x, ychannel, | |
109 | xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, |
|
112 | xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, | |
110 | xlabel=xlabel, ylabel=ylabel, title=title) |
|
113 | xlabel=xlabel, ylabel=ylabel, title=title) | |
111 |
|
114 | |||
112 |
|
115 | |||
113 | def run(self, dataOut, id, wintitle="", channelList=None, |
|
116 | def run(self, dataOut, id, wintitle="", channelList=None, | |
114 | xmin=None, xmax=None, ymin=None, ymax=None, save=False, |
|
117 | xmin=None, xmax=None, ymin=None, ymax=None, save=False, | |
115 | figpath='./', figfile=None, show=True, wr_period=1, |
|
118 | figpath='./', figfile=None, show=True, wr_period=1, | |
116 | ftp=False, server=None, folder=None, username=None, password=None, type='power', **kwargs): |
|
119 | ftp=False, server=None, folder=None, username=None, password=None, type='power', **kwargs): | |
117 |
|
120 | |||
118 | """ |
|
121 | """ | |
119 |
|
122 | |||
120 | Input: |
|
123 | Input: | |
121 | dataOut : |
|
124 | dataOut : | |
122 | id : |
|
125 | id : | |
123 | wintitle : |
|
126 | wintitle : | |
124 | channelList : |
|
127 | channelList : | |
125 | xmin : None, |
|
128 | xmin : None, | |
126 | xmax : None, |
|
129 | xmax : None, | |
127 | ymin : None, |
|
130 | ymin : None, | |
128 | ymax : None, |
|
131 | ymax : None, | |
129 | """ |
|
132 | """ | |
|
133 | if dataOut.flagNoData: | |||
|
134 | return dataOut | |||
130 |
|
135 | |||
131 | if channelList == None: |
|
136 | if channelList == None: | |
132 | channelIndexList = dataOut.channelIndexList |
|
137 | channelIndexList = dataOut.channelIndexList | |
133 | else: |
|
138 | else: | |
134 | channelIndexList = [] |
|
139 | channelIndexList = [] | |
135 | for channel in channelList: |
|
140 | for channel in channelList: | |
136 | if channel not in dataOut.channelList: |
|
141 | if channel not in dataOut.channelList: | |
137 | raise ValueError("Channel %d is not in dataOut.channelList") |
|
142 | raise ValueError("Channel %d is not in dataOut.channelList") | |
138 | channelIndexList.append(dataOut.channelList.index(channel)) |
|
143 | channelIndexList.append(dataOut.channelList.index(channel)) | |
139 |
|
144 | |||
140 | thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0]) |
|
145 | thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0]) | |
141 |
|
146 | |||
142 | if dataOut.flagDataAsBlock: |
|
147 | if dataOut.flagDataAsBlock: | |
143 |
|
148 | |||
144 | for i in range(dataOut.nProfiles): |
|
149 | for i in range(dataOut.nProfiles): | |
145 |
|
150 | |||
146 | wintitle1 = wintitle + " [Profile = %d] " %i |
|
151 | wintitle1 = wintitle + " [Profile = %d] " %i | |
147 |
|
152 | |||
148 | if type == "power": |
|
153 | if type == "power": | |
149 | self.plot_power(dataOut.heightList, |
|
154 | self.plot_power(dataOut.heightList, | |
150 | dataOut.data[:,i,:], |
|
155 | dataOut.data[:,i,:], | |
151 | id, |
|
156 | id, | |
152 | channelIndexList, |
|
157 | channelIndexList, | |
153 | thisDatetime, |
|
158 | thisDatetime, | |
154 | wintitle1, |
|
159 | wintitle1, | |
155 | show, |
|
160 | show, | |
156 | xmin, |
|
161 | xmin, | |
157 | xmax, |
|
162 | xmax, | |
158 | ymin, |
|
163 | ymin, | |
159 | ymax) |
|
164 | ymax) | |
160 |
|
165 | |||
161 | if type == "iq": |
|
166 | if type == "iq": | |
162 | self.plot_iq(dataOut.heightList, |
|
167 | self.plot_iq(dataOut.heightList, | |
163 | dataOut.data[:,i,:], |
|
168 | dataOut.data[:,i,:], | |
164 | id, |
|
169 | id, | |
165 | channelIndexList, |
|
170 | channelIndexList, | |
166 | thisDatetime, |
|
171 | thisDatetime, | |
167 | wintitle1, |
|
172 | wintitle1, | |
168 | show, |
|
173 | show, | |
169 | xmin, |
|
174 | xmin, | |
170 | xmax, |
|
175 | xmax, | |
171 | ymin, |
|
176 | ymin, | |
172 | ymax) |
|
177 | ymax) | |
173 |
|
178 | |||
174 | self.draw() |
|
179 | self.draw() | |
175 |
|
180 | |||
176 | str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S") |
|
181 | str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S") | |
177 | figfile = self.getFilename(name = str_datetime) + "_" + str(i) |
|
182 | figfile = self.getFilename(name = str_datetime) + "_" + str(i) | |
178 |
|
183 | |||
179 | self.save(figpath=figpath, |
|
184 | self.save(figpath=figpath, | |
180 | figfile=figfile, |
|
185 | figfile=figfile, | |
181 | save=save, |
|
186 | save=save, | |
182 | ftp=ftp, |
|
187 | ftp=ftp, | |
183 | wr_period=wr_period, |
|
188 | wr_period=wr_period, | |
184 | thisDatetime=thisDatetime) |
|
189 | thisDatetime=thisDatetime) | |
185 |
|
190 | |||
186 | else: |
|
191 | else: | |
187 | wintitle += " [Profile = %d] " %dataOut.profileIndex |
|
192 | wintitle += " [Profile = %d] " %dataOut.profileIndex | |
188 |
|
193 | |||
189 | if type == "power": |
|
194 | if type == "power": | |
190 | self.plot_power(dataOut.heightList, |
|
195 | self.plot_power(dataOut.heightList, | |
191 | dataOut.data, |
|
196 | dataOut.data, | |
192 | id, |
|
197 | id, | |
193 | channelIndexList, |
|
198 | channelIndexList, | |
194 | thisDatetime, |
|
199 | thisDatetime, | |
195 | wintitle, |
|
200 | wintitle, | |
196 | show, |
|
201 | show, | |
197 | xmin, |
|
202 | xmin, | |
198 | xmax, |
|
203 | xmax, | |
199 | ymin, |
|
204 | ymin, | |
200 | ymax) |
|
205 | ymax) | |
201 |
|
206 | |||
202 | if type == "iq": |
|
207 | if type == "iq": | |
203 | self.plot_iq(dataOut.heightList, |
|
208 | self.plot_iq(dataOut.heightList, | |
204 | dataOut.data, |
|
209 | dataOut.data, | |
205 | id, |
|
210 | id, | |
206 | channelIndexList, |
|
211 | channelIndexList, | |
207 | thisDatetime, |
|
212 | thisDatetime, | |
208 | wintitle, |
|
213 | wintitle, | |
209 | show, |
|
214 | show, | |
210 | xmin, |
|
215 | xmin, | |
211 | xmax, |
|
216 | xmax, | |
212 | ymin, |
|
217 | ymin, | |
213 | ymax) |
|
218 | ymax) | |
214 |
|
219 | |||
215 | self.draw() |
|
220 | self.draw() | |
216 |
|
221 | |||
217 | str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S") + "_" + str(dataOut.profileIndex) |
|
222 | str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S") + "_" + str(dataOut.profileIndex) | |
218 | figfile = self.getFilename(name = str_datetime) |
|
223 | figfile = self.getFilename(name = str_datetime) | |
219 |
|
224 | |||
220 | self.save(figpath=figpath, |
|
225 | self.save(figpath=figpath, | |
221 | figfile=figfile, |
|
226 | figfile=figfile, | |
222 | save=save, |
|
227 | save=save, | |
223 | ftp=ftp, |
|
228 | ftp=ftp, | |
224 | wr_period=wr_period, |
|
229 | wr_period=wr_period, | |
225 | thisDatetime=thisDatetime) No newline at end of file |
|
230 | thisDatetime=thisDatetime) | |
|
231 | ||||
|
232 | return dataOut No newline at end of file |
@@ -1,764 +1,765 | |||||
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, MPDecorator | |
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 io import StringIO |
|
15 | from io import StringIO | |
16 | # from _sha import blocksize |
|
16 | # from _sha import blocksize | |
17 |
|
17 | |||
18 |
|
18 | @MPDecorator | ||
19 | class VoltageReader(JRODataReader, ProcessingUnit): |
|
19 | class VoltageReader(JRODataReader, ProcessingUnit): | |
20 | """ |
|
20 | """ | |
21 | Esta clase permite leer datos de voltage desde archivos en formato rawdata (.r). La lectura |
|
21 | Esta clase permite leer datos de voltage desde archivos en formato rawdata (.r). La lectura | |
22 | de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones: |
|
22 | de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones: | |
23 | perfiles*alturas*canales) son almacenados en la variable "buffer". |
|
23 | perfiles*alturas*canales) son almacenados en la variable "buffer". | |
24 |
|
24 | |||
25 | perfiles * alturas * canales |
|
25 | perfiles * alturas * canales | |
26 |
|
26 | |||
27 | Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader, |
|
27 | Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader, | |
28 | RadarControllerHeader y Voltage. Los tres primeros se usan para almacenar informacion de la |
|
28 | RadarControllerHeader y Voltage. Los tres primeros se usan para almacenar informacion de la | |
29 | cabecera de datos (metadata), y el cuarto (Voltage) para obtener y almacenar un perfil de |
|
29 | cabecera de datos (metadata), y el cuarto (Voltage) para obtener y almacenar un perfil de | |
30 | datos desde el "buffer" cada vez que se ejecute el metodo "getData". |
|
30 | datos desde el "buffer" cada vez que se ejecute el metodo "getData". | |
31 |
|
31 | |||
32 | Example: |
|
32 | Example: | |
33 |
|
33 | |||
34 | dpath = "/home/myuser/data" |
|
34 | dpath = "/home/myuser/data" | |
35 |
|
35 | |||
36 | startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0) |
|
36 | startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0) | |
37 |
|
37 | |||
38 | endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0) |
|
38 | endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0) | |
39 |
|
39 | |||
40 | readerObj = VoltageReader() |
|
40 | readerObj = VoltageReader() | |
41 |
|
41 | |||
42 | readerObj.setup(dpath, startTime, endTime) |
|
42 | readerObj.setup(dpath, startTime, endTime) | |
43 |
|
43 | |||
44 | while(True): |
|
44 | while(True): | |
45 |
|
45 | |||
46 | #to get one profile |
|
46 | #to get one profile | |
47 | profile = readerObj.getData() |
|
47 | profile = readerObj.getData() | |
48 |
|
48 | |||
49 | #print the profile |
|
49 | #print the profile | |
50 | print profile |
|
50 | print profile | |
51 |
|
51 | |||
52 | #If you want to see all datablock |
|
52 | #If you want to see all datablock | |
53 | print readerObj.datablock |
|
53 | print readerObj.datablock | |
54 |
|
54 | |||
55 | if readerObj.flagNoMoreFiles: |
|
55 | if readerObj.flagNoMoreFiles: | |
56 | break |
|
56 | break | |
57 |
|
57 | |||
58 | """ |
|
58 | """ | |
59 |
|
59 | |||
60 | ext = ".r" |
|
60 | ext = ".r" | |
61 |
|
61 | |||
62 | optchar = "D" |
|
62 | optchar = "D" | |
63 | dataOut = None |
|
63 | dataOut = None | |
64 |
|
64 | |||
65 |
def __init__(self |
|
65 | def __init__(self):#, **kwargs): | |
66 | """ |
|
66 | """ | |
67 | Inicializador de la clase VoltageReader para la lectura de datos de voltage. |
|
67 | Inicializador de la clase VoltageReader para la lectura de datos de voltage. | |
68 |
|
68 | |||
69 | Input: |
|
69 | Input: | |
70 | dataOut : Objeto de la clase Voltage. Este objeto sera utilizado para |
|
70 | dataOut : Objeto de la clase Voltage. Este objeto sera utilizado para | |
71 | almacenar un perfil de datos cada vez que se haga un requerimiento |
|
71 | almacenar un perfil de datos cada vez que se haga un requerimiento | |
72 | (getData). El perfil sera obtenido a partir del buffer de datos, |
|
72 | (getData). El perfil sera obtenido a partir del buffer de datos, | |
73 | si el buffer esta vacio se hara un nuevo proceso de lectura de un |
|
73 | si el buffer esta vacio se hara un nuevo proceso de lectura de un | |
74 | bloque de datos. |
|
74 | bloque de datos. | |
75 | Si este parametro no es pasado se creara uno internamente. |
|
75 | Si este parametro no es pasado se creara uno internamente. | |
76 |
|
76 | |||
77 | Variables afectadas: |
|
77 | Variables afectadas: | |
78 | self.dataOut |
|
78 | self.dataOut | |
79 |
|
79 | |||
80 | Return: |
|
80 | Return: | |
81 | None |
|
81 | None | |
82 | """ |
|
82 | """ | |
83 |
|
83 | |||
84 |
ProcessingUnit.__init__(self |
|
84 | ProcessingUnit.__init__(self)#, **kwargs) | |
85 |
|
85 | |||
86 | self.isConfig = False |
|
86 | self.isConfig = False | |
87 |
|
87 | |||
88 | self.datablock = None |
|
88 | self.datablock = None | |
89 |
|
89 | |||
90 | self.utc = 0 |
|
90 | self.utc = 0 | |
91 |
|
91 | |||
92 | self.ext = ".r" |
|
92 | self.ext = ".r" | |
93 |
|
93 | |||
94 | self.optchar = "D" |
|
94 | self.optchar = "D" | |
95 |
|
95 | |||
96 | self.basicHeaderObj = BasicHeader(LOCALTIME) |
|
96 | self.basicHeaderObj = BasicHeader(LOCALTIME) | |
97 |
|
97 | |||
98 | self.systemHeaderObj = SystemHeader() |
|
98 | self.systemHeaderObj = SystemHeader() | |
99 |
|
99 | |||
100 | self.radarControllerHeaderObj = RadarControllerHeader() |
|
100 | self.radarControllerHeaderObj = RadarControllerHeader() | |
101 |
|
101 | |||
102 | self.processingHeaderObj = ProcessingHeader() |
|
102 | self.processingHeaderObj = ProcessingHeader() | |
103 |
|
103 | |||
104 | self.online = 0 |
|
104 | self.online = 0 | |
105 |
|
105 | |||
106 | self.fp = None |
|
106 | self.fp = None | |
107 |
|
107 | |||
108 | self.idFile = None |
|
108 | self.idFile = None | |
109 |
|
109 | |||
110 | self.dtype = None |
|
110 | self.dtype = None | |
111 |
|
111 | |||
112 | self.fileSizeByHeader = None |
|
112 | self.fileSizeByHeader = None | |
113 |
|
113 | |||
114 | self.filenameList = [] |
|
114 | self.filenameList = [] | |
115 |
|
115 | |||
116 | self.filename = None |
|
116 | self.filename = None | |
117 |
|
117 | |||
118 | self.fileSize = None |
|
118 | self.fileSize = None | |
119 |
|
119 | |||
120 | self.firstHeaderSize = 0 |
|
120 | self.firstHeaderSize = 0 | |
121 |
|
121 | |||
122 | self.basicHeaderSize = 24 |
|
122 | self.basicHeaderSize = 24 | |
123 |
|
123 | |||
124 | self.pathList = [] |
|
124 | self.pathList = [] | |
125 |
|
125 | |||
126 | self.filenameList = [] |
|
126 | self.filenameList = [] | |
127 |
|
127 | |||
128 | self.lastUTTime = 0 |
|
128 | self.lastUTTime = 0 | |
129 |
|
129 | |||
130 | self.maxTimeStep = 30 |
|
130 | self.maxTimeStep = 30 | |
131 |
|
131 | |||
132 | self.flagNoMoreFiles = 0 |
|
132 | self.flagNoMoreFiles = 0 | |
133 |
|
133 | |||
134 | self.set = 0 |
|
134 | self.set = 0 | |
135 |
|
135 | |||
136 | self.path = None |
|
136 | self.path = None | |
137 |
|
137 | |||
138 | self.profileIndex = 2**32 - 1 |
|
138 | self.profileIndex = 2**32 - 1 | |
139 |
|
139 | |||
140 | self.delay = 3 # seconds |
|
140 | self.delay = 3 # seconds | |
141 |
|
141 | |||
142 | self.nTries = 3 # quantity tries |
|
142 | self.nTries = 3 # quantity tries | |
143 |
|
143 | |||
144 | self.nFiles = 3 # number of files for searching |
|
144 | self.nFiles = 3 # number of files for searching | |
145 |
|
145 | |||
146 | self.nReadBlocks = 0 |
|
146 | self.nReadBlocks = 0 | |
147 |
|
147 | |||
148 | self.flagIsNewFile = 1 |
|
148 | self.flagIsNewFile = 1 | |
149 |
|
149 | |||
150 | self.__isFirstTimeOnline = 1 |
|
150 | self.__isFirstTimeOnline = 1 | |
151 |
|
151 | |||
152 | # self.ippSeconds = 0 |
|
152 | # self.ippSeconds = 0 | |
153 |
|
153 | |||
154 | self.flagDiscontinuousBlock = 0 |
|
154 | self.flagDiscontinuousBlock = 0 | |
155 |
|
155 | |||
156 | self.flagIsNewBlock = 0 |
|
156 | self.flagIsNewBlock = 0 | |
157 |
|
157 | |||
158 | self.nTotalBlocks = 0 |
|
158 | self.nTotalBlocks = 0 | |
159 |
|
159 | |||
160 | self.blocksize = 0 |
|
160 | self.blocksize = 0 | |
161 |
|
161 | |||
162 | self.dataOut = self.createObjByDefault() |
|
162 | self.dataOut = self.createObjByDefault() | |
163 |
|
163 | |||
164 | self.nTxs = 1 |
|
164 | self.nTxs = 1 | |
165 |
|
165 | |||
166 | self.txIndex = 0 |
|
166 | self.txIndex = 0 | |
167 |
|
167 | |||
168 | def createObjByDefault(self): |
|
168 | def createObjByDefault(self): | |
169 |
|
169 | |||
170 | dataObj = Voltage() |
|
170 | dataObj = Voltage() | |
171 |
|
171 | |||
172 | return dataObj |
|
172 | return dataObj | |
173 |
|
173 | |||
174 | def __hasNotDataInBuffer(self): |
|
174 | def __hasNotDataInBuffer(self): | |
175 |
|
175 | |||
176 | if self.profileIndex >= self.processingHeaderObj.profilesPerBlock * self.nTxs: |
|
176 | if self.profileIndex >= self.processingHeaderObj.profilesPerBlock * self.nTxs: | |
177 | return 1 |
|
177 | return 1 | |
178 |
|
178 | |||
179 | return 0 |
|
179 | return 0 | |
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 * \ |
|
191 | pts2read = self.processingHeaderObj.profilesPerBlock * \ | |
192 | self.processingHeaderObj.nHeights * self.systemHeaderObj.nChannels |
|
192 | self.processingHeaderObj.nHeights * self.systemHeaderObj.nChannels | |
193 | self.blocksize = pts2read |
|
193 | self.blocksize = pts2read | |
194 |
|
194 | |||
195 | def readBlock(self): |
|
195 | def readBlock(self): | |
196 | """ |
|
196 | """ | |
197 | readBlock lee el bloque de datos desde la posicion actual del puntero del archivo |
|
197 | readBlock lee el bloque de datos desde la posicion actual del puntero del archivo | |
198 | (self.fp) y actualiza todos los parametros relacionados al bloque de datos |
|
198 | (self.fp) y actualiza todos los parametros relacionados al bloque de datos | |
199 | (metadata + data). La data leida es almacenada en el buffer y el contador del buffer |
|
199 | (metadata + data). La data leida es almacenada en el buffer y el contador del buffer | |
200 | es seteado a 0 |
|
200 | es seteado a 0 | |
201 |
|
201 | |||
202 | Inputs: |
|
202 | Inputs: | |
203 | None |
|
203 | None | |
204 |
|
204 | |||
205 | Return: |
|
205 | Return: | |
206 | None |
|
206 | None | |
207 |
|
207 | |||
208 | Affected: |
|
208 | Affected: | |
209 | self.profileIndex |
|
209 | self.profileIndex | |
210 | self.datablock |
|
210 | self.datablock | |
211 | self.flagIsNewFile |
|
211 | self.flagIsNewFile | |
212 | self.flagIsNewBlock |
|
212 | self.flagIsNewBlock | |
213 | self.nTotalBlocks |
|
213 | self.nTotalBlocks | |
214 |
|
214 | |||
215 | Exceptions: |
|
215 | Exceptions: | |
216 | Si un bloque leido no es un bloque valido |
|
216 | Si un bloque leido no es un bloque valido | |
217 | """ |
|
217 | """ | |
218 |
|
218 | |||
219 | # if self.server is not None: |
|
219 | # if self.server is not None: | |
220 | # self.zBlock = self.receiver.recv() |
|
220 | # self.zBlock = self.receiver.recv() | |
221 | # self.zHeader = self.zBlock[:24] |
|
221 | # self.zHeader = self.zBlock[:24] | |
222 | # self.zDataBlock = self.zBlock[24:] |
|
222 | # self.zDataBlock = self.zBlock[24:] | |
223 | # junk = numpy.fromstring(self.zDataBlock, numpy.dtype([('real','<i4'),('imag','<i4')])) |
|
223 | # junk = numpy.fromstring(self.zDataBlock, numpy.dtype([('real','<i4'),('imag','<i4')])) | |
224 | # self.processingHeaderObj.profilesPerBlock = 240 |
|
224 | # self.processingHeaderObj.profilesPerBlock = 240 | |
225 | # self.processingHeaderObj.nHeights = 248 |
|
225 | # self.processingHeaderObj.nHeights = 248 | |
226 | # self.systemHeaderObj.nChannels |
|
226 | # self.systemHeaderObj.nChannels | |
227 | # else: |
|
227 | # else: | |
228 | current_pointer_location = self.fp.tell() |
|
228 | current_pointer_location = self.fp.tell() | |
229 | junk = numpy.fromfile(self.fp, self.dtype, self.blocksize) |
|
229 | junk = numpy.fromfile(self.fp, self.dtype, self.blocksize) | |
230 |
|
230 | |||
231 | try: |
|
231 | try: | |
232 | junk = junk.reshape((self.processingHeaderObj.profilesPerBlock, |
|
232 | junk = junk.reshape((self.processingHeaderObj.profilesPerBlock, | |
233 | self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels)) |
|
233 | 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, |
|
239 | junk = junk.reshape((self.processingHeaderObj.profilesPerBlock, | |
240 | self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels)) |
|
240 | self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels)) | |
241 | # return 0 |
|
241 | # return 0 | |
242 |
|
242 | |||
243 | # Dimensions : nChannels, nProfiles, nSamples |
|
243 | # Dimensions : nChannels, nProfiles, nSamples | |
244 |
|
244 | |||
245 | junk = numpy.transpose(junk, (2, 0, 1)) |
|
245 | junk = numpy.transpose(junk, (2, 0, 1)) | |
246 | self.datablock = junk['real'] + junk['imag'] * 1j |
|
246 | self.datablock = junk['real'] + junk['imag'] * 1j | |
247 |
|
247 | |||
248 | self.profileIndex = 0 |
|
248 | self.profileIndex = 0 | |
249 |
|
249 | |||
250 | self.flagIsNewFile = 0 |
|
250 | self.flagIsNewFile = 0 | |
251 | self.flagIsNewBlock = 1 |
|
251 | self.flagIsNewBlock = 1 | |
252 |
|
252 | |||
253 | self.nTotalBlocks += 1 |
|
253 | self.nTotalBlocks += 1 | |
254 | self.nReadBlocks += 1 |
|
254 | self.nReadBlocks += 1 | |
255 |
|
255 | |||
256 | return 1 |
|
256 | return 1 | |
257 |
|
257 | |||
258 | def getFirstHeader(self): |
|
258 | def getFirstHeader(self): | |
259 |
|
259 | |||
260 | self.getBasicHeader() |
|
260 | self.getBasicHeader() | |
261 |
|
261 | |||
262 | self.dataOut.processingHeaderObj = self.processingHeaderObj.copy() |
|
262 | self.dataOut.processingHeaderObj = self.processingHeaderObj.copy() | |
263 |
|
263 | |||
264 | self.dataOut.systemHeaderObj = self.systemHeaderObj.copy() |
|
264 | self.dataOut.systemHeaderObj = self.systemHeaderObj.copy() | |
265 |
|
265 | |||
266 | self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy() |
|
266 | self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy() | |
267 |
|
267 | |||
268 | if self.nTxs > 1: |
|
268 | if self.nTxs > 1: | |
269 | self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs |
|
269 | self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs | |
270 | # Time interval and code are propierties of dataOut. Its value depends of radarControllerHeaderObj. |
|
270 | # Time interval and code are propierties of dataOut. Its value depends of radarControllerHeaderObj. | |
271 |
|
271 | |||
272 | # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt |
|
272 | # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt | |
273 | # |
|
273 | # | |
274 | # if self.radarControllerHeaderObj.code is not None: |
|
274 | # if self.radarControllerHeaderObj.code is not None: | |
275 | # |
|
275 | # | |
276 | # self.dataOut.nCode = self.radarControllerHeaderObj.nCode |
|
276 | # self.dataOut.nCode = self.radarControllerHeaderObj.nCode | |
277 | # |
|
277 | # | |
278 | # self.dataOut.nBaud = self.radarControllerHeaderObj.nBaud |
|
278 | # self.dataOut.nBaud = self.radarControllerHeaderObj.nBaud | |
279 | # |
|
279 | # | |
280 | # self.dataOut.code = self.radarControllerHeaderObj.code |
|
280 | # self.dataOut.code = self.radarControllerHeaderObj.code | |
281 |
|
281 | |||
282 | self.dataOut.dtype = self.dtype |
|
282 | self.dataOut.dtype = self.dtype | |
283 |
|
283 | |||
284 | self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock |
|
284 | self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock | |
285 |
|
285 | |||
286 | self.dataOut.heightList = numpy.arange( |
|
286 | self.dataOut.heightList = numpy.arange( | |
287 | self.processingHeaderObj.nHeights) * self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight |
|
287 | self.processingHeaderObj.nHeights) * self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight | |
288 |
|
288 | |||
289 | self.dataOut.channelList = list(range(self.systemHeaderObj.nChannels)) |
|
289 | self.dataOut.channelList = list(range(self.systemHeaderObj.nChannels)) | |
290 |
|
290 | |||
291 | self.dataOut.nCohInt = self.processingHeaderObj.nCohInt |
|
291 | self.dataOut.nCohInt = self.processingHeaderObj.nCohInt | |
292 |
|
292 | |||
293 | # asumo q la data no esta decodificada |
|
293 | # asumo q la data no esta decodificada | |
294 | self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode |
|
294 | self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode | |
295 |
|
295 | |||
296 | # asumo q la data no esta sin flip |
|
296 | # asumo q la data no esta sin flip | |
297 | self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip |
|
297 | self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip | |
298 |
|
298 | |||
299 | self.dataOut.flagShiftFFT = self.processingHeaderObj.shif_fft |
|
299 | self.dataOut.flagShiftFFT = self.processingHeaderObj.shif_fft | |
300 |
|
300 | |||
301 | def reshapeData(self): |
|
301 | def reshapeData(self): | |
302 |
|
302 | |||
303 | if self.nTxs < 0: |
|
303 | if self.nTxs < 0: | |
304 | return |
|
304 | return | |
305 |
|
305 | |||
306 | if self.nTxs == 1: |
|
306 | if self.nTxs == 1: | |
307 | return |
|
307 | return | |
308 |
|
308 | |||
309 | if self.nTxs < 1 and self.processingHeaderObj.profilesPerBlock % (1. / self.nTxs) != 0: |
|
309 | if self.nTxs < 1 and self.processingHeaderObj.profilesPerBlock % (1. / self.nTxs) != 0: | |
310 | raise ValueError("1./nTxs (=%f), should be a multiple of nProfiles (=%d)" % ( |
|
310 | raise ValueError("1./nTxs (=%f), should be a multiple of nProfiles (=%d)" % ( | |
311 | 1. / self.nTxs, self.processingHeaderObj.profilesPerBlock)) |
|
311 | 1. / self.nTxs, self.processingHeaderObj.profilesPerBlock)) | |
312 |
|
312 | |||
313 | if self.nTxs > 1 and self.processingHeaderObj.nHeights % self.nTxs != 0: |
|
313 | if self.nTxs > 1 and self.processingHeaderObj.nHeights % self.nTxs != 0: | |
314 | raise ValueError("nTxs (=%d), should be a multiple of nHeights (=%d)" % ( |
|
314 | raise ValueError("nTxs (=%d), should be a multiple of nHeights (=%d)" % ( | |
315 | self.nTxs, self.processingHeaderObj.nHeights)) |
|
315 | self.nTxs, self.processingHeaderObj.nHeights)) | |
316 |
|
316 | |||
317 | self.datablock = self.datablock.reshape( |
|
317 | self.datablock = self.datablock.reshape( | |
318 | (self.systemHeaderObj.nChannels, self.processingHeaderObj.profilesPerBlock * self.nTxs, self.processingHeaderObj.nHeights / self.nTxs)) |
|
318 | (self.systemHeaderObj.nChannels, self.processingHeaderObj.profilesPerBlock * self.nTxs, self.processingHeaderObj.nHeights / self.nTxs)) | |
319 |
|
319 | |||
320 | self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock * self.nTxs |
|
320 | self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock * self.nTxs | |
321 | self.dataOut.heightList = numpy.arange(self.processingHeaderObj.nHeights / self.nTxs) * \ |
|
321 | self.dataOut.heightList = numpy.arange(self.processingHeaderObj.nHeights / self.nTxs) * \ | |
322 | self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight |
|
322 | self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight | |
323 | self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs |
|
323 | self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs | |
324 |
|
324 | |||
325 | return |
|
325 | return | |
326 |
|
326 | |||
327 | def readFirstHeaderFromServer(self): |
|
327 | def readFirstHeaderFromServer(self): | |
328 |
|
328 | |||
329 | self.getFirstHeader() |
|
329 | self.getFirstHeader() | |
330 |
|
330 | |||
331 | self.firstHeaderSize = self.basicHeaderObj.size |
|
331 | self.firstHeaderSize = self.basicHeaderObj.size | |
332 |
|
332 | |||
333 | datatype = int(numpy.log2((self.processingHeaderObj.processFlags & |
|
333 | datatype = int(numpy.log2((self.processingHeaderObj.processFlags & | |
334 | PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR)) |
|
334 | PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR)) | |
335 | if datatype == 0: |
|
335 | if datatype == 0: | |
336 | datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')]) |
|
336 | datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')]) | |
337 | elif datatype == 1: |
|
337 | elif datatype == 1: | |
338 | datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')]) |
|
338 | datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')]) | |
339 | elif datatype == 2: |
|
339 | elif datatype == 2: | |
340 | datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')]) |
|
340 | datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')]) | |
341 | elif datatype == 3: |
|
341 | elif datatype == 3: | |
342 | datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')]) |
|
342 | datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')]) | |
343 | elif datatype == 4: |
|
343 | elif datatype == 4: | |
344 | datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')]) |
|
344 | datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')]) | |
345 | elif datatype == 5: |
|
345 | elif datatype == 5: | |
346 | datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')]) |
|
346 | datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')]) | |
347 | else: |
|
347 | else: | |
348 | raise ValueError('Data type was not defined') |
|
348 | raise ValueError('Data type was not defined') | |
349 |
|
349 | |||
350 | self.dtype = datatype_str |
|
350 | self.dtype = datatype_str | |
351 | #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c |
|
351 | #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c | |
352 | self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \ |
|
352 | self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \ | |
353 | self.firstHeaderSize + self.basicHeaderSize * \ |
|
353 | self.firstHeaderSize + self.basicHeaderSize * \ | |
354 | (self.processingHeaderObj.dataBlocksPerFile - 1) |
|
354 | (self.processingHeaderObj.dataBlocksPerFile - 1) | |
355 | # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels) |
|
355 | # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels) | |
356 | # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels) |
|
356 | # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels) | |
357 | self.getBlockDimension() |
|
357 | self.getBlockDimension() | |
358 |
|
358 | |||
359 | def getFromServer(self): |
|
359 | def getFromServer(self): | |
360 | self.flagDiscontinuousBlock = 0 |
|
360 | self.flagDiscontinuousBlock = 0 | |
361 | self.profileIndex = 0 |
|
361 | self.profileIndex = 0 | |
362 | self.flagIsNewBlock = 1 |
|
362 | self.flagIsNewBlock = 1 | |
363 | self.dataOut.flagNoData = False |
|
363 | self.dataOut.flagNoData = False | |
364 | self.nTotalBlocks += 1 |
|
364 | self.nTotalBlocks += 1 | |
365 | self.nReadBlocks += 1 |
|
365 | self.nReadBlocks += 1 | |
366 | self.blockPointer = 0 |
|
366 | self.blockPointer = 0 | |
367 |
|
367 | |||
368 | block = self.receiver.recv() |
|
368 | block = self.receiver.recv() | |
369 |
|
369 | |||
370 | self.basicHeaderObj.read(block[self.blockPointer:]) |
|
370 | self.basicHeaderObj.read(block[self.blockPointer:]) | |
371 | self.blockPointer += self.basicHeaderObj.length |
|
371 | self.blockPointer += self.basicHeaderObj.length | |
372 | self.systemHeaderObj.read(block[self.blockPointer:]) |
|
372 | self.systemHeaderObj.read(block[self.blockPointer:]) | |
373 | self.blockPointer += self.systemHeaderObj.length |
|
373 | self.blockPointer += self.systemHeaderObj.length | |
374 | self.radarControllerHeaderObj.read(block[self.blockPointer:]) |
|
374 | self.radarControllerHeaderObj.read(block[self.blockPointer:]) | |
375 | self.blockPointer += self.radarControllerHeaderObj.length |
|
375 | self.blockPointer += self.radarControllerHeaderObj.length | |
376 | self.processingHeaderObj.read(block[self.blockPointer:]) |
|
376 | self.processingHeaderObj.read(block[self.blockPointer:]) | |
377 | self.blockPointer += self.processingHeaderObj.length |
|
377 | self.blockPointer += self.processingHeaderObj.length | |
378 | self.readFirstHeaderFromServer() |
|
378 | self.readFirstHeaderFromServer() | |
379 |
|
379 | |||
380 | timestamp = self.basicHeaderObj.get_datatime() |
|
380 | timestamp = self.basicHeaderObj.get_datatime() | |
381 | print('[Reading] - Block {} - {}'.format(self.nTotalBlocks, timestamp)) |
|
381 | print('[Reading] - Block {} - {}'.format(self.nTotalBlocks, timestamp)) | |
382 | current_pointer_location = self.blockPointer |
|
382 | current_pointer_location = self.blockPointer | |
383 | junk = numpy.fromstring( |
|
383 | junk = numpy.fromstring( | |
384 | block[self.blockPointer:], self.dtype, self.blocksize) |
|
384 | block[self.blockPointer:], self.dtype, self.blocksize) | |
385 |
|
385 | |||
386 | try: |
|
386 | try: | |
387 | junk = junk.reshape((self.processingHeaderObj.profilesPerBlock, |
|
387 | junk = junk.reshape((self.processingHeaderObj.profilesPerBlock, | |
388 | self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels)) |
|
388 | self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels)) | |
389 | except: |
|
389 | except: | |
390 | # print "The read block (%3d) has not enough data" %self.nReadBlocks |
|
390 | # print "The read block (%3d) has not enough data" %self.nReadBlocks | |
391 | if self.waitDataBlock(pointer_location=current_pointer_location): |
|
391 | if self.waitDataBlock(pointer_location=current_pointer_location): | |
392 | junk = numpy.fromstring( |
|
392 | junk = numpy.fromstring( | |
393 | block[self.blockPointer:], self.dtype, self.blocksize) |
|
393 | block[self.blockPointer:], self.dtype, self.blocksize) | |
394 | junk = junk.reshape((self.processingHeaderObj.profilesPerBlock, |
|
394 | junk = junk.reshape((self.processingHeaderObj.profilesPerBlock, | |
395 | self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels)) |
|
395 | self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels)) | |
396 | # return 0 |
|
396 | # return 0 | |
397 |
|
397 | |||
398 | # Dimensions : nChannels, nProfiles, nSamples |
|
398 | # Dimensions : nChannels, nProfiles, nSamples | |
399 |
|
399 | |||
400 | junk = numpy.transpose(junk, (2, 0, 1)) |
|
400 | junk = numpy.transpose(junk, (2, 0, 1)) | |
401 | self.datablock = junk['real'] + junk['imag'] * 1j |
|
401 | self.datablock = junk['real'] + junk['imag'] * 1j | |
402 | self.profileIndex = 0 |
|
402 | self.profileIndex = 0 | |
403 | if self.selBlocksize == None: |
|
403 | if self.selBlocksize == None: | |
404 | self.selBlocksize = self.dataOut.nProfiles |
|
404 | self.selBlocksize = self.dataOut.nProfiles | |
405 | if self.selBlocktime != None: |
|
405 | if self.selBlocktime != None: | |
406 | if self.dataOut.nCohInt is not None: |
|
406 | if self.dataOut.nCohInt is not None: | |
407 | nCohInt = self.dataOut.nCohInt |
|
407 | nCohInt = self.dataOut.nCohInt | |
408 | else: |
|
408 | else: | |
409 | nCohInt = 1 |
|
409 | nCohInt = 1 | |
410 | self.selBlocksize = int(self.dataOut.nProfiles * round(self.selBlocktime / ( |
|
410 | self.selBlocksize = int(self.dataOut.nProfiles * round(self.selBlocktime / ( | |
411 | nCohInt * self.dataOut.ippSeconds * self.dataOut.nProfiles))) |
|
411 | nCohInt * self.dataOut.ippSeconds * self.dataOut.nProfiles))) | |
412 | self.dataOut.data = self.datablock[:, |
|
412 | self.dataOut.data = self.datablock[:, | |
413 | self.profileIndex:self.profileIndex + self.selBlocksize, :] |
|
413 | self.profileIndex:self.profileIndex + self.selBlocksize, :] | |
414 | datasize = self.dataOut.data.shape[1] |
|
414 | datasize = self.dataOut.data.shape[1] | |
415 | if datasize < self.selBlocksize: |
|
415 | if datasize < self.selBlocksize: | |
416 | buffer = numpy.zeros( |
|
416 | buffer = numpy.zeros( | |
417 | (self.dataOut.data.shape[0], self.selBlocksize, self.dataOut.data.shape[2]), dtype='complex') |
|
417 | (self.dataOut.data.shape[0], self.selBlocksize, self.dataOut.data.shape[2]), dtype='complex') | |
418 | buffer[:, :datasize, :] = self.dataOut.data |
|
418 | buffer[:, :datasize, :] = self.dataOut.data | |
419 | self.dataOut.data = buffer |
|
419 | self.dataOut.data = buffer | |
420 | self.profileIndex = blockIndex |
|
420 | self.profileIndex = blockIndex | |
421 |
|
421 | |||
422 | self.dataOut.flagDataAsBlock = True |
|
422 | self.dataOut.flagDataAsBlock = True | |
423 | self.flagIsNewBlock = 1 |
|
423 | self.flagIsNewBlock = 1 | |
424 | self.dataOut.realtime = self.online |
|
424 | self.dataOut.realtime = self.online | |
425 |
|
425 | |||
426 | return self.dataOut.data |
|
426 | return self.dataOut.data | |
427 |
|
427 | |||
428 | def getData(self): |
|
428 | def getData(self): | |
429 | """ |
|
429 | """ | |
430 | getData obtiene una unidad de datos del buffer de lectura, un perfil, y la copia al objeto self.dataOut |
|
430 | getData obtiene una unidad de datos del buffer de lectura, un perfil, y la copia al objeto self.dataOut | |
431 | del tipo "Voltage" con todos los parametros asociados a este (metadata). cuando no hay datos |
|
431 | del tipo "Voltage" con todos los parametros asociados a este (metadata). cuando no hay datos | |
432 | en el buffer de lectura es necesario hacer una nueva lectura de los bloques de datos usando |
|
432 | en el buffer de lectura es necesario hacer una nueva lectura de los bloques de datos usando | |
433 | "readNextBlock" |
|
433 | "readNextBlock" | |
434 |
|
434 | |||
435 | Ademas incrementa el contador del buffer "self.profileIndex" en 1. |
|
435 | Ademas incrementa el contador del buffer "self.profileIndex" en 1. | |
436 |
|
436 | |||
437 | Return: |
|
437 | Return: | |
438 |
|
438 | |||
439 | Si el flag self.getByBlock ha sido seteado el bloque completo es copiado a self.dataOut y el self.profileIndex |
|
439 | Si el flag self.getByBlock ha sido seteado el bloque completo es copiado a self.dataOut y el self.profileIndex | |
440 | es igual al total de perfiles leidos desde el archivo. |
|
440 | es igual al total de perfiles leidos desde el archivo. | |
441 |
|
441 | |||
442 | Si self.getByBlock == False: |
|
442 | Si self.getByBlock == False: | |
443 |
|
443 | |||
444 | self.dataOut.data = buffer[:, thisProfile, :] |
|
444 | self.dataOut.data = buffer[:, thisProfile, :] | |
445 |
|
445 | |||
446 | shape = [nChannels, nHeis] |
|
446 | shape = [nChannels, nHeis] | |
447 |
|
447 | |||
448 | Si self.getByBlock == True: |
|
448 | Si self.getByBlock == True: | |
449 |
|
449 | |||
450 | self.dataOut.data = buffer[:, :, :] |
|
450 | self.dataOut.data = buffer[:, :, :] | |
451 |
|
451 | |||
452 | shape = [nChannels, nProfiles, nHeis] |
|
452 | shape = [nChannels, nProfiles, nHeis] | |
453 |
|
453 | |||
454 | Variables afectadas: |
|
454 | Variables afectadas: | |
455 | self.dataOut |
|
455 | self.dataOut | |
456 | self.profileIndex |
|
456 | self.profileIndex | |
457 |
|
457 | |||
458 | Affected: |
|
458 | Affected: | |
459 | self.dataOut |
|
459 | self.dataOut | |
460 | self.profileIndex |
|
460 | self.profileIndex | |
461 | self.flagDiscontinuousBlock |
|
461 | self.flagDiscontinuousBlock | |
462 | self.flagIsNewBlock |
|
462 | self.flagIsNewBlock | |
463 | """ |
|
463 | """ | |
464 | if self.flagNoMoreFiles: |
|
464 | if self.flagNoMoreFiles: | |
465 | self.dataOut.flagNoData = True |
|
465 | self.dataOut.flagNoData = True | |
466 | print('Process finished') |
|
466 | print('Process finished') | |
467 | return 0 |
|
467 | return 0 | |
468 | self.flagDiscontinuousBlock = 0 |
|
468 | self.flagDiscontinuousBlock = 0 | |
469 | self.flagIsNewBlock = 0 |
|
469 | self.flagIsNewBlock = 0 | |
470 | if self.__hasNotDataInBuffer(): |
|
470 | if self.__hasNotDataInBuffer(): | |
471 | if not(self.readNextBlock()): |
|
471 | if not(self.readNextBlock()): | |
472 | return 0 |
|
472 | return 0 | |
473 |
|
473 | |||
474 | self.getFirstHeader() |
|
474 | self.getFirstHeader() | |
475 |
|
475 | |||
476 | self.reshapeData() |
|
476 | self.reshapeData() | |
477 | if self.datablock is None: |
|
477 | if self.datablock is None: | |
478 | self.dataOut.flagNoData = True |
|
478 | self.dataOut.flagNoData = True | |
479 | return 0 |
|
479 | return 0 | |
480 |
|
480 | |||
481 | if not self.getByBlock: |
|
481 | if not self.getByBlock: | |
482 |
|
482 | |||
483 | """ |
|
483 | """ | |
484 | Return profile by profile |
|
484 | Return profile by profile | |
485 |
|
485 | |||
486 | If nTxs > 1 then one profile is divided by nTxs and number of total |
|
486 | If nTxs > 1 then one profile is divided by nTxs and number of total | |
487 | blocks is increased by nTxs (nProfiles *= nTxs) |
|
487 | blocks is increased by nTxs (nProfiles *= nTxs) | |
488 | """ |
|
488 | """ | |
489 | self.dataOut.flagDataAsBlock = False |
|
489 | self.dataOut.flagDataAsBlock = False | |
490 | self.dataOut.data = self.datablock[:, self.profileIndex, :] |
|
490 | self.dataOut.data = self.datablock[:, self.profileIndex, :] | |
491 | self.dataOut.profileIndex = self.profileIndex |
|
491 | self.dataOut.profileIndex = self.profileIndex | |
492 |
|
492 | |||
493 | self.profileIndex += 1 |
|
493 | self.profileIndex += 1 | |
494 |
|
494 | |||
495 | # elif self.selBlocksize==None or self.selBlocksize==self.dataOut.nProfiles: |
|
495 | # elif self.selBlocksize==None or self.selBlocksize==self.dataOut.nProfiles: | |
496 | # """ |
|
496 | # """ | |
497 | # Return all block |
|
497 | # Return all block | |
498 | # """ |
|
498 | # """ | |
499 | # self.dataOut.flagDataAsBlock = True |
|
499 | # self.dataOut.flagDataAsBlock = True | |
500 | # self.dataOut.data = self.datablock |
|
500 | # self.dataOut.data = self.datablock | |
501 | # self.dataOut.profileIndex = self.dataOut.nProfiles - 1 |
|
501 | # self.dataOut.profileIndex = self.dataOut.nProfiles - 1 | |
502 | # |
|
502 | # | |
503 | # self.profileIndex = self.dataOut.nProfiles |
|
503 | # self.profileIndex = self.dataOut.nProfiles | |
504 |
|
504 | |||
505 | else: |
|
505 | else: | |
506 | """ |
|
506 | """ | |
507 | Return a block |
|
507 | Return a block | |
508 | """ |
|
508 | """ | |
509 | if self.selBlocksize == None: |
|
509 | if self.selBlocksize == None: | |
510 | self.selBlocksize = self.dataOut.nProfiles |
|
510 | self.selBlocksize = self.dataOut.nProfiles | |
511 | if self.selBlocktime != None: |
|
511 | if self.selBlocktime != None: | |
512 | if self.dataOut.nCohInt is not None: |
|
512 | if self.dataOut.nCohInt is not None: | |
513 | nCohInt = self.dataOut.nCohInt |
|
513 | nCohInt = self.dataOut.nCohInt | |
514 | else: |
|
514 | else: | |
515 | nCohInt = 1 |
|
515 | nCohInt = 1 | |
516 | self.selBlocksize = int(self.dataOut.nProfiles * round(self.selBlocktime / ( |
|
516 | self.selBlocksize = int(self.dataOut.nProfiles * round(self.selBlocktime / ( | |
517 | nCohInt * self.dataOut.ippSeconds * self.dataOut.nProfiles))) |
|
517 | nCohInt * self.dataOut.ippSeconds * self.dataOut.nProfiles))) | |
518 |
|
518 | |||
519 | self.dataOut.data = self.datablock[:, |
|
519 | self.dataOut.data = self.datablock[:, | |
520 | self.profileIndex:self.profileIndex + self.selBlocksize, :] |
|
520 | self.profileIndex:self.profileIndex + self.selBlocksize, :] | |
521 | self.profileIndex += self.selBlocksize |
|
521 | self.profileIndex += self.selBlocksize | |
522 | datasize = self.dataOut.data.shape[1] |
|
522 | datasize = self.dataOut.data.shape[1] | |
523 |
|
523 | |||
524 | if datasize < self.selBlocksize: |
|
524 | if datasize < self.selBlocksize: | |
525 | buffer = numpy.zeros( |
|
525 | buffer = numpy.zeros( | |
526 | (self.dataOut.data.shape[0], self.selBlocksize, self.dataOut.data.shape[2]), dtype='complex') |
|
526 | (self.dataOut.data.shape[0], self.selBlocksize, self.dataOut.data.shape[2]), dtype='complex') | |
527 | buffer[:, :datasize, :] = self.dataOut.data |
|
527 | buffer[:, :datasize, :] = self.dataOut.data | |
528 |
|
528 | |||
529 | while datasize < self.selBlocksize: # Not enough profiles to fill the block |
|
529 | while datasize < self.selBlocksize: # Not enough profiles to fill the block | |
530 | if not(self.readNextBlock()): |
|
530 | if not(self.readNextBlock()): | |
531 | return 0 |
|
531 | return 0 | |
532 | self.getFirstHeader() |
|
532 | self.getFirstHeader() | |
533 | self.reshapeData() |
|
533 | self.reshapeData() | |
534 | if self.datablock is None: |
|
534 | if self.datablock is None: | |
535 | self.dataOut.flagNoData = True |
|
535 | self.dataOut.flagNoData = True | |
536 | return 0 |
|
536 | return 0 | |
537 | # stack data |
|
537 | # stack data | |
538 | blockIndex = self.selBlocksize - datasize |
|
538 | blockIndex = self.selBlocksize - datasize | |
539 | datablock1 = self.datablock[:, :blockIndex, :] |
|
539 | datablock1 = self.datablock[:, :blockIndex, :] | |
540 |
|
540 | |||
541 | buffer[:, datasize:datasize + |
|
541 | buffer[:, datasize:datasize + | |
542 | datablock1.shape[1], :] = datablock1 |
|
542 | datablock1.shape[1], :] = datablock1 | |
543 | datasize += datablock1.shape[1] |
|
543 | datasize += datablock1.shape[1] | |
544 |
|
544 | |||
545 | self.dataOut.data = buffer |
|
545 | self.dataOut.data = buffer | |
546 | self.profileIndex = blockIndex |
|
546 | self.profileIndex = blockIndex | |
547 |
|
547 | |||
548 | self.dataOut.flagDataAsBlock = True |
|
548 | self.dataOut.flagDataAsBlock = True | |
549 | self.dataOut.nProfiles = self.dataOut.data.shape[1] |
|
549 | self.dataOut.nProfiles = self.dataOut.data.shape[1] | |
550 |
|
550 | |||
551 | self.dataOut.flagNoData = False |
|
551 | self.dataOut.flagNoData = False | |
552 |
|
552 | |||
553 | self.getBasicHeader() |
|
553 | self.getBasicHeader() | |
554 |
|
554 | |||
555 | self.dataOut.realtime = self.online |
|
555 | self.dataOut.realtime = self.online | |
556 |
|
556 | |||
557 | return self.dataOut.data |
|
557 | return self.dataOut.data | |
558 |
|
558 | |||
559 |
|
559 | |||
560 | class VoltageWriter(JRODataWriter, Operation): |
|
560 | class VoltageWriter(JRODataWriter, Operation): | |
561 | """ |
|
561 | """ | |
562 | Esta clase permite escribir datos de voltajes a archivos procesados (.r). La escritura |
|
562 | Esta clase permite escribir datos de voltajes a archivos procesados (.r). La escritura | |
563 | de los datos siempre se realiza por bloques. |
|
563 | de los datos siempre se realiza por bloques. | |
564 | """ |
|
564 | """ | |
565 |
|
565 | |||
566 | ext = ".r" |
|
566 | ext = ".r" | |
567 |
|
567 | |||
568 | optchar = "D" |
|
568 | optchar = "D" | |
569 |
|
569 | |||
570 | shapeBuffer = None |
|
570 | shapeBuffer = None | |
571 |
|
571 | |||
572 | def __init__(self, **kwargs): |
|
572 | def __init__(self, **kwargs): | |
573 | """ |
|
573 | """ | |
574 | Inicializador de la clase VoltageWriter para la escritura de datos de espectros. |
|
574 | Inicializador de la clase VoltageWriter para la escritura de datos de espectros. | |
575 |
|
575 | |||
576 | Affected: |
|
576 | Affected: | |
577 | self.dataOut |
|
577 | self.dataOut | |
578 |
|
578 | |||
579 | Return: None |
|
579 | Return: None | |
580 | """ |
|
580 | """ | |
581 | Operation.__init__(self, **kwargs) |
|
581 | Operation.__init__(self, **kwargs) | |
582 |
|
582 | |||
583 | self.nTotalBlocks = 0 |
|
583 | self.nTotalBlocks = 0 | |
584 |
|
584 | |||
585 | self.profileIndex = 0 |
|
585 | self.profileIndex = 0 | |
586 |
|
586 | |||
587 | self.isConfig = False |
|
587 | self.isConfig = False | |
588 |
|
588 | |||
589 | self.fp = None |
|
589 | self.fp = None | |
590 |
|
590 | |||
591 | self.flagIsNewFile = 1 |
|
591 | self.flagIsNewFile = 1 | |
592 |
|
592 | |||
593 | self.blockIndex = 0 |
|
593 | self.blockIndex = 0 | |
594 |
|
594 | |||
595 | self.flagIsNewBlock = 0 |
|
595 | self.flagIsNewBlock = 0 | |
596 |
|
596 | |||
597 | self.setFile = None |
|
597 | self.setFile = None | |
598 |
|
598 | |||
599 | self.dtype = None |
|
599 | self.dtype = None | |
600 |
|
600 | |||
601 | self.path = None |
|
601 | self.path = None | |
602 |
|
602 | |||
603 | self.filename = None |
|
603 | self.filename = None | |
604 |
|
604 | |||
605 | self.basicHeaderObj = BasicHeader(LOCALTIME) |
|
605 | self.basicHeaderObj = BasicHeader(LOCALTIME) | |
606 |
|
606 | |||
607 | self.systemHeaderObj = SystemHeader() |
|
607 | self.systemHeaderObj = SystemHeader() | |
608 |
|
608 | |||
609 | self.radarControllerHeaderObj = RadarControllerHeader() |
|
609 | self.radarControllerHeaderObj = RadarControllerHeader() | |
610 |
|
610 | |||
611 | self.processingHeaderObj = ProcessingHeader() |
|
611 | self.processingHeaderObj = ProcessingHeader() | |
612 |
|
612 | |||
613 | def hasAllDataInBuffer(self): |
|
613 | def hasAllDataInBuffer(self): | |
614 | if self.profileIndex >= self.processingHeaderObj.profilesPerBlock: |
|
614 | if self.profileIndex >= self.processingHeaderObj.profilesPerBlock: | |
615 | return 1 |
|
615 | return 1 | |
616 | return 0 |
|
616 | return 0 | |
617 |
|
617 | |||
618 | def setBlockDimension(self): |
|
618 | def setBlockDimension(self): | |
619 | """ |
|
619 | """ | |
620 | Obtiene las formas dimensionales del los subbloques de datos que componen un bloque |
|
620 | Obtiene las formas dimensionales del los subbloques de datos que componen un bloque | |
621 |
|
621 | |||
622 | Affected: |
|
622 | Affected: | |
623 | self.shape_spc_Buffer |
|
623 | self.shape_spc_Buffer | |
624 | self.shape_cspc_Buffer |
|
624 | self.shape_cspc_Buffer | |
625 | self.shape_dc_Buffer |
|
625 | self.shape_dc_Buffer | |
626 |
|
626 | |||
627 | Return: None |
|
627 | Return: None | |
628 | """ |
|
628 | """ | |
629 | self.shapeBuffer = (self.processingHeaderObj.profilesPerBlock, |
|
629 | self.shapeBuffer = (self.processingHeaderObj.profilesPerBlock, | |
630 | self.processingHeaderObj.nHeights, |
|
630 | self.processingHeaderObj.nHeights, | |
631 | self.systemHeaderObj.nChannels) |
|
631 | self.systemHeaderObj.nChannels) | |
632 |
|
632 | |||
633 | self.datablock = numpy.zeros((self.systemHeaderObj.nChannels, |
|
633 | self.datablock = numpy.zeros((self.systemHeaderObj.nChannels, | |
634 | self.processingHeaderObj.profilesPerBlock, |
|
634 | self.processingHeaderObj.profilesPerBlock, | |
635 | self.processingHeaderObj.nHeights), |
|
635 | self.processingHeaderObj.nHeights), | |
636 | dtype=numpy.dtype('complex64')) |
|
636 | dtype=numpy.dtype('complex64')) | |
637 |
|
637 | |||
638 | def writeBlock(self): |
|
638 | def writeBlock(self): | |
639 | """ |
|
639 | """ | |
640 | Escribe el buffer en el file designado |
|
640 | Escribe el buffer en el file designado | |
641 |
|
641 | |||
642 | Affected: |
|
642 | Affected: | |
643 | self.profileIndex |
|
643 | self.profileIndex | |
644 | self.flagIsNewFile |
|
644 | self.flagIsNewFile | |
645 | self.flagIsNewBlock |
|
645 | self.flagIsNewBlock | |
646 | self.nTotalBlocks |
|
646 | self.nTotalBlocks | |
647 | self.blockIndex |
|
647 | self.blockIndex | |
648 |
|
648 | |||
649 | Return: None |
|
649 | Return: None | |
650 | """ |
|
650 | """ | |
651 | data = numpy.zeros(self.shapeBuffer, self.dtype) |
|
651 | data = numpy.zeros(self.shapeBuffer, self.dtype) | |
652 |
|
652 | |||
653 | junk = numpy.transpose(self.datablock, (1, 2, 0)) |
|
653 | junk = numpy.transpose(self.datablock, (1, 2, 0)) | |
654 |
|
654 | |||
655 | data['real'] = junk.real |
|
655 | data['real'] = junk.real | |
656 | data['imag'] = junk.imag |
|
656 | data['imag'] = junk.imag | |
657 |
|
657 | |||
658 | data = data.reshape((-1)) |
|
658 | data = data.reshape((-1)) | |
659 |
|
659 | |||
660 | data.tofile(self.fp) |
|
660 | data.tofile(self.fp) | |
661 |
|
661 | |||
662 | self.datablock.fill(0) |
|
662 | self.datablock.fill(0) | |
663 |
|
663 | |||
664 | self.profileIndex = 0 |
|
664 | self.profileIndex = 0 | |
665 | self.flagIsNewFile = 0 |
|
665 | self.flagIsNewFile = 0 | |
666 | self.flagIsNewBlock = 1 |
|
666 | self.flagIsNewBlock = 1 | |
667 |
|
667 | |||
668 | self.blockIndex += 1 |
|
668 | self.blockIndex += 1 | |
669 | self.nTotalBlocks += 1 |
|
669 | self.nTotalBlocks += 1 | |
670 |
|
670 | |||
671 | # print "[Writing] Block = %04d" %self.blockIndex |
|
671 | # print "[Writing] Block = %04d" %self.blockIndex | |
672 |
|
672 | |||
673 | def putData(self): |
|
673 | def putData(self): | |
674 | """ |
|
674 | """ | |
675 | Setea un bloque de datos y luego los escribe en un file |
|
675 | Setea un bloque de datos y luego los escribe en un file | |
676 |
|
676 | |||
677 | Affected: |
|
677 | Affected: | |
678 | self.flagIsNewBlock |
|
678 | self.flagIsNewBlock | |
679 | self.profileIndex |
|
679 | self.profileIndex | |
680 |
|
680 | |||
681 | Return: |
|
681 | Return: | |
682 | 0 : Si no hay data o no hay mas files que puedan escribirse |
|
682 | 0 : Si no hay data o no hay mas files que puedan escribirse | |
683 | 1 : Si se escribio la data de un bloque en un file |
|
683 | 1 : Si se escribio la data de un bloque en un file | |
684 | """ |
|
684 | """ | |
685 | if self.dataOut.flagNoData: |
|
685 | if self.dataOut.flagNoData: | |
686 | return 0 |
|
686 | return 0 | |
687 |
|
687 | |||
688 | self.flagIsNewBlock = 0 |
|
688 | self.flagIsNewBlock = 0 | |
689 |
|
689 | |||
690 | if self.dataOut.flagDiscontinuousBlock: |
|
690 | if self.dataOut.flagDiscontinuousBlock: | |
691 | self.datablock.fill(0) |
|
691 | self.datablock.fill(0) | |
692 | self.profileIndex = 0 |
|
692 | self.profileIndex = 0 | |
693 | self.setNextFile() |
|
693 | self.setNextFile() | |
694 |
|
694 | |||
695 | if self.profileIndex == 0: |
|
695 | if self.profileIndex == 0: | |
696 | self.setBasicHeader() |
|
696 | self.setBasicHeader() | |
697 |
|
697 | |||
698 | self.datablock[:, self.profileIndex, :] = self.dataOut.data |
|
698 | self.datablock[:, self.profileIndex, :] = self.dataOut.data | |
699 |
|
699 | |||
700 | self.profileIndex += 1 |
|
700 | self.profileIndex += 1 | |
701 |
|
701 | |||
702 | if self.hasAllDataInBuffer(): |
|
702 | if self.hasAllDataInBuffer(): | |
703 | # if self.flagIsNewFile: |
|
703 | # if self.flagIsNewFile: | |
704 | self.writeNextBlock() |
|
704 | self.writeNextBlock() | |
705 | # self.setFirstHeader() |
|
705 | # self.setFirstHeader() | |
706 |
|
706 | |||
707 | return 1 |
|
707 | return 1 | |
708 |
|
708 | |||
709 | def __getBlockSize(self): |
|
709 | def __getBlockSize(self): | |
710 | ''' |
|
710 | ''' | |
711 | Este metodos determina el cantidad de bytes para un bloque de datos de tipo Voltage |
|
711 | Este metodos determina el cantidad de bytes para un bloque de datos de tipo Voltage | |
712 | ''' |
|
712 | ''' | |
713 |
|
713 | |||
714 | dtype_width = self.getDtypeWidth() |
|
714 | dtype_width = self.getDtypeWidth() | |
715 |
|
715 | |||
716 | blocksize = int(self.dataOut.nHeights * self.dataOut.nChannels * |
|
716 | blocksize = int(self.dataOut.nHeights * self.dataOut.nChannels * | |
717 | self.profilesPerBlock * dtype_width * 2) |
|
717 | self.profilesPerBlock * dtype_width * 2) | |
718 |
|
718 | |||
719 | return blocksize |
|
719 | return blocksize | |
720 |
|
720 | |||
721 | def setFirstHeader(self): |
|
721 | def setFirstHeader(self): | |
722 | """ |
|
722 | """ | |
723 | Obtiene una copia del First Header |
|
723 | Obtiene una copia del First Header | |
724 |
|
724 | |||
725 | Affected: |
|
725 | Affected: | |
726 | self.systemHeaderObj |
|
726 | self.systemHeaderObj | |
727 | self.radarControllerHeaderObj |
|
727 | self.radarControllerHeaderObj | |
728 | self.dtype |
|
728 | self.dtype | |
729 |
|
729 | |||
730 | Return: |
|
730 | Return: | |
731 | None |
|
731 | None | |
732 | """ |
|
732 | """ | |
733 |
|
733 | |||
734 | self.systemHeaderObj = self.dataOut.systemHeaderObj.copy() |
|
734 | self.systemHeaderObj = self.dataOut.systemHeaderObj.copy() | |
735 | self.systemHeaderObj.nChannels = self.dataOut.nChannels |
|
735 | self.systemHeaderObj.nChannels = self.dataOut.nChannels | |
736 | self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy() |
|
736 | self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy() | |
737 |
|
737 | |||
738 | self.processingHeaderObj.dtype = 0 # Voltage |
|
738 | self.processingHeaderObj.dtype = 0 # Voltage | |
739 | self.processingHeaderObj.blockSize = self.__getBlockSize() |
|
739 | self.processingHeaderObj.blockSize = self.__getBlockSize() | |
740 | self.processingHeaderObj.profilesPerBlock = self.profilesPerBlock |
|
740 | self.processingHeaderObj.profilesPerBlock = self.profilesPerBlock | |
741 | self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile |
|
741 | self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile | |
742 | # podria ser 1 o self.dataOut.processingHeaderObj.nWindows |
|
742 | # podria ser 1 o self.dataOut.processingHeaderObj.nWindows | |
743 | self.processingHeaderObj.nWindows = 1 |
|
743 | self.processingHeaderObj.nWindows = 1 | |
744 | self.processingHeaderObj.nCohInt = self.dataOut.nCohInt |
|
744 | self.processingHeaderObj.nCohInt = self.dataOut.nCohInt | |
745 | # Cuando la data de origen es de tipo Voltage |
|
745 | # Cuando la data de origen es de tipo Voltage | |
746 | self.processingHeaderObj.nIncohInt = 1 |
|
746 | self.processingHeaderObj.nIncohInt = 1 | |
747 | # Cuando la data de origen es de tipo Voltage |
|
747 | # Cuando la data de origen es de tipo Voltage | |
748 | self.processingHeaderObj.totalSpectra = 0 |
|
748 | self.processingHeaderObj.totalSpectra = 0 | |
749 |
|
749 | |||
750 | if self.dataOut.code is not None: |
|
750 | if self.dataOut.code is not None: | |
751 | self.processingHeaderObj.code = self.dataOut.code |
|
751 | self.processingHeaderObj.code = self.dataOut.code | |
752 | self.processingHeaderObj.nCode = self.dataOut.nCode |
|
752 | self.processingHeaderObj.nCode = self.dataOut.nCode | |
753 | self.processingHeaderObj.nBaud = self.dataOut.nBaud |
|
753 | self.processingHeaderObj.nBaud = self.dataOut.nBaud | |
754 |
|
754 | |||
755 | if self.processingHeaderObj.nWindows != 0: |
|
755 | if self.processingHeaderObj.nWindows != 0: | |
756 | self.processingHeaderObj.firstHeight = self.dataOut.heightList[0] |
|
756 | self.processingHeaderObj.firstHeight = self.dataOut.heightList[0] | |
757 | self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - \ |
|
757 | self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - \ | |
758 | self.dataOut.heightList[0] |
|
758 | self.dataOut.heightList[0] | |
759 | self.processingHeaderObj.nHeights = self.dataOut.nHeights |
|
759 | self.processingHeaderObj.nHeights = self.dataOut.nHeights | |
760 | self.processingHeaderObj.samplesWin = self.dataOut.nHeights |
|
760 | self.processingHeaderObj.samplesWin = self.dataOut.nHeights | |
761 |
|
761 | |||
762 | self.processingHeaderObj.processFlags = self.getProcessFlags() |
|
762 | self.processingHeaderObj.processFlags = self.getProcessFlags() | |
763 |
|
763 | |||
764 | self.setBasicHeader() No newline at end of file |
|
764 | self.setBasicHeader() | |
|
765 | No newline at end of file |
@@ -1,538 +1,538 | |||||
1 | ''' |
|
1 | ''' | |
2 | Updated for multiprocessing |
|
2 | Updated for multiprocessing | |
3 | Author : Sergio Cortez |
|
3 | Author : Sergio Cortez | |
4 | Jan 2018 |
|
4 | Jan 2018 | |
5 | Abstract: |
|
5 | Abstract: | |
6 | Base class for processing units and operations. A decorator provides multiprocessing features and interconnect the processes created. |
|
6 | Base class for processing units and operations. A decorator provides multiprocessing features and interconnect the processes created. | |
7 | The argument (kwargs) sent from the controller is parsed and filtered via the decorator for each processing unit or operation instantiated. |
|
7 | The argument (kwargs) sent from the controller is parsed and filtered via the decorator for each processing unit or operation instantiated. | |
8 | The decorator handle also the methods inside the processing unit to be called from the main script (not as operations) (OPERATION -> type ='self'). |
|
8 | The decorator handle also the methods inside the processing unit to be called from the main script (not as operations) (OPERATION -> type ='self'). | |
9 |
|
9 | |||
10 | Based on: |
|
10 | Based on: | |
11 | $Author: murco $ |
|
11 | $Author: murco $ | |
12 | $Id: jroproc_base.py 1 2012-11-12 18:56:07Z murco $ |
|
12 | $Id: jroproc_base.py 1 2012-11-12 18:56:07Z murco $ | |
13 | ''' |
|
13 | ''' | |
14 | from platform import python_version |
|
14 | from platform import python_version | |
15 | import inspect |
|
15 | import inspect | |
16 | import zmq |
|
16 | import zmq | |
17 | import time |
|
17 | import time | |
18 | import pickle |
|
18 | import pickle | |
19 | import os |
|
19 | import os | |
20 | from multiprocessing import Process |
|
20 | from multiprocessing import Process | |
21 |
|
21 | |||
22 | from schainpy.utils import log |
|
22 | from schainpy.utils import log | |
23 |
|
23 | |||
24 |
|
24 | |||
25 | class ProcessingUnit(object): |
|
25 | class ProcessingUnit(object): | |
26 |
|
26 | |||
27 | """ |
|
27 | """ | |
28 | Update - Jan 2018 - MULTIPROCESSING |
|
28 | Update - Jan 2018 - MULTIPROCESSING | |
29 | All the "call" methods present in the previous base were removed. |
|
29 | All the "call" methods present in the previous base were removed. | |
30 | The majority of operations are independant processes, thus |
|
30 | The majority of operations are independant processes, thus | |
31 | the decorator is in charge of communicate the operation processes |
|
31 | the decorator is in charge of communicate the operation processes | |
32 | with the proccessing unit via IPC. |
|
32 | with the proccessing unit via IPC. | |
33 |
|
33 | |||
34 | The constructor does not receive any argument. The remaining methods |
|
34 | The constructor does not receive any argument. The remaining methods | |
35 | are related with the operations to execute. |
|
35 | are related with the operations to execute. | |
36 |
|
36 | |||
37 |
|
37 | |||
38 | """ |
|
38 | """ | |
39 | # objeto de datos de entrada (Voltage, Spectra o Correlation) |
|
39 | # objeto de datos de entrada (Voltage, Spectra o Correlation) | |
40 | dataIn = None |
|
40 | dataIn = None | |
41 | dataInList = [] |
|
41 | dataInList = [] | |
42 |
|
42 | |||
43 | # objeto de datos de entrada (Voltage, Spectra o Correlation) |
|
43 | # objeto de datos de entrada (Voltage, Spectra o Correlation) | |
44 |
|
44 | |||
45 | id = None |
|
45 | id = None | |
46 | inputId = None |
|
46 | inputId = None | |
47 |
|
47 | |||
48 | dataOut = None |
|
48 | dataOut = None | |
49 |
|
49 | |||
50 | dictProcs = None |
|
50 | dictProcs = None | |
51 |
|
51 | |||
52 | operations2RunDict = None |
|
52 | operations2RunDict = None | |
53 |
|
53 | |||
54 | isConfig = False |
|
54 | isConfig = False | |
55 |
|
55 | |||
56 | def __init__(self): |
|
56 | def __init__(self): | |
57 |
|
57 | |||
58 | self.dataIn = None |
|
58 | self.dataIn = None | |
59 | self.dataOut = None |
|
59 | self.dataOut = None | |
60 |
|
60 | |||
61 | self.isConfig = False |
|
61 | self.isConfig = False | |
62 |
|
62 | |||
63 | def getAllowedArgs(self): |
|
63 | def getAllowedArgs(self): | |
64 | if hasattr(self, '__attrs__'): |
|
64 | if hasattr(self, '__attrs__'): | |
65 | return self.__attrs__ |
|
65 | return self.__attrs__ | |
66 | else: |
|
66 | else: | |
67 | return inspect.getargspec(self.run).args |
|
67 | return inspect.getargspec(self.run).args | |
68 |
|
68 | |||
69 | def addOperationKwargs(self, objId, **kwargs): |
|
69 | def addOperationKwargs(self, objId, **kwargs): | |
70 | ''' |
|
70 | ''' | |
71 | ''' |
|
71 | ''' | |
72 |
|
72 | |||
73 | self.operationKwargs[objId] = kwargs |
|
73 | self.operationKwargs[objId] = kwargs | |
74 |
|
74 | |||
75 | def addOperation(self, opObj, objId): |
|
75 | def addOperation(self, opObj, objId): | |
76 |
|
76 | |||
77 | """ |
|
77 | """ | |
78 | This method is used in the controller, and update the dictionary containing the operations to execute. The dict |
|
78 | This method is used in the controller, and update the dictionary containing the operations to execute. The dict | |
79 | posses the id of the operation process (IPC purposes) |
|
79 | posses the id of the operation process (IPC purposes) | |
80 |
|
80 | |||
81 | Agrega un objeto del tipo "Operation" (opObj) a la lista de objetos "self.objectList" y retorna el |
|
81 | Agrega un objeto del tipo "Operation" (opObj) a la lista de objetos "self.objectList" y retorna el | |
82 | identificador asociado a este objeto. |
|
82 | identificador asociado a este objeto. | |
83 |
|
83 | |||
84 | Input: |
|
84 | Input: | |
85 |
|
85 | |||
86 | object : objeto de la clase "Operation" |
|
86 | object : objeto de la clase "Operation" | |
87 |
|
87 | |||
88 | Return: |
|
88 | Return: | |
89 |
|
89 | |||
90 | objId : identificador del objeto, necesario para comunicar con master(procUnit) |
|
90 | objId : identificador del objeto, necesario para comunicar con master(procUnit) | |
91 | """ |
|
91 | """ | |
92 |
|
92 | |||
93 | self.operations2RunDict[objId] = opObj |
|
93 | self.operations2RunDict[objId] = opObj | |
94 |
|
94 | |||
95 | return objId |
|
95 | return objId | |
96 |
|
96 | |||
97 |
|
97 | |||
98 | def getOperationObj(self, objId): |
|
98 | def getOperationObj(self, objId): | |
99 |
|
99 | |||
100 | if objId not in list(self.operations2RunDict.keys()): |
|
100 | if objId not in list(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 setup(self): |
|
118 | def setup(self): | |
119 |
|
119 | |||
120 | raise NotImplementedError |
|
120 | raise NotImplementedError | |
121 |
|
121 | |||
122 | def run(self): |
|
122 | def run(self): | |
123 |
|
123 | |||
124 | raise NotImplementedError |
|
124 | raise NotImplementedError | |
125 |
|
125 | |||
126 | def close(self): |
|
126 | def close(self): | |
127 | #Close every thread, queue or any other object here is it is neccesary. |
|
127 | #Close every thread, queue or any other object here is it is neccesary. | |
128 | return |
|
128 | return | |
129 |
|
129 | |||
130 | class Operation(object): |
|
130 | class Operation(object): | |
131 |
|
131 | |||
132 | """ |
|
132 | """ | |
133 | Update - Jan 2018 - MULTIPROCESSING |
|
133 | Update - Jan 2018 - MULTIPROCESSING | |
134 |
|
134 | |||
135 | Most of the methods remained the same. The decorator parse the arguments and executed the run() method for each process. |
|
135 | Most of the methods remained the same. The decorator parse the arguments and executed the run() method for each process. | |
136 | The constructor doe snot receive any argument, neither the baseclass. |
|
136 | The constructor doe snot receive any argument, neither the baseclass. | |
137 |
|
137 | |||
138 |
|
138 | |||
139 | Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit |
|
139 | Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit | |
140 | y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de |
|
140 | y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de | |
141 | acumulacion dentro de esta clase |
|
141 | acumulacion dentro de esta clase | |
142 |
|
142 | |||
143 | Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer) |
|
143 | Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer) | |
144 |
|
144 | |||
145 | """ |
|
145 | """ | |
146 | id = None |
|
146 | id = None | |
147 | __buffer = None |
|
147 | __buffer = None | |
148 | dest = None |
|
148 | dest = None | |
149 | isConfig = False |
|
149 | isConfig = False | |
150 | readyFlag = None |
|
150 | readyFlag = None | |
151 |
|
151 | |||
152 | def __init__(self): |
|
152 | def __init__(self): | |
153 |
|
153 | |||
154 | self.buffer = None |
|
154 | self.buffer = None | |
155 | self.dest = None |
|
155 | self.dest = None | |
156 | self.isConfig = False |
|
156 | self.isConfig = False | |
157 | self.readyFlag = False |
|
157 | self.readyFlag = False | |
158 |
|
158 | |||
159 | if not hasattr(self, 'name'): |
|
159 | if not hasattr(self, 'name'): | |
160 | self.name = self.__class__.__name__ |
|
160 | self.name = self.__class__.__name__ | |
161 |
|
161 | |||
162 | def getAllowedArgs(self): |
|
162 | def getAllowedArgs(self): | |
163 | if hasattr(self, '__attrs__'): |
|
163 | if hasattr(self, '__attrs__'): | |
164 | return self.__attrs__ |
|
164 | return self.__attrs__ | |
165 | else: |
|
165 | else: | |
166 | return inspect.getargspec(self.run).args |
|
166 | return inspect.getargspec(self.run).args | |
167 |
|
167 | |||
168 | def setup(self): |
|
168 | def setup(self): | |
169 |
|
169 | |||
170 | self.isConfig = True |
|
170 | self.isConfig = True | |
171 |
|
171 | |||
172 | raise NotImplementedError |
|
172 | raise NotImplementedError | |
173 |
|
173 | |||
174 |
|
174 | |||
175 | def run(self, dataIn, **kwargs): |
|
175 | def run(self, dataIn, **kwargs): | |
176 |
|
176 | |||
177 | """ |
|
177 | """ | |
178 | Realiza las operaciones necesarias sobre la dataIn.data y actualiza los |
|
178 | Realiza las operaciones necesarias sobre la dataIn.data y actualiza los | |
179 | atributos del objeto dataIn. |
|
179 | atributos del objeto dataIn. | |
180 |
|
180 | |||
181 | Input: |
|
181 | Input: | |
182 |
|
182 | |||
183 | dataIn : objeto del tipo JROData |
|
183 | dataIn : objeto del tipo JROData | |
184 |
|
184 | |||
185 | Return: |
|
185 | Return: | |
186 |
|
186 | |||
187 | None |
|
187 | None | |
188 |
|
188 | |||
189 | Affected: |
|
189 | Affected: | |
190 | __buffer : buffer de recepcion de datos. |
|
190 | __buffer : buffer de recepcion de datos. | |
191 |
|
191 | |||
192 | """ |
|
192 | """ | |
193 | if not self.isConfig: |
|
193 | if not self.isConfig: | |
194 | self.setup(**kwargs) |
|
194 | self.setup(**kwargs) | |
195 |
|
195 | |||
196 | raise NotImplementedError |
|
196 | raise NotImplementedError | |
197 |
|
197 | |||
198 | def close(self): |
|
198 | def close(self): | |
199 |
|
199 | |||
200 | pass |
|
200 | pass | |
201 |
|
201 | |||
202 |
|
202 | |||
203 | ######### Decorator ######### |
|
203 | ######### Decorator ######### | |
204 |
|
204 | |||
205 |
|
205 | |||
206 | def MPDecorator(BaseClass): |
|
206 | def MPDecorator(BaseClass): | |
207 |
|
207 | |||
208 | """ |
|
208 | """ | |
209 | "Multiprocessing class decorator" |
|
209 | "Multiprocessing class decorator" | |
210 |
|
210 | |||
211 | This function add multiprocessing features to the base class. Also, |
|
211 | This function add multiprocessing features to the base class. Also, | |
212 | it handle the communication beetween processes (readers, procUnits and operations). |
|
212 | it handle the communication beetween processes (readers, procUnits and operations). | |
213 | Receive the arguments at the moment of instantiation. According to that, discriminates if it |
|
213 | Receive the arguments at the moment of instantiation. According to that, discriminates if it | |
214 | is a procUnit or an operation |
|
214 | is a procUnit or an operation | |
215 | """ |
|
215 | """ | |
216 |
|
216 | |||
217 | class MPClass(BaseClass, Process): |
|
217 | class MPClass(BaseClass, Process): | |
218 |
|
218 | |||
219 | "This is the overwritten class" |
|
219 | "This is the overwritten class" | |
220 | operations2RunDict = None |
|
220 | operations2RunDict = None | |
221 | socket_l = None |
|
221 | socket_l = None | |
222 | socket_p = None |
|
222 | socket_p = None | |
223 | socketOP = None |
|
223 | socketOP = None | |
224 | socket_router = None |
|
224 | socket_router = None | |
225 | dictProcs = None |
|
225 | dictProcs = None | |
226 | typeProc = None |
|
226 | typeProc = None | |
227 | def __init__(self, *args, **kwargs): |
|
227 | def __init__(self, *args, **kwargs): | |
228 | super(MPClass, self).__init__() |
|
228 | super(MPClass, self).__init__() | |
229 | Process.__init__(self) |
|
229 | Process.__init__(self) | |
230 |
|
230 | |||
231 |
|
231 | |||
232 | self.operationKwargs = {} |
|
232 | self.operationKwargs = {} | |
233 | self.args = args |
|
233 | self.args = args | |
234 |
|
234 | |||
235 |
|
235 | |||
236 | self.operations2RunDict = {} |
|
236 | self.operations2RunDict = {} | |
237 | self.kwargs = kwargs |
|
237 | self.kwargs = kwargs | |
238 |
|
238 | |||
239 | # The number of arguments (args) determine the type of process |
|
239 | # The number of arguments (args) determine the type of process | |
240 |
|
240 | |||
241 | if len(self.args) is 3: |
|
241 | if len(self.args) is 3: | |
242 | self.typeProc = "ProcUnit" |
|
242 | self.typeProc = "ProcUnit" | |
243 | self.id = args[0] #topico de publicacion |
|
243 | self.id = args[0] #topico de publicacion | |
244 | self.inputId = args[1] #topico de subcripcion |
|
244 | self.inputId = args[1] #topico de subcripcion | |
245 | self.dictProcs = args[2] #diccionario de procesos globales |
|
245 | self.dictProcs = args[2] #diccionario de procesos globales | |
246 | else: |
|
246 | else: | |
247 | self.id = args[0] |
|
247 | self.id = args[0] | |
248 | self.typeProc = "Operation" |
|
248 | self.typeProc = "Operation" | |
249 |
|
249 | |||
250 | def addOperationKwargs(self, objId, **kwargs): |
|
250 | def addOperationKwargs(self, objId, **kwargs): | |
251 |
|
251 | |||
252 | self.operationKwargs[objId] = kwargs |
|
252 | self.operationKwargs[objId] = kwargs | |
253 |
|
253 | |||
254 | def getAllowedArgs(self): |
|
254 | def getAllowedArgs(self): | |
255 |
|
255 | |||
256 | if hasattr(self, '__attrs__'): |
|
256 | if hasattr(self, '__attrs__'): | |
257 | return self.__attrs__ |
|
257 | return self.__attrs__ | |
258 | else: |
|
258 | else: | |
259 | return inspect.getargspec(self.run).args |
|
259 | return inspect.getargspec(self.run).args | |
260 |
|
260 | |||
261 |
|
261 | |||
262 | def sockListening(self, topic): |
|
262 | def sockListening(self, topic): | |
263 |
|
263 | |||
264 | """ |
|
264 | """ | |
265 | This function create a socket to receive objects. |
|
265 | This function create a socket to receive objects. | |
266 | The 'topic' argument is related to the publisher process from which the self process is |
|
266 | The 'topic' argument is related to the publisher process from which the self process is | |
267 | listening (data). |
|
267 | listening (data). | |
268 | In the case were the self process is listening to a Reader (proc Unit), |
|
268 | In the case were the self process is listening to a Reader (proc Unit), | |
269 | special conditions are introduced to maximize parallelism. |
|
269 | special conditions are introduced to maximize parallelism. | |
270 | """ |
|
270 | """ | |
271 |
|
271 | |||
272 | cont = zmq.Context() |
|
272 | cont = zmq.Context() | |
273 | zmq_socket = cont.socket(zmq.SUB) |
|
273 | zmq_socket = cont.socket(zmq.SUB) | |
274 | if not os.path.exists('/tmp/socketTmp'): |
|
274 | if not os.path.exists('/tmp/socketTmp'): | |
275 | os.mkdir('/tmp/socketTmp') |
|
275 | os.mkdir('/tmp/socketTmp') | |
276 |
|
276 | |||
277 | if 'Reader' in self.dictProcs[self.inputId].name: |
|
277 | if 'Reader' in self.dictProcs[self.inputId].name: | |
278 | zmq_socket.connect('ipc:///tmp/socketTmp/b') |
|
278 | zmq_socket.connect('ipc:///tmp/socketTmp/b') | |
279 |
|
279 | |||
280 | else: |
|
280 | else: | |
281 | zmq_socket.connect('ipc:///tmp/socketTmp/%s' % self.inputId) |
|
281 | zmq_socket.connect('ipc:///tmp/socketTmp/%s' % self.inputId) | |
282 |
|
282 | |||
283 | #log.error('RECEIVING FROM {} {}'.format(self.inputId, str(topic).encode())) |
|
283 | #log.error('RECEIVING FROM {} {}'.format(self.inputId, str(topic).encode())) | |
284 | zmq_socket.setsockopt(zmq.SUBSCRIBE, str(topic).encode()) #yong |
|
284 | zmq_socket.setsockopt(zmq.SUBSCRIBE, str(topic).encode()) #yong | |
285 |
|
285 | |||
286 | return zmq_socket |
|
286 | return zmq_socket | |
287 |
|
287 | |||
288 |
|
288 | |||
289 | def listenProc(self, sock): |
|
289 | def listenProc(self, sock): | |
290 |
|
290 | |||
291 | """ |
|
291 | """ | |
292 | This function listen to a ipc addres until a message is recovered. To serialize the |
|
292 | This function listen to a ipc addres until a message is recovered. To serialize the | |
293 | data (object), pickle has been use. |
|
293 | data (object), pickle has been use. | |
294 | The 'sock' argument is the socket previously connect to an ipc address and with a topic subscription. |
|
294 | The 'sock' argument is the socket previously connect to an ipc address and with a topic subscription. | |
295 | """ |
|
295 | """ | |
296 |
|
296 | |||
297 | a = sock.recv_multipart() |
|
297 | a = sock.recv_multipart() | |
298 | a = pickle.loads(a[1]) |
|
298 | a = pickle.loads(a[1]) | |
299 | return a |
|
299 | return a | |
300 |
|
300 | |||
301 | def sockPublishing(self): |
|
301 | def sockPublishing(self): | |
302 |
|
302 | |||
303 | """ |
|
303 | """ | |
304 | This function create a socket for publishing purposes. |
|
304 | This function create a socket for publishing purposes. | |
305 | Depending on the process type from where is created, it binds or connect |
|
305 | Depending on the process type from where is created, it binds or connect | |
306 | to special IPC addresses. |
|
306 | to special IPC addresses. | |
307 | """ |
|
307 | """ | |
308 | time.sleep(4) #yong |
|
308 | time.sleep(4) #yong | |
309 | context = zmq.Context() |
|
309 | context = zmq.Context() | |
310 | zmq_socket = context.socket(zmq.PUB) |
|
310 | zmq_socket = context.socket(zmq.PUB) | |
311 | if not os.path.exists('/tmp/socketTmp'): os.mkdir('/tmp/socketTmp') |
|
311 | if not os.path.exists('/tmp/socketTmp'): os.mkdir('/tmp/socketTmp') | |
312 | if 'Reader' in self.dictProcs[self.id].name: |
|
312 | if 'Reader' in self.dictProcs[self.id].name: | |
313 | zmq_socket.connect('ipc:///tmp/socketTmp/a') |
|
313 | zmq_socket.connect('ipc:///tmp/socketTmp/a') | |
314 | else: |
|
314 | else: | |
315 | zmq_socket.bind('ipc:///tmp/socketTmp/%s' % self.id) |
|
315 | zmq_socket.bind('ipc:///tmp/socketTmp/%s' % self.id) | |
316 |
|
316 | |||
317 | return zmq_socket |
|
317 | return zmq_socket | |
318 |
|
318 | |||
319 | def publishProc(self, sock, data): |
|
319 | def publishProc(self, sock, data): | |
320 |
|
320 | |||
321 | """ |
|
321 | """ | |
322 | This function publish a python object (data) under a specific topic in a socket (sock). |
|
322 | This function publish a python object (data) under a specific topic in a socket (sock). | |
323 | Usually, the topic is the self id of the process. |
|
323 | Usually, the topic is the self id of the process. | |
324 | """ |
|
324 | """ | |
325 |
|
325 | |||
326 | sock.send_multipart([str(self.id).encode(), pickle.dumps(data)]) #yong |
|
326 | sock.send_multipart([str(self.id).encode(), pickle.dumps(data)]) #yong | |
327 |
|
327 | |||
328 | return True |
|
328 | return True | |
329 |
|
329 | |||
330 | def sockOp(self): |
|
330 | def sockOp(self): | |
331 |
|
331 | |||
332 | """ |
|
332 | """ | |
333 | This function create a socket for communication purposes with operation processes. |
|
333 | This function create a socket for communication purposes with operation processes. | |
334 | """ |
|
334 | """ | |
335 |
|
335 | |||
336 | cont = zmq.Context() |
|
336 | cont = zmq.Context() | |
337 | zmq_socket = cont.socket(zmq.DEALER) |
|
337 | zmq_socket = cont.socket(zmq.DEALER) | |
338 |
|
338 | |||
339 | if python_version()[0] == '2': |
|
339 | if python_version()[0] == '2': | |
340 | zmq_socket.setsockopt(zmq.IDENTITY, self.id) |
|
340 | zmq_socket.setsockopt(zmq.IDENTITY, self.id) | |
341 | if python_version()[0] == '3': |
|
341 | if python_version()[0] == '3': | |
342 | zmq_socket.setsockopt_string(zmq.IDENTITY, self.id) |
|
342 | zmq_socket.setsockopt_string(zmq.IDENTITY, self.id) | |
343 |
|
343 | |||
344 |
|
344 | |||
345 | return zmq_socket |
|
345 | return zmq_socket | |
346 |
|
346 | |||
347 |
|
347 | |||
348 | def execOp(self, socket, opId, dataObj): |
|
348 | def execOp(self, socket, opId, dataObj): | |
349 |
|
349 | |||
350 | """ |
|
350 | """ | |
351 | This function 'execute' an operation main routine by establishing a |
|
351 | This function 'execute' an operation main routine by establishing a | |
352 | connection with it and sending a python object (dataOut). |
|
352 | connection with it and sending a python object (dataOut). | |
353 | """ |
|
353 | """ | |
354 | if not os.path.exists('/tmp/socketTmp'): os.mkdir('/tmp/socketTmp') |
|
354 | if not os.path.exists('/tmp/socketTmp'): os.mkdir('/tmp/socketTmp') | |
355 | socket.connect('ipc:///tmp/socketTmp/%s' %opId) |
|
355 | socket.connect('ipc:///tmp/socketTmp/%s' %opId) | |
356 |
|
356 | |||
357 |
|
357 | |||
358 | socket.send(pickle.dumps(dataObj)) #yong |
|
358 | socket.send(pickle.dumps(dataObj)) #yong | |
359 |
|
359 | |||
360 | argument = socket.recv_multipart()[0] |
|
360 | argument = socket.recv_multipart()[0] | |
361 |
|
361 | |||
362 | argument = pickle.loads(argument) |
|
362 | argument = pickle.loads(argument) | |
363 |
|
363 | |||
364 | return argument |
|
364 | return argument | |
365 |
|
365 | |||
366 | def sockIO(self): |
|
366 | def sockIO(self): | |
367 |
|
367 | |||
368 | """ |
|
368 | """ | |
369 | Socket defined for an operation process. It is able to recover the object sent from another process as well as a |
|
369 | Socket defined for an operation process. It is able to recover the object sent from another process as well as a | |
370 | identifier of who sent it. |
|
370 | identifier of who sent it. | |
371 | """ |
|
371 | """ | |
372 |
|
372 | |||
373 | cont = zmq.Context() |
|
373 | cont = zmq.Context() | |
374 | if not os.path.exists('/tmp/socketTmp'): os.mkdir('/tmp/socketTmp') |
|
374 | if not os.path.exists('/tmp/socketTmp'): os.mkdir('/tmp/socketTmp') | |
375 | socket = cont.socket(zmq.ROUTER) |
|
375 | socket = cont.socket(zmq.ROUTER) | |
376 | socket.bind('ipc:///tmp/socketTmp/%s' % self.id) |
|
376 | socket.bind('ipc:///tmp/socketTmp/%s' % self.id) | |
377 |
|
377 | |||
378 | return socket |
|
378 | return socket | |
379 |
|
379 | |||
380 | def funIOrec(self, socket): |
|
380 | def funIOrec(self, socket): | |
381 |
|
381 | |||
382 | """ |
|
382 | """ | |
383 | Operation method, recover the id of the process who sent a python object. |
|
383 | Operation method, recover the id of the process who sent a python object. | |
384 | The 'socket' argument is the socket binded to a specific process ipc. |
|
384 | The 'socket' argument is the socket binded to a specific process ipc. | |
385 | """ |
|
385 | """ | |
386 |
|
386 | |||
387 | #id_proc = socket.recv() |
|
387 | #id_proc = socket.recv() | |
388 |
|
388 | |||
389 | #dataObj = socket.recv_pyobj() |
|
389 | #dataObj = socket.recv_pyobj() | |
390 |
|
390 | |||
391 | dataObj = socket.recv_multipart() |
|
391 | dataObj = socket.recv_multipart() | |
392 |
|
392 | |||
393 | dataObj[1] = pickle.loads(dataObj[1]) |
|
393 | dataObj[1] = pickle.loads(dataObj[1]) | |
394 | return dataObj[0], dataObj[1] |
|
394 | return dataObj[0], dataObj[1] | |
395 |
|
395 | |||
396 | def funIOsen(self, socket, data, dest): |
|
396 | def funIOsen(self, socket, data, dest): | |
397 |
|
397 | |||
398 | """ |
|
398 | """ | |
399 | Operation method, send a python object to a specific destination. |
|
399 | Operation method, send a python object to a specific destination. | |
400 | The 'dest' argument is the id of a proccesinf unit. |
|
400 | The 'dest' argument is the id of a proccesinf unit. | |
401 | """ |
|
401 | """ | |
402 |
|
402 | |||
403 | socket.send_multipart([dest, pickle.dumps(data)]) #yong |
|
403 | socket.send_multipart([dest, pickle.dumps(data)]) #yong | |
404 |
|
404 | |||
405 | return True |
|
405 | return True | |
406 |
|
406 | |||
407 |
|
407 | |||
408 | def runReader(self): |
|
408 | def runReader(self): | |
409 |
|
409 | |||
410 | # time.sleep(3) |
|
410 | # time.sleep(3) | |
411 | while True: |
|
411 | while True: | |
412 |
|
412 | |||
413 | BaseClass.run(self, **self.kwargs) |
|
413 | BaseClass.run(self, **self.kwargs) | |
414 |
|
414 | |||
415 |
|
415 | |||
416 | keyList = list(self.operations2RunDict.keys()) |
|
416 | keyList = list(self.operations2RunDict.keys()) | |
417 | keyList.sort() |
|
417 | keyList.sort() | |
418 |
|
418 | |||
419 | for key in keyList: |
|
419 | for key in keyList: | |
420 | self.socketOP = self.sockOp() |
|
420 | self.socketOP = self.sockOp() | |
421 | self.dataOut = self.execOp(self.socketOP, key, self.dataOut) |
|
421 | self.dataOut = self.execOp(self.socketOP, key, self.dataOut) | |
422 |
|
422 | |||
423 |
|
423 | |||
424 | if self.flagNoMoreFiles: #Usar un objeto con flags para saber si termino el proc o hubo un error |
|
424 | if self.flagNoMoreFiles: #Usar un objeto con flags para saber si termino el proc o hubo un error | |
425 | self.publishProc(self.socket_p, "Finish") |
|
425 | self.publishProc(self.socket_p, "Finish") | |
426 | break |
|
426 | break | |
427 |
|
427 | |||
428 | if self.dataOut.flagNoData: |
|
428 | if self.dataOut.flagNoData: | |
429 | continue |
|
429 | continue | |
430 |
|
430 | |||
431 | print("Publishing data...") |
|
431 | #print("Publishing data...") | |
432 | self.publishProc(self.socket_p, self.dataOut) |
|
432 | self.publishProc(self.socket_p, self.dataOut) | |
433 | # time.sleep(2) |
|
433 | # time.sleep(2) | |
434 |
|
434 | |||
435 |
|
435 | |||
436 | print("%s done" %BaseClass.__name__) |
|
436 | print("%s done" %BaseClass.__name__) | |
437 | return 0 |
|
437 | return 0 | |
438 |
|
438 | |||
439 | def runProc(self): |
|
439 | def runProc(self): | |
440 |
|
440 | |||
441 | # All the procUnits with kwargs that require a setup initialization must be defined here. |
|
441 | # All the procUnits with kwargs that require a setup initialization must be defined here. | |
442 |
|
442 | |||
443 | if self.setupReq: |
|
443 | if self.setupReq: | |
444 | BaseClass.setup(self, **self.kwargs) |
|
444 | BaseClass.setup(self, **self.kwargs) | |
445 |
|
445 | |||
446 | while True: |
|
446 | while True: | |
447 | self.dataIn = self.listenProc(self.socket_l) |
|
447 | self.dataIn = self.listenProc(self.socket_l) | |
448 | print("%s received data" %BaseClass.__name__) |
|
448 | #print("%s received data" %BaseClass.__name__) | |
449 |
|
449 | |||
450 | if self.dataIn == "Finish": |
|
450 | if self.dataIn == "Finish": | |
451 | break |
|
451 | break | |
452 |
|
452 | |||
453 | m_arg = list(self.kwargs.keys()) |
|
453 | m_arg = list(self.kwargs.keys()) | |
454 | num_arg = list(range(1,int(BaseClass.run.__code__.co_argcount))) |
|
454 | num_arg = list(range(1,int(BaseClass.run.__code__.co_argcount))) | |
455 |
|
455 | |||
456 | run_arg = {} |
|
456 | run_arg = {} | |
457 |
|
457 | |||
458 | for var in num_arg: |
|
458 | for var in num_arg: | |
459 | if BaseClass.run.__code__.co_varnames[var] in m_arg: |
|
459 | if BaseClass.run.__code__.co_varnames[var] in m_arg: | |
460 | run_arg[BaseClass.run.__code__.co_varnames[var]] = self.kwargs[BaseClass.run.__code__.co_varnames[var]] |
|
460 | run_arg[BaseClass.run.__code__.co_varnames[var]] = self.kwargs[BaseClass.run.__code__.co_varnames[var]] | |
461 |
|
461 | |||
462 | #BaseClass.run(self, **self.kwargs) |
|
462 | #BaseClass.run(self, **self.kwargs) | |
463 | BaseClass.run(self, **run_arg) |
|
463 | BaseClass.run(self, **run_arg) | |
464 |
|
464 | |||
465 | ## Iterar sobre una serie de data que podrias aplicarse |
|
465 | ## Iterar sobre una serie de data que podrias aplicarse | |
466 |
|
466 | |||
467 | for m_name in BaseClass.METHODS: |
|
467 | for m_name in BaseClass.METHODS: | |
468 |
|
468 | |||
469 | met_arg = {} |
|
469 | met_arg = {} | |
470 |
|
470 | |||
471 | for arg in m_arg: |
|
471 | for arg in m_arg: | |
472 | if arg in BaseClass.METHODS[m_name]: |
|
472 | if arg in BaseClass.METHODS[m_name]: | |
473 | for att in BaseClass.METHODS[m_name]: |
|
473 | for att in BaseClass.METHODS[m_name]: | |
474 | met_arg[att] = self.kwargs[att] |
|
474 | met_arg[att] = self.kwargs[att] | |
475 |
|
475 | |||
476 | method = getattr(BaseClass, m_name) |
|
476 | method = getattr(BaseClass, m_name) | |
477 | method(self, **met_arg) |
|
477 | method(self, **met_arg) | |
478 | break |
|
478 | break | |
479 |
|
479 | |||
480 | if self.dataOut.flagNoData: |
|
480 | if self.dataOut.flagNoData: | |
481 | continue |
|
481 | continue | |
482 |
|
482 | |||
483 | keyList = list(self.operations2RunDict.keys()) |
|
483 | keyList = list(self.operations2RunDict.keys()) | |
484 | keyList.sort() |
|
484 | keyList.sort() | |
485 |
|
485 | |||
486 | for key in keyList: |
|
486 | for key in keyList: | |
487 |
|
487 | |||
488 | self.socketOP = self.sockOp() |
|
488 | self.socketOP = self.sockOp() | |
489 | self.dataOut = self.execOp(self.socketOP, key, self.dataOut) |
|
489 | self.dataOut = self.execOp(self.socketOP, key, self.dataOut) | |
490 |
|
490 | |||
491 |
|
491 | |||
492 | self.publishProc(self.socket_p, self.dataOut) |
|
492 | self.publishProc(self.socket_p, self.dataOut) | |
493 |
|
493 | |||
494 |
|
494 | |||
495 | print("%s done" %BaseClass.__name__) |
|
495 | print("%s done" %BaseClass.__name__) | |
496 |
|
496 | |||
497 | return 0 |
|
497 | return 0 | |
498 |
|
498 | |||
499 | def runOp(self): |
|
499 | def runOp(self): | |
500 |
|
500 | |||
501 | while True: |
|
501 | while True: | |
502 |
|
502 | |||
503 | [self.dest ,self.buffer] = self.funIOrec(self.socket_router) |
|
503 | [self.dest ,self.buffer] = self.funIOrec(self.socket_router) | |
504 |
|
504 | |||
505 | self.buffer = BaseClass.run(self, self.buffer, **self.kwargs) |
|
505 | self.buffer = BaseClass.run(self, self.buffer, **self.kwargs) | |
506 |
|
506 | |||
507 | self.funIOsen(self.socket_router, self.buffer, self.dest) |
|
507 | self.funIOsen(self.socket_router, self.buffer, self.dest) | |
508 |
|
508 | |||
509 | print("%s done" %BaseClass.__name__) |
|
509 | print("%s done" %BaseClass.__name__) | |
510 | return 0 |
|
510 | return 0 | |
511 |
|
511 | |||
512 |
|
512 | |||
513 | def run(self): |
|
513 | def run(self): | |
514 |
|
514 | |||
515 | if self.typeProc is "ProcUnit": |
|
515 | if self.typeProc is "ProcUnit": | |
516 |
|
516 | |||
517 | self.socket_p = self.sockPublishing() |
|
517 | self.socket_p = self.sockPublishing() | |
518 |
|
518 | |||
519 | if 'Reader' not in self.dictProcs[self.id].name: |
|
519 | if 'Reader' not in self.dictProcs[self.id].name: | |
520 | self.socket_l = self.sockListening(self.inputId) |
|
520 | self.socket_l = self.sockListening(self.inputId) | |
521 | self.runProc() |
|
521 | self.runProc() | |
522 |
|
522 | |||
523 | else: |
|
523 | else: | |
524 |
|
524 | |||
525 | self.runReader() |
|
525 | self.runReader() | |
526 |
|
526 | |||
527 | elif self.typeProc is "Operation": |
|
527 | elif self.typeProc is "Operation": | |
528 |
|
528 | |||
529 | self.socket_router = self.sockIO() |
|
529 | self.socket_router = self.sockIO() | |
530 |
|
530 | |||
531 | self.runOp() |
|
531 | self.runOp() | |
532 |
|
532 | |||
533 | else: |
|
533 | else: | |
534 | raise ValueError("Unknown type") |
|
534 | raise ValueError("Unknown type") | |
535 |
|
535 | |||
536 | return 0 |
|
536 | return 0 | |
537 |
|
537 | |||
538 | return MPClass No newline at end of file |
|
538 | return MPClass |
@@ -1,1321 +1,1335 | |||||
1 | import sys |
|
1 | import sys | |
2 | import numpy |
|
2 | import numpy | |
3 | from scipy import interpolate |
|
3 | from scipy import interpolate | |
4 | #TODO |
|
4 | #TODO | |
5 | #from schainpy import cSchain |
|
5 | #from schainpy import cSchain | |
6 | from .jroproc_base import ProcessingUnit, Operation |
|
6 | from schainpy.model.proc.jroproc_base import ProcessingUnit, MPDecorator, Operation | |
7 | from schainpy.model.data.jrodata import Voltage |
|
7 | from schainpy.model.data.jrodata import Voltage | |
8 | from time import time |
|
|||
9 | from schainpy.utils import log |
|
8 | from schainpy.utils import log | |
|
9 | from time import time | |||
10 |
|
10 | |||
11 |
|
11 | |||
|
12 | @MPDecorator | |||
12 | class VoltageProc(ProcessingUnit): |
|
13 | class VoltageProc(ProcessingUnit): | |
|
14 | ||||
|
15 | METHODS = {} #yong | |||
13 |
|
16 | |||
|
17 | def __init__(self):#, **kwargs): #yong | |||
14 |
|
18 | |||
15 |
|
|
19 | ProcessingUnit.__init__(self)#, **kwargs) | |
16 |
|
||||
17 | ProcessingUnit.__init__(self, **kwargs) |
|
|||
18 |
|
20 | |||
19 | # self.objectDict = {} |
|
21 | # self.objectDict = {} | |
20 | self.dataOut = Voltage() |
|
22 | self.dataOut = Voltage() | |
21 | self.flip = 1 |
|
23 | self.flip = 1 | |
|
24 | self.setupReq = False #yong | |||
22 |
|
25 | |||
23 | def run(self): |
|
26 | def run(self): | |
|
27 | ||||
24 | if self.dataIn.type == 'AMISR': |
|
28 | if self.dataIn.type == 'AMISR': | |
25 | self.__updateObjFromAmisrInput() |
|
29 | self.__updateObjFromAmisrInput() | |
26 |
|
30 | |||
27 | if self.dataIn.type == 'Voltage': |
|
31 | if self.dataIn.type == 'Voltage': | |
28 | self.dataOut.copy(self.dataIn) |
|
32 | self.dataOut.copy(self.dataIn) | |
29 |
|
33 | |||
30 | # self.dataOut.copy(self.dataIn) |
|
34 | # self.dataOut.copy(self.dataIn) | |
31 |
|
35 | |||
32 | def __updateObjFromAmisrInput(self): |
|
36 | def __updateObjFromAmisrInput(self): | |
33 |
|
37 | |||
34 | self.dataOut.timeZone = self.dataIn.timeZone |
|
38 | self.dataOut.timeZone = self.dataIn.timeZone | |
35 | self.dataOut.dstFlag = self.dataIn.dstFlag |
|
39 | self.dataOut.dstFlag = self.dataIn.dstFlag | |
36 | self.dataOut.errorCount = self.dataIn.errorCount |
|
40 | self.dataOut.errorCount = self.dataIn.errorCount | |
37 | self.dataOut.useLocalTime = self.dataIn.useLocalTime |
|
41 | self.dataOut.useLocalTime = self.dataIn.useLocalTime | |
38 |
|
42 | |||
39 | self.dataOut.flagNoData = self.dataIn.flagNoData |
|
43 | self.dataOut.flagNoData = self.dataIn.flagNoData | |
40 | self.dataOut.data = self.dataIn.data |
|
44 | self.dataOut.data = self.dataIn.data | |
41 | self.dataOut.utctime = self.dataIn.utctime |
|
45 | self.dataOut.utctime = self.dataIn.utctime | |
42 | self.dataOut.channelList = self.dataIn.channelList |
|
46 | self.dataOut.channelList = self.dataIn.channelList | |
43 | # self.dataOut.timeInterval = self.dataIn.timeInterval |
|
47 | # self.dataOut.timeInterval = self.dataIn.timeInterval | |
44 | self.dataOut.heightList = self.dataIn.heightList |
|
48 | self.dataOut.heightList = self.dataIn.heightList | |
45 | self.dataOut.nProfiles = self.dataIn.nProfiles |
|
49 | self.dataOut.nProfiles = self.dataIn.nProfiles | |
46 |
|
50 | |||
47 | self.dataOut.nCohInt = self.dataIn.nCohInt |
|
51 | self.dataOut.nCohInt = self.dataIn.nCohInt | |
48 | self.dataOut.ippSeconds = self.dataIn.ippSeconds |
|
52 | self.dataOut.ippSeconds = self.dataIn.ippSeconds | |
49 | self.dataOut.frequency = self.dataIn.frequency |
|
53 | self.dataOut.frequency = self.dataIn.frequency | |
50 |
|
54 | |||
51 | self.dataOut.azimuth = self.dataIn.azimuth |
|
55 | self.dataOut.azimuth = self.dataIn.azimuth | |
52 | self.dataOut.zenith = self.dataIn.zenith |
|
56 | self.dataOut.zenith = self.dataIn.zenith | |
53 |
|
57 | |||
54 | self.dataOut.beam.codeList = self.dataIn.beam.codeList |
|
58 | self.dataOut.beam.codeList = self.dataIn.beam.codeList | |
55 | self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList |
|
59 | self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList | |
56 | self.dataOut.beam.zenithList = self.dataIn.beam.zenithList |
|
60 | self.dataOut.beam.zenithList = self.dataIn.beam.zenithList | |
57 | # |
|
61 | # | |
58 | # pass# |
|
62 | # pass# | |
59 | # |
|
63 | # | |
60 | # def init(self): |
|
64 | # def init(self): | |
61 | # |
|
65 | # | |
62 | # |
|
66 | # | |
63 | # if self.dataIn.type == 'AMISR': |
|
67 | # if self.dataIn.type == 'AMISR': | |
64 | # self.__updateObjFromAmisrInput() |
|
68 | # self.__updateObjFromAmisrInput() | |
65 | # |
|
69 | # | |
66 | # if self.dataIn.type == 'Voltage': |
|
70 | # if self.dataIn.type == 'Voltage': | |
67 | # self.dataOut.copy(self.dataIn) |
|
71 | # self.dataOut.copy(self.dataIn) | |
68 | # # No necesita copiar en cada init() los atributos de dataIn |
|
72 | # # No necesita copiar en cada init() los atributos de dataIn | |
69 | # # la copia deberia hacerse por cada nuevo bloque de datos |
|
73 | # # la copia deberia hacerse por cada nuevo bloque de datos | |
70 |
|
74 | |||
71 | def selectChannels(self, channelList): |
|
75 | def selectChannels(self, channelList): | |
72 |
|
76 | |||
73 | channelIndexList = [] |
|
77 | channelIndexList = [] | |
74 |
|
78 | |||
75 | for channel in channelList: |
|
79 | for channel in channelList: | |
76 | if channel not in self.dataOut.channelList: |
|
80 | if channel not in self.dataOut.channelList: | |
77 | raise ValueError("Channel %d is not in %s" %(channel, str(self.dataOut.channelList))) |
|
81 | raise ValueError("Channel %d is not in %s" %(channel, str(self.dataOut.channelList))) | |
78 |
|
82 | |||
79 | index = self.dataOut.channelList.index(channel) |
|
83 | index = self.dataOut.channelList.index(channel) | |
80 | channelIndexList.append(index) |
|
84 | channelIndexList.append(index) | |
81 |
|
85 | |||
82 | self.selectChannelsByIndex(channelIndexList) |
|
86 | self.selectChannelsByIndex(channelIndexList) | |
83 |
|
87 | |||
84 | def selectChannelsByIndex(self, channelIndexList): |
|
88 | def selectChannelsByIndex(self, channelIndexList): | |
85 | """ |
|
89 | """ | |
86 | Selecciona un bloque de datos en base a canales segun el channelIndexList |
|
90 | Selecciona un bloque de datos en base a canales segun el channelIndexList | |
87 |
|
91 | |||
88 | Input: |
|
92 | Input: | |
89 | channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7] |
|
93 | channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7] | |
90 |
|
94 | |||
91 | Affected: |
|
95 | Affected: | |
92 | self.dataOut.data |
|
96 | self.dataOut.data | |
93 | self.dataOut.channelIndexList |
|
97 | self.dataOut.channelIndexList | |
94 | self.dataOut.nChannels |
|
98 | self.dataOut.nChannels | |
95 | self.dataOut.m_ProcessingHeader.totalSpectra |
|
99 | self.dataOut.m_ProcessingHeader.totalSpectra | |
96 | self.dataOut.systemHeaderObj.numChannels |
|
100 | self.dataOut.systemHeaderObj.numChannels | |
97 | self.dataOut.m_ProcessingHeader.blockSize |
|
101 | self.dataOut.m_ProcessingHeader.blockSize | |
98 |
|
102 | |||
99 | Return: |
|
103 | Return: | |
100 | None |
|
104 | None | |
101 | """ |
|
105 | """ | |
102 |
|
106 | |||
103 | for channelIndex in channelIndexList: |
|
107 | for channelIndex in channelIndexList: | |
104 | if channelIndex not in self.dataOut.channelIndexList: |
|
108 | if channelIndex not in self.dataOut.channelIndexList: | |
105 | print(channelIndexList) |
|
109 | print(channelIndexList) | |
106 | raise ValueError("The value %d in channelIndexList is not valid" %channelIndex) |
|
110 | raise ValueError("The value %d in channelIndexList is not valid" %channelIndex) | |
107 |
|
111 | |||
108 | if self.dataOut.flagDataAsBlock: |
|
112 | if self.dataOut.flagDataAsBlock: | |
109 | """ |
|
113 | """ | |
110 | Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis] |
|
114 | Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis] | |
111 | """ |
|
115 | """ | |
112 | data = self.dataOut.data[channelIndexList,:,:] |
|
116 | data = self.dataOut.data[channelIndexList,:,:] | |
113 | else: |
|
117 | else: | |
114 | data = self.dataOut.data[channelIndexList,:] |
|
118 | data = self.dataOut.data[channelIndexList,:] | |
115 |
|
119 | |||
116 | self.dataOut.data = data |
|
120 | self.dataOut.data = data | |
117 | self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList] |
|
121 | self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList] | |
118 | # self.dataOut.nChannels = nChannels |
|
122 | # self.dataOut.nChannels = nChannels | |
119 |
|
123 | |||
120 | return 1 |
|
124 | return 1 | |
121 |
|
125 | |||
122 | def selectHeights(self, minHei=None, maxHei=None): |
|
126 | def selectHeights(self, minHei=None, maxHei=None): | |
123 | """ |
|
127 | """ | |
124 | Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango |
|
128 | Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango | |
125 | minHei <= height <= maxHei |
|
129 | minHei <= height <= maxHei | |
126 |
|
130 | |||
127 | Input: |
|
131 | Input: | |
128 | minHei : valor minimo de altura a considerar |
|
132 | minHei : valor minimo de altura a considerar | |
129 | maxHei : valor maximo de altura a considerar |
|
133 | maxHei : valor maximo de altura a considerar | |
130 |
|
134 | |||
131 | Affected: |
|
135 | Affected: | |
132 | Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex |
|
136 | Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex | |
133 |
|
137 | |||
134 | Return: |
|
138 | Return: | |
135 | 1 si el metodo se ejecuto con exito caso contrario devuelve 0 |
|
139 | 1 si el metodo se ejecuto con exito caso contrario devuelve 0 | |
136 | """ |
|
140 | """ | |
137 |
|
141 | |||
138 | if minHei == None: |
|
142 | if minHei == None: | |
139 | minHei = self.dataOut.heightList[0] |
|
143 | minHei = self.dataOut.heightList[0] | |
140 |
|
144 | |||
141 | if maxHei == None: |
|
145 | if maxHei == None: | |
142 | maxHei = self.dataOut.heightList[-1] |
|
146 | maxHei = self.dataOut.heightList[-1] | |
143 |
|
147 | |||
144 | if (minHei < self.dataOut.heightList[0]): |
|
148 | if (minHei < self.dataOut.heightList[0]): | |
145 | minHei = self.dataOut.heightList[0] |
|
149 | minHei = self.dataOut.heightList[0] | |
146 |
|
150 | |||
147 | if (maxHei > self.dataOut.heightList[-1]): |
|
151 | if (maxHei > self.dataOut.heightList[-1]): | |
148 | maxHei = self.dataOut.heightList[-1] |
|
152 | maxHei = self.dataOut.heightList[-1] | |
149 |
|
153 | |||
150 | minIndex = 0 |
|
154 | minIndex = 0 | |
151 | maxIndex = 0 |
|
155 | maxIndex = 0 | |
152 | heights = self.dataOut.heightList |
|
156 | heights = self.dataOut.heightList | |
153 |
|
157 | |||
154 | inda = numpy.where(heights >= minHei) |
|
158 | inda = numpy.where(heights >= minHei) | |
155 | indb = numpy.where(heights <= maxHei) |
|
159 | indb = numpy.where(heights <= maxHei) | |
156 |
|
160 | |||
157 | try: |
|
161 | try: | |
158 | minIndex = inda[0][0] |
|
162 | minIndex = inda[0][0] | |
159 | except: |
|
163 | except: | |
160 | minIndex = 0 |
|
164 | minIndex = 0 | |
161 |
|
165 | |||
162 | try: |
|
166 | try: | |
163 | maxIndex = indb[0][-1] |
|
167 | maxIndex = indb[0][-1] | |
164 | except: |
|
168 | except: | |
165 | maxIndex = len(heights) |
|
169 | maxIndex = len(heights) | |
166 |
|
170 | |||
167 | self.selectHeightsByIndex(minIndex, maxIndex) |
|
171 | self.selectHeightsByIndex(minIndex, maxIndex) | |
168 |
|
172 | |||
169 | return 1 |
|
173 | return 1 | |
170 |
|
174 | |||
171 |
|
175 | |||
172 | def selectHeightsByIndex(self, minIndex, maxIndex): |
|
176 | def selectHeightsByIndex(self, minIndex, maxIndex): | |
173 | """ |
|
177 | """ | |
174 | Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango |
|
178 | Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango | |
175 | minIndex <= index <= maxIndex |
|
179 | minIndex <= index <= maxIndex | |
176 |
|
180 | |||
177 | Input: |
|
181 | Input: | |
178 | minIndex : valor de indice minimo de altura a considerar |
|
182 | minIndex : valor de indice minimo de altura a considerar | |
179 | maxIndex : valor de indice maximo de altura a considerar |
|
183 | maxIndex : valor de indice maximo de altura a considerar | |
180 |
|
184 | |||
181 | Affected: |
|
185 | Affected: | |
182 | self.dataOut.data |
|
186 | self.dataOut.data | |
183 | self.dataOut.heightList |
|
187 | self.dataOut.heightList | |
184 |
|
188 | |||
185 | Return: |
|
189 | Return: | |
186 | 1 si el metodo se ejecuto con exito caso contrario devuelve 0 |
|
190 | 1 si el metodo se ejecuto con exito caso contrario devuelve 0 | |
187 | """ |
|
191 | """ | |
188 |
|
192 | |||
189 | if (minIndex < 0) or (minIndex > maxIndex): |
|
193 | if (minIndex < 0) or (minIndex > maxIndex): | |
190 | raise ValueError("Height index range (%d,%d) is not valid" % (minIndex, maxIndex)) |
|
194 | raise ValueError("Height index range (%d,%d) is not valid" % (minIndex, maxIndex)) | |
191 |
|
195 | |||
192 | if (maxIndex >= self.dataOut.nHeights): |
|
196 | if (maxIndex >= self.dataOut.nHeights): | |
193 | maxIndex = self.dataOut.nHeights |
|
197 | maxIndex = self.dataOut.nHeights | |
194 |
|
198 | |||
195 | #voltage |
|
199 | #voltage | |
196 | if self.dataOut.flagDataAsBlock: |
|
200 | if self.dataOut.flagDataAsBlock: | |
197 | """ |
|
201 | """ | |
198 | Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis] |
|
202 | Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis] | |
199 | """ |
|
203 | """ | |
200 | data = self.dataOut.data[:,:, minIndex:maxIndex] |
|
204 | data = self.dataOut.data[:,:, minIndex:maxIndex] | |
201 | else: |
|
205 | else: | |
202 | data = self.dataOut.data[:, minIndex:maxIndex] |
|
206 | data = self.dataOut.data[:, minIndex:maxIndex] | |
203 |
|
207 | |||
204 | # firstHeight = self.dataOut.heightList[minIndex] |
|
208 | # firstHeight = self.dataOut.heightList[minIndex] | |
205 |
|
209 | |||
206 | self.dataOut.data = data |
|
210 | self.dataOut.data = data | |
207 | self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex] |
|
211 | self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex] | |
208 |
|
212 | |||
209 | if self.dataOut.nHeights <= 1: |
|
213 | if self.dataOut.nHeights <= 1: | |
210 | raise ValueError("selectHeights: Too few heights. Current number of heights is %d" %(self.dataOut.nHeights)) |
|
214 | raise ValueError("selectHeights: Too few heights. Current number of heights is %d" %(self.dataOut.nHeights)) | |
211 |
|
215 | |||
212 | return 1 |
|
216 | return 1 | |
213 |
|
217 | |||
214 |
|
218 | |||
215 | def filterByHeights(self, window): |
|
219 | def filterByHeights(self, window): | |
216 |
|
220 | |||
217 | deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0] |
|
221 | deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0] | |
218 |
|
222 | |||
219 | if window == None: |
|
223 | if window == None: | |
220 | window = (self.dataOut.radarControllerHeaderObj.txA/self.dataOut.radarControllerHeaderObj.nBaud) / deltaHeight |
|
224 | window = (self.dataOut.radarControllerHeaderObj.txA/self.dataOut.radarControllerHeaderObj.nBaud) / deltaHeight | |
221 |
|
225 | |||
222 | newdelta = deltaHeight * window |
|
226 | newdelta = deltaHeight * window | |
223 | r = self.dataOut.nHeights % window |
|
227 | r = self.dataOut.nHeights % window | |
224 | newheights = (self.dataOut.nHeights-r)/window |
|
228 | newheights = (self.dataOut.nHeights-r)/window | |
225 |
|
229 | |||
226 | if newheights <= 1: |
|
230 | if newheights <= 1: | |
227 | raise ValueError("filterByHeights: Too few heights. Current number of heights is %d and window is %d" %(self.dataOut.nHeights, window)) |
|
231 | raise ValueError("filterByHeights: Too few heights. Current number of heights is %d and window is %d" %(self.dataOut.nHeights, window)) | |
228 |
|
232 | |||
229 | if self.dataOut.flagDataAsBlock: |
|
233 | if self.dataOut.flagDataAsBlock: | |
230 | """ |
|
234 | """ | |
231 | Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis] |
|
235 | Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis] | |
232 | """ |
|
236 | """ | |
233 | buffer = self.dataOut.data[:, :, 0:self.dataOut.nHeights-r] |
|
237 | buffer = self.dataOut.data[:, :, 0:self.dataOut.nHeights-r] | |
234 | buffer = buffer.reshape(self.dataOut.nChannels,self.dataOut.nProfiles,self.dataOut.nHeights/window,window) |
|
238 | buffer = buffer.reshape(self.dataOut.nChannels,self.dataOut.nProfiles,self.dataOut.nHeights/window,window) | |
235 | buffer = numpy.sum(buffer,3) |
|
239 | buffer = numpy.sum(buffer,3) | |
236 |
|
240 | |||
237 | else: |
|
241 | else: | |
238 | buffer = self.dataOut.data[:,0:self.dataOut.nHeights-r] |
|
242 | buffer = self.dataOut.data[:,0:self.dataOut.nHeights-r] | |
239 | buffer = buffer.reshape(self.dataOut.nChannels,self.dataOut.nHeights/window,window) |
|
243 | buffer = buffer.reshape(self.dataOut.nChannels,self.dataOut.nHeights/window,window) | |
240 | buffer = numpy.sum(buffer,2) |
|
244 | buffer = numpy.sum(buffer,2) | |
241 |
|
245 | |||
242 | self.dataOut.data = buffer |
|
246 | self.dataOut.data = buffer | |
243 | self.dataOut.heightList = self.dataOut.heightList[0] + numpy.arange( newheights )*newdelta |
|
247 | self.dataOut.heightList = self.dataOut.heightList[0] + numpy.arange( newheights )*newdelta | |
244 | self.dataOut.windowOfFilter = window |
|
248 | self.dataOut.windowOfFilter = window | |
245 |
|
249 | |||
246 | def setH0(self, h0, deltaHeight = None): |
|
250 | def setH0(self, h0, deltaHeight = None): | |
247 |
|
251 | |||
248 | if not deltaHeight: |
|
252 | if not deltaHeight: | |
249 | deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0] |
|
253 | deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0] | |
250 |
|
254 | |||
251 | nHeights = self.dataOut.nHeights |
|
255 | nHeights = self.dataOut.nHeights | |
252 |
|
256 | |||
253 | newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight |
|
257 | newHeiRange = h0 + numpy.arange(nHeights)*deltaHeight | |
254 |
|
258 | |||
255 | self.dataOut.heightList = newHeiRange |
|
259 | self.dataOut.heightList = newHeiRange | |
256 |
|
260 | |||
257 | def deFlip(self, channelList = []): |
|
261 | def deFlip(self, channelList = []): | |
258 |
|
262 | |||
259 | data = self.dataOut.data.copy() |
|
263 | data = self.dataOut.data.copy() | |
260 |
|
264 | |||
261 | if self.dataOut.flagDataAsBlock: |
|
265 | if self.dataOut.flagDataAsBlock: | |
262 | flip = self.flip |
|
266 | flip = self.flip | |
263 | profileList = list(range(self.dataOut.nProfiles)) |
|
267 | profileList = list(range(self.dataOut.nProfiles)) | |
264 |
|
268 | |||
265 | if not channelList: |
|
269 | if not channelList: | |
266 | for thisProfile in profileList: |
|
270 | for thisProfile in profileList: | |
267 | data[:,thisProfile,:] = data[:,thisProfile,:]*flip |
|
271 | data[:,thisProfile,:] = data[:,thisProfile,:]*flip | |
268 | flip *= -1.0 |
|
272 | flip *= -1.0 | |
269 | else: |
|
273 | else: | |
270 | for thisChannel in channelList: |
|
274 | for thisChannel in channelList: | |
271 | if thisChannel not in self.dataOut.channelList: |
|
275 | if thisChannel not in self.dataOut.channelList: | |
272 | continue |
|
276 | continue | |
273 |
|
277 | |||
274 | for thisProfile in profileList: |
|
278 | for thisProfile in profileList: | |
275 | data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip |
|
279 | data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip | |
276 | flip *= -1.0 |
|
280 | flip *= -1.0 | |
277 |
|
281 | |||
278 | self.flip = flip |
|
282 | self.flip = flip | |
279 |
|
283 | |||
280 | else: |
|
284 | else: | |
281 | if not channelList: |
|
285 | if not channelList: | |
282 | data[:,:] = data[:,:]*self.flip |
|
286 | data[:,:] = data[:,:]*self.flip | |
283 | else: |
|
287 | else: | |
284 | for thisChannel in channelList: |
|
288 | for thisChannel in channelList: | |
285 | if thisChannel not in self.dataOut.channelList: |
|
289 | if thisChannel not in self.dataOut.channelList: | |
286 | continue |
|
290 | continue | |
287 |
|
291 | |||
288 | data[thisChannel,:] = data[thisChannel,:]*self.flip |
|
292 | data[thisChannel,:] = data[thisChannel,:]*self.flip | |
289 |
|
293 | |||
290 | self.flip *= -1. |
|
294 | self.flip *= -1. | |
291 |
|
295 | |||
292 | self.dataOut.data = data |
|
296 | self.dataOut.data = data | |
293 |
|
297 | |||
294 | def setRadarFrequency(self, frequency=None): |
|
298 | def setRadarFrequency(self, frequency=None): | |
295 |
|
299 | |||
296 | if frequency != None: |
|
300 | if frequency != None: | |
297 | self.dataOut.frequency = frequency |
|
301 | self.dataOut.frequency = frequency | |
298 |
|
302 | |||
299 | return 1 |
|
303 | return 1 | |
300 |
|
304 | |||
301 | def interpolateHeights(self, topLim, botLim): |
|
305 | def interpolateHeights(self, topLim, botLim): | |
302 | #69 al 72 para julia |
|
306 | #69 al 72 para julia | |
303 | #82-84 para meteoros |
|
307 | #82-84 para meteoros | |
304 | if len(numpy.shape(self.dataOut.data))==2: |
|
308 | if len(numpy.shape(self.dataOut.data))==2: | |
305 | sampInterp = (self.dataOut.data[:,botLim-1] + self.dataOut.data[:,topLim+1])/2 |
|
309 | sampInterp = (self.dataOut.data[:,botLim-1] + self.dataOut.data[:,topLim+1])/2 | |
306 | sampInterp = numpy.transpose(numpy.tile(sampInterp,(topLim-botLim + 1,1))) |
|
310 | sampInterp = numpy.transpose(numpy.tile(sampInterp,(topLim-botLim + 1,1))) | |
307 | #self.dataOut.data[:,botLim:limSup+1] = sampInterp |
|
311 | #self.dataOut.data[:,botLim:limSup+1] = sampInterp | |
308 | self.dataOut.data[:,botLim:topLim+1] = sampInterp |
|
312 | self.dataOut.data[:,botLim:topLim+1] = sampInterp | |
309 | else: |
|
313 | else: | |
310 | nHeights = self.dataOut.data.shape[2] |
|
314 | nHeights = self.dataOut.data.shape[2] | |
311 | x = numpy.hstack((numpy.arange(botLim),numpy.arange(topLim+1,nHeights))) |
|
315 | x = numpy.hstack((numpy.arange(botLim),numpy.arange(topLim+1,nHeights))) | |
312 | y = self.dataOut.data[:,:,list(range(botLim))+list(range(topLim+1,nHeights))] |
|
316 | y = self.dataOut.data[:,:,list(range(botLim))+list(range(topLim+1,nHeights))] | |
313 | f = interpolate.interp1d(x, y, axis = 2) |
|
317 | f = interpolate.interp1d(x, y, axis = 2) | |
314 | xnew = numpy.arange(botLim,topLim+1) |
|
318 | xnew = numpy.arange(botLim,topLim+1) | |
315 | ynew = f(xnew) |
|
319 | ynew = f(xnew) | |
316 |
|
320 | |||
317 | self.dataOut.data[:,:,botLim:topLim+1] = ynew |
|
321 | self.dataOut.data[:,:,botLim:topLim+1] = ynew | |
318 |
|
322 | |||
319 | # import collections |
|
323 | # import collections | |
320 |
|
324 | @MPDecorator | ||
321 | class CohInt(Operation): |
|
325 | class CohInt(Operation): | |
322 |
|
326 | |||
323 | isConfig = False |
|
327 | isConfig = False | |
324 | __profIndex = 0 |
|
328 | __profIndex = 0 | |
325 | __byTime = False |
|
329 | __byTime = False | |
326 | __initime = None |
|
330 | __initime = None | |
327 | __lastdatatime = None |
|
331 | __lastdatatime = None | |
328 | __integrationtime = None |
|
332 | __integrationtime = None | |
329 | __buffer = None |
|
333 | __buffer = None | |
330 | __bufferStride = [] |
|
334 | __bufferStride = [] | |
331 | __dataReady = False |
|
335 | __dataReady = False | |
332 | __profIndexStride = 0 |
|
336 | __profIndexStride = 0 | |
333 | __dataToPutStride = False |
|
337 | __dataToPutStride = False | |
334 | n = None |
|
338 | n = None | |
335 |
|
339 | |||
336 |
def __init__(self |
|
340 | def __init__(self):#, **kwargs): | |
337 |
|
341 | |||
338 |
Operation.__init__(self |
|
342 | Operation.__init__(self)#, **kwargs) | |
339 |
|
343 | |||
340 | # self.isConfig = False |
|
344 | # self.isConfig = False | |
341 |
|
345 | |||
342 | def setup(self, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False): |
|
346 | def setup(self, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False): | |
343 | """ |
|
347 | """ | |
344 | Set the parameters of the integration class. |
|
348 | Set the parameters of the integration class. | |
345 |
|
349 | |||
346 | Inputs: |
|
350 | Inputs: | |
347 |
|
351 | |||
348 | n : Number of coherent integrations |
|
352 | n : Number of coherent integrations | |
349 | timeInterval : Time of integration. If the parameter "n" is selected this one does not work |
|
353 | timeInterval : Time of integration. If the parameter "n" is selected this one does not work | |
350 | overlapping : |
|
354 | overlapping : | |
351 | """ |
|
355 | """ | |
352 |
|
356 | |||
353 | self.__initime = None |
|
357 | self.__initime = None | |
354 | self.__lastdatatime = 0 |
|
358 | self.__lastdatatime = 0 | |
355 | self.__buffer = None |
|
359 | self.__buffer = None | |
356 | self.__dataReady = False |
|
360 | self.__dataReady = False | |
357 | self.byblock = byblock |
|
361 | self.byblock = byblock | |
358 | self.stride = stride |
|
362 | self.stride = stride | |
359 |
|
363 | |||
360 | if n == None and timeInterval == None: |
|
364 | if n == None and timeInterval == None: | |
361 | raise ValueError("n or timeInterval should be specified ...") |
|
365 | raise ValueError("n or timeInterval should be specified ...") | |
362 |
|
366 | |||
363 | if n != None: |
|
367 | if n != None: | |
364 | self.n = n |
|
368 | self.n = n | |
365 | self.__byTime = False |
|
369 | self.__byTime = False | |
366 | else: |
|
370 | else: | |
367 | self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line |
|
371 | self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line | |
368 | self.n = 9999 |
|
372 | self.n = 9999 | |
369 | self.__byTime = True |
|
373 | self.__byTime = True | |
370 |
|
374 | |||
371 | if overlapping: |
|
375 | if overlapping: | |
372 | self.__withOverlapping = True |
|
376 | self.__withOverlapping = True | |
373 | self.__buffer = None |
|
377 | self.__buffer = None | |
374 | else: |
|
378 | else: | |
375 | self.__withOverlapping = False |
|
379 | self.__withOverlapping = False | |
376 | self.__buffer = 0 |
|
380 | self.__buffer = 0 | |
377 |
|
381 | |||
378 | self.__profIndex = 0 |
|
382 | self.__profIndex = 0 | |
379 |
|
383 | |||
380 | def putData(self, data): |
|
384 | def putData(self, data): | |
381 |
|
385 | |||
382 | """ |
|
386 | """ | |
383 | Add a profile to the __buffer and increase in one the __profileIndex |
|
387 | Add a profile to the __buffer and increase in one the __profileIndex | |
384 |
|
388 | |||
385 | """ |
|
389 | """ | |
386 |
|
390 | |||
387 | if not self.__withOverlapping: |
|
391 | if not self.__withOverlapping: | |
388 | self.__buffer += data.copy() |
|
392 | self.__buffer += data.copy() | |
389 | self.__profIndex += 1 |
|
393 | self.__profIndex += 1 | |
390 | return |
|
394 | return | |
391 |
|
395 | |||
392 | #Overlapping data |
|
396 | #Overlapping data | |
393 | nChannels, nHeis = data.shape |
|
397 | nChannels, nHeis = data.shape | |
394 | data = numpy.reshape(data, (1, nChannels, nHeis)) |
|
398 | data = numpy.reshape(data, (1, nChannels, nHeis)) | |
395 |
|
399 | |||
396 | #If the buffer is empty then it takes the data value |
|
400 | #If the buffer is empty then it takes the data value | |
397 | if self.__buffer is None: |
|
401 | if self.__buffer is None: | |
398 | self.__buffer = data |
|
402 | self.__buffer = data | |
399 | self.__profIndex += 1 |
|
403 | self.__profIndex += 1 | |
400 | return |
|
404 | return | |
401 |
|
405 | |||
402 | #If the buffer length is lower than n then stakcing the data value |
|
406 | #If the buffer length is lower than n then stakcing the data value | |
403 | if self.__profIndex < self.n: |
|
407 | if self.__profIndex < self.n: | |
404 | self.__buffer = numpy.vstack((self.__buffer, data)) |
|
408 | self.__buffer = numpy.vstack((self.__buffer, data)) | |
405 | self.__profIndex += 1 |
|
409 | self.__profIndex += 1 | |
406 | return |
|
410 | return | |
407 |
|
411 | |||
408 | #If the buffer length is equal to n then replacing the last buffer value with the data value |
|
412 | #If the buffer length is equal to n then replacing the last buffer value with the data value | |
409 | self.__buffer = numpy.roll(self.__buffer, -1, axis=0) |
|
413 | self.__buffer = numpy.roll(self.__buffer, -1, axis=0) | |
410 | self.__buffer[self.n-1] = data |
|
414 | self.__buffer[self.n-1] = data | |
411 | self.__profIndex = self.n |
|
415 | self.__profIndex = self.n | |
412 | return |
|
416 | return | |
413 |
|
417 | |||
414 |
|
418 | |||
415 | def pushData(self): |
|
419 | def pushData(self): | |
416 | """ |
|
420 | """ | |
417 | Return the sum of the last profiles and the profiles used in the sum. |
|
421 | Return the sum of the last profiles and the profiles used in the sum. | |
418 |
|
422 | |||
419 | Affected: |
|
423 | Affected: | |
420 |
|
424 | |||
421 | self.__profileIndex |
|
425 | self.__profileIndex | |
422 |
|
426 | |||
423 | """ |
|
427 | """ | |
424 |
|
428 | |||
425 | if not self.__withOverlapping: |
|
429 | if not self.__withOverlapping: | |
426 | data = self.__buffer |
|
430 | data = self.__buffer | |
427 | n = self.__profIndex |
|
431 | n = self.__profIndex | |
428 |
|
432 | |||
429 | self.__buffer = 0 |
|
433 | self.__buffer = 0 | |
430 | self.__profIndex = 0 |
|
434 | self.__profIndex = 0 | |
431 |
|
435 | |||
432 | return data, n |
|
436 | return data, n | |
433 |
|
437 | |||
434 | #Integration with Overlapping |
|
438 | #Integration with Overlapping | |
435 | data = numpy.sum(self.__buffer, axis=0) |
|
439 | data = numpy.sum(self.__buffer, axis=0) | |
436 | # print data |
|
440 | # print data | |
437 | # raise |
|
441 | # raise | |
438 | n = self.__profIndex |
|
442 | n = self.__profIndex | |
439 |
|
443 | |||
440 | return data, n |
|
444 | return data, n | |
441 |
|
445 | |||
442 | def byProfiles(self, data): |
|
446 | def byProfiles(self, data): | |
443 |
|
447 | |||
444 | self.__dataReady = False |
|
448 | self.__dataReady = False | |
445 | avgdata = None |
|
449 | avgdata = None | |
446 | # n = None |
|
450 | # n = None | |
447 | # print data |
|
451 | # print data | |
448 | # raise |
|
452 | # raise | |
449 | self.putData(data) |
|
453 | self.putData(data) | |
450 |
|
454 | |||
451 | if self.__profIndex == self.n: |
|
455 | if self.__profIndex == self.n: | |
452 | avgdata, n = self.pushData() |
|
456 | avgdata, n = self.pushData() | |
453 | self.__dataReady = True |
|
457 | self.__dataReady = True | |
454 |
|
458 | |||
455 | return avgdata |
|
459 | return avgdata | |
456 |
|
460 | |||
457 | def byTime(self, data, datatime): |
|
461 | def byTime(self, data, datatime): | |
458 |
|
462 | |||
459 | self.__dataReady = False |
|
463 | self.__dataReady = False | |
460 | avgdata = None |
|
464 | avgdata = None | |
461 | n = None |
|
465 | n = None | |
462 |
|
466 | |||
463 | self.putData(data) |
|
467 | self.putData(data) | |
464 |
|
468 | |||
465 | if (datatime - self.__initime) >= self.__integrationtime: |
|
469 | if (datatime - self.__initime) >= self.__integrationtime: | |
466 | avgdata, n = self.pushData() |
|
470 | avgdata, n = self.pushData() | |
467 | self.n = n |
|
471 | self.n = n | |
468 | self.__dataReady = True |
|
472 | self.__dataReady = True | |
469 |
|
473 | |||
470 | return avgdata |
|
474 | return avgdata | |
471 |
|
475 | |||
472 | def integrateByStride(self, data, datatime): |
|
476 | def integrateByStride(self, data, datatime): | |
473 | # print data |
|
477 | # print data | |
474 | if self.__profIndex == 0: |
|
478 | if self.__profIndex == 0: | |
475 | self.__buffer = [[data.copy(), datatime]] |
|
479 | self.__buffer = [[data.copy(), datatime]] | |
476 | else: |
|
480 | else: | |
477 | self.__buffer.append([data.copy(),datatime]) |
|
481 | self.__buffer.append([data.copy(),datatime]) | |
478 | self.__profIndex += 1 |
|
482 | self.__profIndex += 1 | |
479 | self.__dataReady = False |
|
483 | self.__dataReady = False | |
480 |
|
484 | |||
481 | if self.__profIndex == self.n * self.stride : |
|
485 | if self.__profIndex == self.n * self.stride : | |
482 | self.__dataToPutStride = True |
|
486 | self.__dataToPutStride = True | |
483 | self.__profIndexStride = 0 |
|
487 | self.__profIndexStride = 0 | |
484 | self.__profIndex = 0 |
|
488 | self.__profIndex = 0 | |
485 | self.__bufferStride = [] |
|
489 | self.__bufferStride = [] | |
486 | for i in range(self.stride): |
|
490 | for i in range(self.stride): | |
487 | current = self.__buffer[i::self.stride] |
|
491 | current = self.__buffer[i::self.stride] | |
488 | data = numpy.sum([t[0] for t in current], axis=0) |
|
492 | data = numpy.sum([t[0] for t in current], axis=0) | |
489 | avgdatatime = numpy.average([t[1] for t in current]) |
|
493 | avgdatatime = numpy.average([t[1] for t in current]) | |
490 | # print data |
|
494 | # print data | |
491 | self.__bufferStride.append((data, avgdatatime)) |
|
495 | self.__bufferStride.append((data, avgdatatime)) | |
492 |
|
496 | |||
493 | if self.__dataToPutStride: |
|
497 | if self.__dataToPutStride: | |
494 | self.__dataReady = True |
|
498 | self.__dataReady = True | |
495 | self.__profIndexStride += 1 |
|
499 | self.__profIndexStride += 1 | |
496 | if self.__profIndexStride == self.stride: |
|
500 | if self.__profIndexStride == self.stride: | |
497 | self.__dataToPutStride = False |
|
501 | self.__dataToPutStride = False | |
498 | # print self.__bufferStride[self.__profIndexStride - 1] |
|
502 | # print self.__bufferStride[self.__profIndexStride - 1] | |
499 | # raise |
|
503 | # raise | |
500 | return self.__bufferStride[self.__profIndexStride - 1] |
|
504 | return self.__bufferStride[self.__profIndexStride - 1] | |
501 |
|
505 | |||
502 |
|
506 | |||
503 | return None, None |
|
507 | return None, None | |
504 |
|
508 | |||
505 | def integrate(self, data, datatime=None): |
|
509 | def integrate(self, data, datatime=None): | |
506 |
|
510 | |||
507 | if self.__initime == None: |
|
511 | if self.__initime == None: | |
508 | self.__initime = datatime |
|
512 | self.__initime = datatime | |
509 |
|
513 | |||
510 | if self.__byTime: |
|
514 | if self.__byTime: | |
511 | avgdata = self.byTime(data, datatime) |
|
515 | avgdata = self.byTime(data, datatime) | |
512 | else: |
|
516 | else: | |
513 | avgdata = self.byProfiles(data) |
|
517 | avgdata = self.byProfiles(data) | |
514 |
|
518 | |||
515 |
|
519 | |||
516 | self.__lastdatatime = datatime |
|
520 | self.__lastdatatime = datatime | |
517 |
|
521 | |||
518 | if avgdata is None: |
|
522 | if avgdata is None: | |
519 | return None, None |
|
523 | return None, None | |
520 |
|
524 | |||
521 | avgdatatime = self.__initime |
|
525 | avgdatatime = self.__initime | |
522 |
|
526 | |||
523 | deltatime = datatime - self.__lastdatatime |
|
527 | deltatime = datatime - self.__lastdatatime | |
524 |
|
528 | |||
525 | if not self.__withOverlapping: |
|
529 | if not self.__withOverlapping: | |
526 | self.__initime = datatime |
|
530 | self.__initime = datatime | |
527 | else: |
|
531 | else: | |
528 | self.__initime += deltatime |
|
532 | self.__initime += deltatime | |
529 |
|
533 | |||
530 | return avgdata, avgdatatime |
|
534 | return avgdata, avgdatatime | |
531 |
|
535 | |||
532 | def integrateByBlock(self, dataOut): |
|
536 | def integrateByBlock(self, dataOut): | |
533 |
|
537 | |||
534 | times = int(dataOut.data.shape[1]/self.n) |
|
538 | times = int(dataOut.data.shape[1]/self.n) | |
535 | avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex) |
|
539 | avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=numpy.complex) | |
536 |
|
540 | |||
537 | id_min = 0 |
|
541 | id_min = 0 | |
538 | id_max = self.n |
|
542 | id_max = self.n | |
539 |
|
543 | |||
540 | for i in range(times): |
|
544 | for i in range(times): | |
541 | junk = dataOut.data[:,id_min:id_max,:] |
|
545 | junk = dataOut.data[:,id_min:id_max,:] | |
542 | avgdata[:,i,:] = junk.sum(axis=1) |
|
546 | avgdata[:,i,:] = junk.sum(axis=1) | |
543 | id_min += self.n |
|
547 | id_min += self.n | |
544 | id_max += self.n |
|
548 | id_max += self.n | |
545 |
|
549 | |||
546 | timeInterval = dataOut.ippSeconds*self.n |
|
550 | timeInterval = dataOut.ippSeconds*self.n | |
547 | avgdatatime = (times - 1) * timeInterval + dataOut.utctime |
|
551 | avgdatatime = (times - 1) * timeInterval + dataOut.utctime | |
548 | self.__dataReady = True |
|
552 | self.__dataReady = True | |
549 | return avgdata, avgdatatime |
|
553 | return avgdata, avgdatatime | |
550 |
|
554 | |||
551 | def run(self, dataOut, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False, **kwargs): |
|
555 | def run(self, dataOut, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False, **kwargs): | |
|
556 | ||||
552 | if not self.isConfig: |
|
557 | if not self.isConfig: | |
553 | self.setup(n=n, stride=stride, timeInterval=timeInterval, overlapping=overlapping, byblock=byblock, **kwargs) |
|
558 | self.setup(n=n, stride=stride, timeInterval=timeInterval, overlapping=overlapping, byblock=byblock, **kwargs) | |
554 | self.isConfig = True |
|
559 | self.isConfig = True | |
555 |
|
560 | |||
556 | if dataOut.flagDataAsBlock: |
|
561 | if dataOut.flagDataAsBlock: | |
557 | """ |
|
562 | """ | |
558 | Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis] |
|
563 | Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis] | |
559 | """ |
|
564 | """ | |
560 | avgdata, avgdatatime = self.integrateByBlock(dataOut) |
|
565 | avgdata, avgdatatime = self.integrateByBlock(dataOut) | |
561 | dataOut.nProfiles /= self.n |
|
566 | dataOut.nProfiles /= self.n | |
562 | else: |
|
567 | else: | |
563 | if stride is None: |
|
568 | if stride is None: | |
564 | avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime) |
|
569 | avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime) | |
565 | else: |
|
570 | else: | |
566 | avgdata, avgdatatime = self.integrateByStride(dataOut.data, dataOut.utctime) |
|
571 | avgdata, avgdatatime = self.integrateByStride(dataOut.data, dataOut.utctime) | |
567 |
|
572 | |||
568 |
|
573 | |||
569 | # dataOut.timeInterval *= n |
|
574 | # dataOut.timeInterval *= n | |
570 | dataOut.flagNoData = True |
|
575 | dataOut.flagNoData = True | |
571 |
|
576 | |||
572 | if self.__dataReady: |
|
577 | if self.__dataReady: | |
573 | dataOut.data = avgdata |
|
578 | dataOut.data = avgdata | |
574 | dataOut.nCohInt *= self.n |
|
579 | dataOut.nCohInt *= self.n | |
575 | dataOut.utctime = avgdatatime |
|
580 | dataOut.utctime = avgdatatime | |
576 | # print avgdata, avgdatatime |
|
581 | # print avgdata, avgdatatime | |
577 | # raise |
|
582 | # raise | |
578 | # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt |
|
583 | # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt | |
579 | dataOut.flagNoData = False |
|
584 | dataOut.flagNoData = False | |
580 |
|
585 | return dataOut | ||
|
586 | @MPDecorator | |||
581 | class Decoder(Operation): |
|
587 | class Decoder(Operation): | |
582 |
|
588 | |||
583 | isConfig = False |
|
589 | isConfig = False | |
584 | __profIndex = 0 |
|
590 | __profIndex = 0 | |
585 |
|
591 | |||
586 | code = None |
|
592 | code = None | |
587 |
|
593 | |||
588 | nCode = None |
|
594 | nCode = None | |
589 | nBaud = None |
|
595 | nBaud = None | |
590 |
|
596 | |||
591 |
def __init__(self |
|
597 | def __init__(self):#, **kwargs): | |
592 |
|
598 | |||
593 |
Operation.__init__(self |
|
599 | Operation.__init__(self)#, **kwargs) | |
594 |
|
600 | |||
595 | self.times = None |
|
601 | self.times = None | |
596 | self.osamp = None |
|
602 | self.osamp = None | |
597 | # self.__setValues = False |
|
603 | # self.__setValues = False | |
598 | self.isConfig = False |
|
604 | # self.isConfig = False | |
599 |
|
605 | self.setupReq = False | ||
600 | def setup(self, code, osamp, dataOut): |
|
606 | def setup(self, code, osamp, dataOut): | |
601 |
|
607 | |||
602 | self.__profIndex = 0 |
|
608 | self.__profIndex = 0 | |
603 |
|
609 | |||
604 | self.code = code |
|
610 | self.code = code | |
605 |
|
611 | |||
606 | self.nCode = len(code) |
|
612 | self.nCode = len(code) | |
607 | self.nBaud = len(code[0]) |
|
613 | self.nBaud = len(code[0]) | |
608 |
|
614 | |||
609 | if (osamp != None) and (osamp >1): |
|
615 | if (osamp != None) and (osamp >1): | |
610 | self.osamp = osamp |
|
616 | self.osamp = osamp | |
611 | self.code = numpy.repeat(code, repeats=self.osamp, axis=1) |
|
617 | self.code = numpy.repeat(code, repeats=self.osamp, axis=1) | |
612 | self.nBaud = self.nBaud*self.osamp |
|
618 | self.nBaud = self.nBaud*self.osamp | |
613 |
|
619 | |||
614 | self.__nChannels = dataOut.nChannels |
|
620 | self.__nChannels = dataOut.nChannels | |
615 | self.__nProfiles = dataOut.nProfiles |
|
621 | self.__nProfiles = dataOut.nProfiles | |
616 | self.__nHeis = dataOut.nHeights |
|
622 | self.__nHeis = dataOut.nHeights | |
617 |
|
623 | |||
618 | if self.__nHeis < self.nBaud: |
|
624 | if self.__nHeis < self.nBaud: | |
619 | raise ValueError('Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud)) |
|
625 | raise ValueError('Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud)) | |
620 |
|
626 | |||
621 | #Frequency |
|
627 | #Frequency | |
622 | __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex) |
|
628 | __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=numpy.complex) | |
623 |
|
629 | |||
624 | __codeBuffer[:,0:self.nBaud] = self.code |
|
630 | __codeBuffer[:,0:self.nBaud] = self.code | |
625 |
|
631 | |||
626 | self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1)) |
|
632 | self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1)) | |
627 |
|
633 | |||
628 | if dataOut.flagDataAsBlock: |
|
634 | if dataOut.flagDataAsBlock: | |
629 |
|
635 | |||
630 | self.ndatadec = self.__nHeis #- self.nBaud + 1 |
|
636 | self.ndatadec = self.__nHeis #- self.nBaud + 1 | |
631 |
|
637 | |||
632 | self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex) |
|
638 | self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=numpy.complex) | |
633 |
|
639 | |||
634 | else: |
|
640 | else: | |
635 |
|
641 | |||
636 | #Time |
|
642 | #Time | |
637 | self.ndatadec = self.__nHeis #- self.nBaud + 1 |
|
643 | self.ndatadec = self.__nHeis #- self.nBaud + 1 | |
638 |
|
644 | |||
639 | self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex) |
|
645 | self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=numpy.complex) | |
640 |
|
646 | |||
641 | def __convolutionInFreq(self, data): |
|
647 | def __convolutionInFreq(self, data): | |
642 |
|
648 | |||
643 | fft_code = self.fft_code[self.__profIndex].reshape(1,-1) |
|
649 | fft_code = self.fft_code[self.__profIndex].reshape(1,-1) | |
644 |
|
650 | |||
645 | fft_data = numpy.fft.fft(data, axis=1) |
|
651 | fft_data = numpy.fft.fft(data, axis=1) | |
646 |
|
652 | |||
647 | conv = fft_data*fft_code |
|
653 | conv = fft_data*fft_code | |
648 |
|
654 | |||
649 | data = numpy.fft.ifft(conv,axis=1) |
|
655 | data = numpy.fft.ifft(conv,axis=1) | |
650 |
|
656 | |||
651 | return data |
|
657 | return data | |
652 |
|
658 | |||
653 | def __convolutionInFreqOpt(self, data): |
|
659 | def __convolutionInFreqOpt(self, data): | |
654 |
|
660 | |||
655 | raise NotImplementedError |
|
661 | raise NotImplementedError | |
656 |
|
662 | |||
657 | def __convolutionInTime(self, data): |
|
663 | def __convolutionInTime(self, data): | |
658 |
|
664 | |||
659 | code = self.code[self.__profIndex] |
|
665 | code = self.code[self.__profIndex] | |
660 | for i in range(self.__nChannels): |
|
666 | for i in range(self.__nChannels): | |
661 | self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:] |
|
667 | self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:] | |
662 |
|
668 | |||
663 | return self.datadecTime |
|
669 | return self.datadecTime | |
664 |
|
670 | |||
665 | def __convolutionByBlockInTime(self, data): |
|
671 | def __convolutionByBlockInTime(self, data): | |
666 |
|
672 | |||
667 | repetitions = self.__nProfiles / self.nCode |
|
673 | repetitions = self.__nProfiles / self.nCode | |
668 |
|
674 | |||
669 | junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize)) |
|
675 | junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize)) | |
670 | junk = junk.flatten() |
|
676 | junk = junk.flatten() | |
671 | code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud)) |
|
677 | code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud)) | |
672 | profilesList = range(self.__nProfiles) |
|
678 | profilesList = range(self.__nProfiles) | |
673 |
|
679 | |||
674 | for i in range(self.__nChannels): |
|
680 | for i in range(self.__nChannels): | |
675 | for j in profilesList: |
|
681 | for j in profilesList: | |
676 | self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:] |
|
682 | self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:] | |
677 | return self.datadecTime |
|
683 | return self.datadecTime | |
678 |
|
684 | |||
679 | def __convolutionByBlockInFreq(self, data): |
|
685 | def __convolutionByBlockInFreq(self, data): | |
680 |
|
686 | |||
681 | raise NotImplementedError("Decoder by frequency fro Blocks not implemented") |
|
687 | raise NotImplementedError("Decoder by frequency fro Blocks not implemented") | |
682 |
|
688 | |||
683 |
|
689 | |||
684 | fft_code = self.fft_code[self.__profIndex].reshape(1,-1) |
|
690 | fft_code = self.fft_code[self.__profIndex].reshape(1,-1) | |
685 |
|
691 | |||
686 | fft_data = numpy.fft.fft(data, axis=2) |
|
692 | fft_data = numpy.fft.fft(data, axis=2) | |
687 |
|
693 | |||
688 | conv = fft_data*fft_code |
|
694 | conv = fft_data*fft_code | |
689 |
|
695 | |||
690 | data = numpy.fft.ifft(conv,axis=2) |
|
696 | data = numpy.fft.ifft(conv,axis=2) | |
691 |
|
697 | |||
692 | return data |
|
698 | return data | |
693 |
|
699 | |||
694 |
|
700 | |||
695 | def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None): |
|
701 | def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None): | |
696 |
|
702 | |||
697 | if dataOut.flagDecodeData: |
|
703 | if dataOut.flagDecodeData: | |
698 | print("This data is already decoded, recoding again ...") |
|
704 | print("This data is already decoded, recoding again ...") | |
699 |
|
705 | |||
700 | if not self.isConfig: |
|
706 | if not self.isConfig: | |
701 |
|
707 | |||
702 | if code is None: |
|
708 | if code is None: | |
703 | if dataOut.code is None: |
|
709 | if dataOut.code is None: | |
704 | raise ValueError("Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type) |
|
710 | raise ValueError("Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type) | |
705 |
|
711 | |||
706 | code = dataOut.code |
|
712 | code = dataOut.code | |
707 | else: |
|
713 | else: | |
708 | code = numpy.array(code).reshape(nCode,nBaud) |
|
714 | code = numpy.array(code).reshape(nCode,nBaud) | |
709 | self.setup(code, osamp, dataOut) |
|
715 | self.setup(code, osamp, dataOut) | |
710 |
|
716 | |||
711 | self.isConfig = True |
|
717 | self.isConfig = True | |
712 |
|
718 | |||
713 | if mode == 3: |
|
719 | if mode == 3: | |
714 | sys.stderr.write("Decoder Warning: mode=%d is not valid, using mode=0\n" %mode) |
|
720 | sys.stderr.write("Decoder Warning: mode=%d is not valid, using mode=0\n" %mode) | |
715 |
|
721 | |||
716 | if times != None: |
|
722 | if times != None: | |
717 | sys.stderr.write("Decoder Warning: Argument 'times' in not used anymore\n") |
|
723 | sys.stderr.write("Decoder Warning: Argument 'times' in not used anymore\n") | |
718 |
|
724 | |||
719 | if self.code is None: |
|
725 | if self.code is None: | |
720 | print("Fail decoding: Code is not defined.") |
|
726 | print("Fail decoding: Code is not defined.") | |
721 | return |
|
727 | return | |
722 |
|
728 | |||
723 | self.__nProfiles = dataOut.nProfiles |
|
729 | self.__nProfiles = dataOut.nProfiles | |
724 | datadec = None |
|
730 | datadec = None | |
725 |
|
731 | |||
726 | if mode == 3: |
|
732 | if mode == 3: | |
727 | mode = 0 |
|
733 | mode = 0 | |
728 |
|
734 | |||
729 | if dataOut.flagDataAsBlock: |
|
735 | if dataOut.flagDataAsBlock: | |
730 | """ |
|
736 | """ | |
731 | Decoding when data have been read as block, |
|
737 | Decoding when data have been read as block, | |
732 | """ |
|
738 | """ | |
733 |
|
739 | |||
734 | if mode == 0: |
|
740 | if mode == 0: | |
735 | datadec = self.__convolutionByBlockInTime(dataOut.data) |
|
741 | datadec = self.__convolutionByBlockInTime(dataOut.data) | |
736 | if mode == 1: |
|
742 | if mode == 1: | |
737 | datadec = self.__convolutionByBlockInFreq(dataOut.data) |
|
743 | datadec = self.__convolutionByBlockInFreq(dataOut.data) | |
738 | else: |
|
744 | else: | |
739 | """ |
|
745 | """ | |
740 | Decoding when data have been read profile by profile |
|
746 | Decoding when data have been read profile by profile | |
741 | """ |
|
747 | """ | |
742 | if mode == 0: |
|
748 | if mode == 0: | |
743 | datadec = self.__convolutionInTime(dataOut.data) |
|
749 | datadec = self.__convolutionInTime(dataOut.data) | |
744 |
|
750 | |||
745 | if mode == 1: |
|
751 | if mode == 1: | |
746 | datadec = self.__convolutionInFreq(dataOut.data) |
|
752 | datadec = self.__convolutionInFreq(dataOut.data) | |
747 |
|
753 | |||
748 | if mode == 2: |
|
754 | if mode == 2: | |
749 | datadec = self.__convolutionInFreqOpt(dataOut.data) |
|
755 | datadec = self.__convolutionInFreqOpt(dataOut.data) | |
750 |
|
756 | |||
751 | if datadec is None: |
|
757 | if datadec is None: | |
752 | raise ValueError("Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode) |
|
758 | raise ValueError("Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode) | |
753 |
|
759 | |||
754 | dataOut.code = self.code |
|
760 | dataOut.code = self.code | |
755 | dataOut.nCode = self.nCode |
|
761 | dataOut.nCode = self.nCode | |
756 | dataOut.nBaud = self.nBaud |
|
762 | dataOut.nBaud = self.nBaud | |
757 |
|
763 | |||
758 | dataOut.data = datadec |
|
764 | dataOut.data = datadec | |
759 |
|
765 | |||
760 | dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]] |
|
766 | dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]] | |
761 |
|
767 | |||
762 | dataOut.flagDecodeData = True #asumo q la data esta decodificada |
|
768 | dataOut.flagDecodeData = True #asumo q la data esta decodificada | |
763 |
|
769 | |||
764 | if self.__profIndex == self.nCode-1: |
|
770 | if self.__profIndex == self.nCode-1: | |
765 | self.__profIndex = 0 |
|
771 | self.__profIndex = 0 | |
766 |
return |
|
772 | return dataOut | |
767 |
|
773 | |||
768 | self.__profIndex += 1 |
|
774 | self.__profIndex += 1 | |
769 |
|
775 | |||
770 |
return |
|
776 | return dataOut | |
771 | # dataOut.flagDeflipData = True #asumo q la data no esta sin flip |
|
777 | # dataOut.flagDeflipData = True #asumo q la data no esta sin flip | |
772 |
|
778 | |||
773 |
|
779 | @MPDecorator | ||
774 | class ProfileConcat(Operation): |
|
780 | class ProfileConcat(Operation): | |
775 |
|
781 | |||
776 | isConfig = False |
|
782 | isConfig = False | |
777 | buffer = None |
|
783 | buffer = None | |
778 |
|
784 | |||
779 |
def __init__(self |
|
785 | def __init__(self):#, **kwargs): | |
780 |
|
786 | |||
781 |
Operation.__init__(self |
|
787 | Operation.__init__(self)#, **kwargs) | |
782 | self.profileIndex = 0 |
|
788 | self.profileIndex = 0 | |
783 |
|
789 | |||
784 | def reset(self): |
|
790 | def reset(self): | |
785 | self.buffer = numpy.zeros_like(self.buffer) |
|
791 | self.buffer = numpy.zeros_like(self.buffer) | |
786 | self.start_index = 0 |
|
792 | self.start_index = 0 | |
787 | self.times = 1 |
|
793 | self.times = 1 | |
788 |
|
794 | |||
789 | def setup(self, data, m, n=1): |
|
795 | def setup(self, data, m, n=1): | |
790 | self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0])) |
|
796 | self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0])) | |
791 | self.nHeights = data.shape[1]#.nHeights |
|
797 | self.nHeights = data.shape[1]#.nHeights | |
792 | self.start_index = 0 |
|
798 | self.start_index = 0 | |
793 | self.times = 1 |
|
799 | self.times = 1 | |
794 |
|
800 | |||
795 | def concat(self, data): |
|
801 | def concat(self, data): | |
796 |
|
802 | |||
797 | self.buffer[:,self.start_index:self.nHeights*self.times] = data.copy() |
|
803 | self.buffer[:,self.start_index:self.nHeights*self.times] = data.copy() | |
798 | self.start_index = self.start_index + self.nHeights |
|
804 | self.start_index = self.start_index + self.nHeights | |
799 |
|
805 | |||
800 | def run(self, dataOut, m): |
|
806 | def run(self, dataOut, m): | |
801 |
|
807 | |||
802 | dataOut.flagNoData = True |
|
808 | dataOut.flagNoData = True | |
803 |
|
809 | |||
804 | if not self.isConfig: |
|
810 | if not self.isConfig: | |
805 | self.setup(dataOut.data, m, 1) |
|
811 | self.setup(dataOut.data, m, 1) | |
806 | self.isConfig = True |
|
812 | self.isConfig = True | |
807 |
|
813 | |||
808 | if dataOut.flagDataAsBlock: |
|
814 | if dataOut.flagDataAsBlock: | |
809 | raise ValueError("ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False") |
|
815 | raise ValueError("ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False") | |
810 |
|
816 | |||
811 | else: |
|
817 | else: | |
812 | self.concat(dataOut.data) |
|
818 | self.concat(dataOut.data) | |
813 | self.times += 1 |
|
819 | self.times += 1 | |
814 | if self.times > m: |
|
820 | if self.times > m: | |
815 | dataOut.data = self.buffer |
|
821 | dataOut.data = self.buffer | |
816 | self.reset() |
|
822 | self.reset() | |
817 | dataOut.flagNoData = False |
|
823 | dataOut.flagNoData = False | |
818 | # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas |
|
824 | # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas | |
819 | deltaHeight = dataOut.heightList[1] - dataOut.heightList[0] |
|
825 | deltaHeight = dataOut.heightList[1] - dataOut.heightList[0] | |
820 | xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m |
|
826 | xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m | |
821 | dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight) |
|
827 | dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight) | |
822 | dataOut.ippSeconds *= m |
|
828 | dataOut.ippSeconds *= m | |
823 |
|
829 | return dataOut | ||
|
830 | @MPDecorator | |||
824 | class ProfileSelector(Operation): |
|
831 | class ProfileSelector(Operation): | |
825 |
|
832 | |||
826 | profileIndex = None |
|
833 | profileIndex = None | |
827 | # Tamanho total de los perfiles |
|
834 | # Tamanho total de los perfiles | |
828 | nProfiles = None |
|
835 | nProfiles = None | |
829 |
|
836 | |||
830 |
def __init__(self |
|
837 | def __init__(self):#, **kwargs): | |
831 |
|
838 | |||
832 |
Operation.__init__(self |
|
839 | Operation.__init__(self)#, **kwargs) | |
833 | self.profileIndex = 0 |
|
840 | self.profileIndex = 0 | |
834 |
|
841 | |||
835 | def incProfileIndex(self): |
|
842 | def incProfileIndex(self): | |
836 |
|
843 | |||
837 | self.profileIndex += 1 |
|
844 | self.profileIndex += 1 | |
838 |
|
845 | |||
839 | if self.profileIndex >= self.nProfiles: |
|
846 | if self.profileIndex >= self.nProfiles: | |
840 | self.profileIndex = 0 |
|
847 | self.profileIndex = 0 | |
841 |
|
848 | |||
842 | def isThisProfileInRange(self, profileIndex, minIndex, maxIndex): |
|
849 | def isThisProfileInRange(self, profileIndex, minIndex, maxIndex): | |
843 |
|
850 | |||
844 | if profileIndex < minIndex: |
|
851 | if profileIndex < minIndex: | |
845 | return False |
|
852 | return False | |
846 |
|
853 | |||
847 | if profileIndex > maxIndex: |
|
854 | if profileIndex > maxIndex: | |
848 | return False |
|
855 | return False | |
849 |
|
856 | |||
850 | return True |
|
857 | return True | |
851 |
|
858 | |||
852 | def isThisProfileInList(self, profileIndex, profileList): |
|
859 | def isThisProfileInList(self, profileIndex, profileList): | |
853 |
|
860 | |||
854 | if profileIndex not in profileList: |
|
861 | if profileIndex not in profileList: | |
855 | return False |
|
862 | return False | |
856 |
|
863 | |||
857 | return True |
|
864 | return True | |
858 |
|
865 | |||
859 | def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None): |
|
866 | def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None): | |
860 |
|
867 | |||
861 | """ |
|
868 | """ | |
862 | ProfileSelector: |
|
869 | ProfileSelector: | |
863 |
|
870 | |||
864 | Inputs: |
|
871 | Inputs: | |
865 | profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8) |
|
872 | profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8) | |
866 |
|
873 | |||
867 | profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30) |
|
874 | profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30) | |
868 |
|
875 | |||
869 | rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256)) |
|
876 | rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256)) | |
870 |
|
877 | |||
871 | """ |
|
878 | """ | |
872 |
|
879 | |||
873 | if rangeList is not None: |
|
880 | if rangeList is not None: | |
874 | if type(rangeList[0]) not in (tuple, list): |
|
881 | if type(rangeList[0]) not in (tuple, list): | |
875 | rangeList = [rangeList] |
|
882 | rangeList = [rangeList] | |
876 |
|
883 | |||
877 | dataOut.flagNoData = True |
|
884 | dataOut.flagNoData = True | |
878 |
|
885 | |||
879 | if dataOut.flagDataAsBlock: |
|
886 | if dataOut.flagDataAsBlock: | |
880 | """ |
|
887 | """ | |
881 | data dimension = [nChannels, nProfiles, nHeis] |
|
888 | data dimension = [nChannels, nProfiles, nHeis] | |
882 | """ |
|
889 | """ | |
883 | if profileList != None: |
|
890 | if profileList != None: | |
884 | dataOut.data = dataOut.data[:,profileList,:] |
|
891 | dataOut.data = dataOut.data[:,profileList,:] | |
885 |
|
892 | |||
886 | if profileRangeList != None: |
|
893 | if profileRangeList != None: | |
887 | minIndex = profileRangeList[0] |
|
894 | minIndex = profileRangeList[0] | |
888 | maxIndex = profileRangeList[1] |
|
895 | maxIndex = profileRangeList[1] | |
889 | profileList = list(range(minIndex, maxIndex+1)) |
|
896 | profileList = list(range(minIndex, maxIndex+1)) | |
890 |
|
897 | |||
891 | dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:] |
|
898 | dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:] | |
892 |
|
899 | |||
893 | if rangeList != None: |
|
900 | if rangeList != None: | |
894 |
|
901 | |||
895 | profileList = [] |
|
902 | profileList = [] | |
896 |
|
903 | |||
897 | for thisRange in rangeList: |
|
904 | for thisRange in rangeList: | |
898 | minIndex = thisRange[0] |
|
905 | minIndex = thisRange[0] | |
899 | maxIndex = thisRange[1] |
|
906 | maxIndex = thisRange[1] | |
900 |
|
907 | |||
901 | profileList.extend(list(range(minIndex, maxIndex+1))) |
|
908 | profileList.extend(list(range(minIndex, maxIndex+1))) | |
902 |
|
909 | |||
903 | dataOut.data = dataOut.data[:,profileList,:] |
|
910 | dataOut.data = dataOut.data[:,profileList,:] | |
904 |
|
911 | |||
905 | dataOut.nProfiles = len(profileList) |
|
912 | dataOut.nProfiles = len(profileList) | |
906 | dataOut.profileIndex = dataOut.nProfiles - 1 |
|
913 | dataOut.profileIndex = dataOut.nProfiles - 1 | |
907 | dataOut.flagNoData = False |
|
914 | dataOut.flagNoData = False | |
908 |
|
915 | |||
909 | return True |
|
916 | return True | |
910 |
|
917 | |||
911 | """ |
|
918 | """ | |
912 | data dimension = [nChannels, nHeis] |
|
919 | data dimension = [nChannels, nHeis] | |
913 | """ |
|
920 | """ | |
914 |
|
921 | |||
915 | if profileList != None: |
|
922 | if profileList != None: | |
916 |
|
923 | |||
917 | if self.isThisProfileInList(dataOut.profileIndex, profileList): |
|
924 | if self.isThisProfileInList(dataOut.profileIndex, profileList): | |
918 |
|
925 | |||
919 | self.nProfiles = len(profileList) |
|
926 | self.nProfiles = len(profileList) | |
920 | dataOut.nProfiles = self.nProfiles |
|
927 | dataOut.nProfiles = self.nProfiles | |
921 | dataOut.profileIndex = self.profileIndex |
|
928 | dataOut.profileIndex = self.profileIndex | |
922 | dataOut.flagNoData = False |
|
929 | dataOut.flagNoData = False | |
923 |
|
930 | |||
924 | self.incProfileIndex() |
|
931 | self.incProfileIndex() | |
925 | return True |
|
932 | return True | |
926 |
|
933 | |||
927 | if profileRangeList != None: |
|
934 | if profileRangeList != None: | |
928 |
|
935 | |||
929 | minIndex = profileRangeList[0] |
|
936 | minIndex = profileRangeList[0] | |
930 | maxIndex = profileRangeList[1] |
|
937 | maxIndex = profileRangeList[1] | |
931 |
|
938 | |||
932 | if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex): |
|
939 | if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex): | |
933 |
|
940 | |||
934 | self.nProfiles = maxIndex - minIndex + 1 |
|
941 | self.nProfiles = maxIndex - minIndex + 1 | |
935 | dataOut.nProfiles = self.nProfiles |
|
942 | dataOut.nProfiles = self.nProfiles | |
936 | dataOut.profileIndex = self.profileIndex |
|
943 | dataOut.profileIndex = self.profileIndex | |
937 | dataOut.flagNoData = False |
|
944 | dataOut.flagNoData = False | |
938 |
|
945 | |||
939 | self.incProfileIndex() |
|
946 | self.incProfileIndex() | |
940 | return True |
|
947 | return True | |
941 |
|
948 | |||
942 | if rangeList != None: |
|
949 | if rangeList != None: | |
943 |
|
950 | |||
944 | nProfiles = 0 |
|
951 | nProfiles = 0 | |
945 |
|
952 | |||
946 | for thisRange in rangeList: |
|
953 | for thisRange in rangeList: | |
947 | minIndex = thisRange[0] |
|
954 | minIndex = thisRange[0] | |
948 | maxIndex = thisRange[1] |
|
955 | maxIndex = thisRange[1] | |
949 |
|
956 | |||
950 | nProfiles += maxIndex - minIndex + 1 |
|
957 | nProfiles += maxIndex - minIndex + 1 | |
951 |
|
958 | |||
952 | for thisRange in rangeList: |
|
959 | for thisRange in rangeList: | |
953 |
|
960 | |||
954 | minIndex = thisRange[0] |
|
961 | minIndex = thisRange[0] | |
955 | maxIndex = thisRange[1] |
|
962 | maxIndex = thisRange[1] | |
956 |
|
963 | |||
957 | if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex): |
|
964 | if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex): | |
958 |
|
965 | |||
959 | self.nProfiles = nProfiles |
|
966 | self.nProfiles = nProfiles | |
960 | dataOut.nProfiles = self.nProfiles |
|
967 | dataOut.nProfiles = self.nProfiles | |
961 | dataOut.profileIndex = self.profileIndex |
|
968 | dataOut.profileIndex = self.profileIndex | |
962 | dataOut.flagNoData = False |
|
969 | dataOut.flagNoData = False | |
963 |
|
970 | |||
964 | self.incProfileIndex() |
|
971 | self.incProfileIndex() | |
965 |
|
972 | |||
966 | break |
|
973 | break | |
967 |
|
974 | |||
968 | return True |
|
975 | return True | |
969 |
|
976 | |||
970 |
|
977 | |||
971 | if beam != None: #beam is only for AMISR data |
|
978 | if beam != None: #beam is only for AMISR data | |
972 | if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]): |
|
979 | if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]): | |
973 | dataOut.flagNoData = False |
|
980 | dataOut.flagNoData = False | |
974 | dataOut.profileIndex = self.profileIndex |
|
981 | dataOut.profileIndex = self.profileIndex | |
975 |
|
982 | |||
976 | self.incProfileIndex() |
|
983 | self.incProfileIndex() | |
977 |
|
984 | |||
978 | return True |
|
985 | return True | |
979 |
|
986 | |||
980 | raise ValueError("ProfileSelector needs profileList, profileRangeList or rangeList parameter") |
|
987 | raise ValueError("ProfileSelector needs profileList, profileRangeList or rangeList parameter") | |
981 |
|
988 | |||
982 | return False |
|
989 | #return False | |
983 |
|
990 | return dataOut | ||
|
991 | @MPDecorator | |||
984 | class Reshaper(Operation): |
|
992 | class Reshaper(Operation): | |
985 |
|
993 | |||
986 |
def __init__(self |
|
994 | def __init__(self):#, **kwargs): | |
987 |
|
995 | |||
988 |
Operation.__init__(self |
|
996 | Operation.__init__(self)#, **kwargs) | |
989 |
|
997 | |||
990 | self.__buffer = None |
|
998 | self.__buffer = None | |
991 | self.__nitems = 0 |
|
999 | self.__nitems = 0 | |
992 |
|
1000 | |||
993 | def __appendProfile(self, dataOut, nTxs): |
|
1001 | def __appendProfile(self, dataOut, nTxs): | |
994 |
|
1002 | |||
995 | if self.__buffer is None: |
|
1003 | if self.__buffer is None: | |
996 | shape = (dataOut.nChannels, int(dataOut.nHeights/nTxs) ) |
|
1004 | shape = (dataOut.nChannels, int(dataOut.nHeights/nTxs) ) | |
997 | self.__buffer = numpy.empty(shape, dtype = dataOut.data.dtype) |
|
1005 | self.__buffer = numpy.empty(shape, dtype = dataOut.data.dtype) | |
998 |
|
1006 | |||
999 | ini = dataOut.nHeights * self.__nitems |
|
1007 | ini = dataOut.nHeights * self.__nitems | |
1000 | end = ini + dataOut.nHeights |
|
1008 | end = ini + dataOut.nHeights | |
1001 |
|
1009 | |||
1002 | self.__buffer[:, ini:end] = dataOut.data |
|
1010 | self.__buffer[:, ini:end] = dataOut.data | |
1003 |
|
1011 | |||
1004 | self.__nitems += 1 |
|
1012 | self.__nitems += 1 | |
1005 |
|
1013 | |||
1006 | return int(self.__nitems*nTxs) |
|
1014 | return int(self.__nitems*nTxs) | |
1007 |
|
1015 | |||
1008 | def __getBuffer(self): |
|
1016 | def __getBuffer(self): | |
1009 |
|
1017 | |||
1010 | if self.__nitems == int(1./self.__nTxs): |
|
1018 | if self.__nitems == int(1./self.__nTxs): | |
1011 |
|
1019 | |||
1012 | self.__nitems = 0 |
|
1020 | self.__nitems = 0 | |
1013 |
|
1021 | |||
1014 | return self.__buffer.copy() |
|
1022 | return self.__buffer.copy() | |
1015 |
|
1023 | |||
1016 | return None |
|
1024 | return None | |
1017 |
|
1025 | |||
1018 | def __checkInputs(self, dataOut, shape, nTxs): |
|
1026 | def __checkInputs(self, dataOut, shape, nTxs): | |
1019 |
|
1027 | |||
1020 | if shape is None and nTxs is None: |
|
1028 | if shape is None and nTxs is None: | |
1021 | raise ValueError("Reshaper: shape of factor should be defined") |
|
1029 | raise ValueError("Reshaper: shape of factor should be defined") | |
1022 |
|
1030 | |||
1023 | if nTxs: |
|
1031 | if nTxs: | |
1024 | if nTxs < 0: |
|
1032 | if nTxs < 0: | |
1025 | raise ValueError("nTxs should be greater than 0") |
|
1033 | raise ValueError("nTxs should be greater than 0") | |
1026 |
|
1034 | |||
1027 | if nTxs < 1 and dataOut.nProfiles % (1./nTxs) != 0: |
|
1035 | if nTxs < 1 and dataOut.nProfiles % (1./nTxs) != 0: | |
1028 | raise ValueError("nProfiles= %d is not divisibled by (1./nTxs) = %f" %(dataOut.nProfiles, (1./nTxs))) |
|
1036 | raise ValueError("nProfiles= %d is not divisibled by (1./nTxs) = %f" %(dataOut.nProfiles, (1./nTxs))) | |
1029 |
|
1037 | |||
1030 | shape = [dataOut.nChannels, dataOut.nProfiles*nTxs, dataOut.nHeights/nTxs] |
|
1038 | shape = [dataOut.nChannels, dataOut.nProfiles*nTxs, dataOut.nHeights/nTxs] | |
1031 |
|
1039 | |||
1032 | return shape, nTxs |
|
1040 | return shape, nTxs | |
1033 |
|
1041 | |||
1034 | if len(shape) != 2 and len(shape) != 3: |
|
1042 | if len(shape) != 2 and len(shape) != 3: | |
1035 | raise ValueError("shape dimension should be equal to 2 or 3. shape = (nProfiles, nHeis) or (nChannels, nProfiles, nHeis). Actually shape = (%d, %d, %d)" %(dataOut.nChannels, dataOut.nProfiles, dataOut.nHeights)) |
|
1043 | raise ValueError("shape dimension should be equal to 2 or 3. shape = (nProfiles, nHeis) or (nChannels, nProfiles, nHeis). Actually shape = (%d, %d, %d)" %(dataOut.nChannels, dataOut.nProfiles, dataOut.nHeights)) | |
1036 |
|
1044 | |||
1037 | if len(shape) == 2: |
|
1045 | if len(shape) == 2: | |
1038 | shape_tuple = [dataOut.nChannels] |
|
1046 | shape_tuple = [dataOut.nChannels] | |
1039 | shape_tuple.extend(shape) |
|
1047 | shape_tuple.extend(shape) | |
1040 | else: |
|
1048 | else: | |
1041 | shape_tuple = list(shape) |
|
1049 | shape_tuple = list(shape) | |
1042 |
|
1050 | |||
1043 | nTxs = 1.0*shape_tuple[1]/dataOut.nProfiles |
|
1051 | nTxs = 1.0*shape_tuple[1]/dataOut.nProfiles | |
1044 |
|
1052 | |||
1045 | return shape_tuple, nTxs |
|
1053 | return shape_tuple, nTxs | |
1046 |
|
1054 | |||
1047 | def run(self, dataOut, shape=None, nTxs=None): |
|
1055 | def run(self, dataOut, shape=None, nTxs=None): | |
1048 |
|
1056 | |||
1049 | shape_tuple, self.__nTxs = self.__checkInputs(dataOut, shape, nTxs) |
|
1057 | shape_tuple, self.__nTxs = self.__checkInputs(dataOut, shape, nTxs) | |
1050 |
|
1058 | |||
1051 | dataOut.flagNoData = True |
|
1059 | dataOut.flagNoData = True | |
1052 | profileIndex = None |
|
1060 | profileIndex = None | |
1053 |
|
1061 | |||
1054 | if dataOut.flagDataAsBlock: |
|
1062 | if dataOut.flagDataAsBlock: | |
1055 |
|
1063 | |||
1056 | dataOut.data = numpy.reshape(dataOut.data, shape_tuple) |
|
1064 | dataOut.data = numpy.reshape(dataOut.data, shape_tuple) | |
1057 | dataOut.flagNoData = False |
|
1065 | dataOut.flagNoData = False | |
1058 |
|
1066 | |||
1059 | profileIndex = int(dataOut.nProfiles*self.__nTxs) - 1 |
|
1067 | profileIndex = int(dataOut.nProfiles*self.__nTxs) - 1 | |
1060 |
|
1068 | |||
1061 | else: |
|
1069 | else: | |
1062 |
|
1070 | |||
1063 | if self.__nTxs < 1: |
|
1071 | if self.__nTxs < 1: | |
1064 |
|
1072 | |||
1065 | self.__appendProfile(dataOut, self.__nTxs) |
|
1073 | self.__appendProfile(dataOut, self.__nTxs) | |
1066 | new_data = self.__getBuffer() |
|
1074 | new_data = self.__getBuffer() | |
1067 |
|
1075 | |||
1068 | if new_data is not None: |
|
1076 | if new_data is not None: | |
1069 | dataOut.data = new_data |
|
1077 | dataOut.data = new_data | |
1070 | dataOut.flagNoData = False |
|
1078 | dataOut.flagNoData = False | |
1071 |
|
1079 | |||
1072 | profileIndex = dataOut.profileIndex*nTxs |
|
1080 | profileIndex = dataOut.profileIndex*nTxs | |
1073 |
|
1081 | |||
1074 | else: |
|
1082 | else: | |
1075 | raise ValueError("nTxs should be greater than 0 and lower than 1, or use VoltageReader(..., getblock=True)") |
|
1083 | raise ValueError("nTxs should be greater than 0 and lower than 1, or use VoltageReader(..., getblock=True)") | |
1076 |
|
1084 | |||
1077 | deltaHeight = dataOut.heightList[1] - dataOut.heightList[0] |
|
1085 | deltaHeight = dataOut.heightList[1] - dataOut.heightList[0] | |
1078 |
|
1086 | |||
1079 | dataOut.heightList = numpy.arange(dataOut.nHeights/self.__nTxs) * deltaHeight + dataOut.heightList[0] |
|
1087 | dataOut.heightList = numpy.arange(dataOut.nHeights/self.__nTxs) * deltaHeight + dataOut.heightList[0] | |
1080 |
|
1088 | |||
1081 | dataOut.nProfiles = int(dataOut.nProfiles*self.__nTxs) |
|
1089 | dataOut.nProfiles = int(dataOut.nProfiles*self.__nTxs) | |
1082 |
|
1090 | |||
1083 | dataOut.profileIndex = profileIndex |
|
1091 | dataOut.profileIndex = profileIndex | |
1084 |
|
1092 | |||
1085 | dataOut.ippSeconds /= self.__nTxs |
|
1093 | dataOut.ippSeconds /= self.__nTxs | |
1086 |
|
1094 | |||
|
1095 | return dataOut | |||
|
1096 | @MPDecorator | |||
1087 | class SplitProfiles(Operation): |
|
1097 | class SplitProfiles(Operation): | |
1088 |
|
1098 | |||
1089 |
def __init__(self |
|
1099 | def __init__(self):#, **kwargs): | |
1090 |
|
1100 | |||
1091 |
Operation.__init__(self |
|
1101 | Operation.__init__(self)#, **kwargs) | |
1092 |
|
1102 | |||
1093 | def run(self, dataOut, n): |
|
1103 | def run(self, dataOut, n): | |
1094 |
|
1104 | |||
1095 | dataOut.flagNoData = True |
|
1105 | dataOut.flagNoData = True | |
1096 | profileIndex = None |
|
1106 | profileIndex = None | |
1097 |
|
1107 | |||
1098 | if dataOut.flagDataAsBlock: |
|
1108 | if dataOut.flagDataAsBlock: | |
1099 |
|
1109 | |||
1100 | #nchannels, nprofiles, nsamples |
|
1110 | #nchannels, nprofiles, nsamples | |
1101 | shape = dataOut.data.shape |
|
1111 | shape = dataOut.data.shape | |
1102 |
|
1112 | |||
1103 | if shape[2] % n != 0: |
|
1113 | if shape[2] % n != 0: | |
1104 | raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[2])) |
|
1114 | raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[2])) | |
1105 |
|
1115 | |||
1106 | new_shape = shape[0], shape[1]*n, int(shape[2]/n) |
|
1116 | new_shape = shape[0], shape[1]*n, int(shape[2]/n) | |
|
1117 | ||||
1107 | dataOut.data = numpy.reshape(dataOut.data, new_shape) |
|
1118 | dataOut.data = numpy.reshape(dataOut.data, new_shape) | |
1108 | dataOut.flagNoData = False |
|
1119 | dataOut.flagNoData = False | |
1109 |
|
1120 | |||
1110 | profileIndex = int(dataOut.nProfiles/n) - 1 |
|
1121 | profileIndex = int(dataOut.nProfiles/n) - 1 | |
1111 |
|
1122 | |||
1112 | else: |
|
1123 | else: | |
1113 |
|
1124 | |||
1114 | raise ValueError("Could not split the data when is read Profile by Profile. Use VoltageReader(..., getblock=True)") |
|
1125 | raise ValueError("Could not split the data when is read Profile by Profile. Use VoltageReader(..., getblock=True)") | |
1115 |
|
1126 | |||
1116 | deltaHeight = dataOut.heightList[1] - dataOut.heightList[0] |
|
1127 | deltaHeight = dataOut.heightList[1] - dataOut.heightList[0] | |
1117 |
|
1128 | |||
1118 | dataOut.heightList = numpy.arange(dataOut.nHeights/n) * deltaHeight + dataOut.heightList[0] |
|
1129 | dataOut.heightList = numpy.arange(dataOut.nHeights/n) * deltaHeight + dataOut.heightList[0] | |
1119 |
|
1130 | |||
1120 | dataOut.nProfiles = int(dataOut.nProfiles*n) |
|
1131 | dataOut.nProfiles = int(dataOut.nProfiles*n) | |
1121 |
|
1132 | |||
1122 | dataOut.profileIndex = profileIndex |
|
1133 | dataOut.profileIndex = profileIndex | |
1123 |
|
1134 | |||
1124 | dataOut.ippSeconds /= n |
|
1135 | dataOut.ippSeconds /= n | |
1125 |
|
1136 | |||
|
1137 | return dataOut | |||
|
1138 | @MPDecorator | |||
1126 | class CombineProfiles(Operation): |
|
1139 | class CombineProfiles(Operation): | |
1127 |
def __init__(self |
|
1140 | def __init__(self):#, **kwargs): | |
1128 |
|
1141 | |||
1129 |
Operation.__init__(self |
|
1142 | Operation.__init__(self)#, **kwargs) | |
1130 |
|
1143 | |||
1131 | self.__remData = None |
|
1144 | self.__remData = None | |
1132 | self.__profileIndex = 0 |
|
1145 | self.__profileIndex = 0 | |
1133 |
|
1146 | |||
1134 | def run(self, dataOut, n): |
|
1147 | def run(self, dataOut, n): | |
1135 |
|
1148 | |||
1136 | dataOut.flagNoData = True |
|
1149 | dataOut.flagNoData = True | |
1137 | profileIndex = None |
|
1150 | profileIndex = None | |
1138 |
|
1151 | |||
1139 | if dataOut.flagDataAsBlock: |
|
1152 | if dataOut.flagDataAsBlock: | |
1140 |
|
1153 | |||
1141 | #nchannels, nprofiles, nsamples |
|
1154 | #nchannels, nprofiles, nsamples | |
1142 | shape = dataOut.data.shape |
|
1155 | shape = dataOut.data.shape | |
1143 | new_shape = shape[0], shape[1]/n, shape[2]*n |
|
1156 | new_shape = shape[0], shape[1]/n, shape[2]*n | |
1144 |
|
1157 | |||
1145 | if shape[1] % n != 0: |
|
1158 | if shape[1] % n != 0: | |
1146 | raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[1])) |
|
1159 | raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[1])) | |
1147 |
|
1160 | |||
1148 | dataOut.data = numpy.reshape(dataOut.data, new_shape) |
|
1161 | dataOut.data = numpy.reshape(dataOut.data, new_shape) | |
1149 | dataOut.flagNoData = False |
|
1162 | dataOut.flagNoData = False | |
1150 |
|
1163 | |||
1151 | profileIndex = int(dataOut.nProfiles*n) - 1 |
|
1164 | profileIndex = int(dataOut.nProfiles*n) - 1 | |
1152 |
|
1165 | |||
1153 | else: |
|
1166 | else: | |
1154 |
|
1167 | |||
1155 | #nchannels, nsamples |
|
1168 | #nchannels, nsamples | |
1156 | if self.__remData is None: |
|
1169 | if self.__remData is None: | |
1157 | newData = dataOut.data |
|
1170 | newData = dataOut.data | |
1158 | else: |
|
1171 | else: | |
1159 | newData = numpy.concatenate((self.__remData, dataOut.data), axis=1) |
|
1172 | newData = numpy.concatenate((self.__remData, dataOut.data), axis=1) | |
1160 |
|
1173 | |||
1161 | self.__profileIndex += 1 |
|
1174 | self.__profileIndex += 1 | |
1162 |
|
1175 | |||
1163 | if self.__profileIndex < n: |
|
1176 | if self.__profileIndex < n: | |
1164 | self.__remData = newData |
|
1177 | self.__remData = newData | |
1165 | #continue |
|
1178 | #continue | |
1166 | return |
|
1179 | return | |
1167 |
|
1180 | |||
1168 | self.__profileIndex = 0 |
|
1181 | self.__profileIndex = 0 | |
1169 | self.__remData = None |
|
1182 | self.__remData = None | |
1170 |
|
1183 | |||
1171 | dataOut.data = newData |
|
1184 | dataOut.data = newData | |
1172 | dataOut.flagNoData = False |
|
1185 | dataOut.flagNoData = False | |
1173 |
|
1186 | |||
1174 | profileIndex = dataOut.profileIndex/n |
|
1187 | profileIndex = dataOut.profileIndex/n | |
1175 |
|
1188 | |||
1176 |
|
1189 | |||
1177 | deltaHeight = dataOut.heightList[1] - dataOut.heightList[0] |
|
1190 | deltaHeight = dataOut.heightList[1] - dataOut.heightList[0] | |
1178 |
|
1191 | |||
1179 | dataOut.heightList = numpy.arange(dataOut.nHeights*n) * deltaHeight + dataOut.heightList[0] |
|
1192 | dataOut.heightList = numpy.arange(dataOut.nHeights*n) * deltaHeight + dataOut.heightList[0] | |
1180 |
|
1193 | |||
1181 | dataOut.nProfiles = int(dataOut.nProfiles/n) |
|
1194 | dataOut.nProfiles = int(dataOut.nProfiles/n) | |
1182 |
|
1195 | |||
1183 | dataOut.profileIndex = profileIndex |
|
1196 | dataOut.profileIndex = profileIndex | |
1184 |
|
1197 | |||
1185 | dataOut.ippSeconds *= n |
|
1198 | dataOut.ippSeconds *= n | |
1186 |
|
1199 | |||
|
1200 | return dataOut | |||
1187 | # import collections |
|
1201 | # import collections | |
1188 | # from scipy.stats import mode |
|
1202 | # from scipy.stats import mode | |
1189 | # |
|
1203 | # | |
1190 | # class Synchronize(Operation): |
|
1204 | # class Synchronize(Operation): | |
1191 | # |
|
1205 | # | |
1192 | # isConfig = False |
|
1206 | # isConfig = False | |
1193 | # __profIndex = 0 |
|
1207 | # __profIndex = 0 | |
1194 | # |
|
1208 | # | |
1195 | # def __init__(self, **kwargs): |
|
1209 | # def __init__(self, **kwargs): | |
1196 | # |
|
1210 | # | |
1197 | # Operation.__init__(self, **kwargs) |
|
1211 | # Operation.__init__(self, **kwargs) | |
1198 | # # self.isConfig = False |
|
1212 | # # self.isConfig = False | |
1199 | # self.__powBuffer = None |
|
1213 | # self.__powBuffer = None | |
1200 | # self.__startIndex = 0 |
|
1214 | # self.__startIndex = 0 | |
1201 | # self.__pulseFound = False |
|
1215 | # self.__pulseFound = False | |
1202 | # |
|
1216 | # | |
1203 | # def __findTxPulse(self, dataOut, channel=0, pulse_with = None): |
|
1217 | # def __findTxPulse(self, dataOut, channel=0, pulse_with = None): | |
1204 | # |
|
1218 | # | |
1205 | # #Read data |
|
1219 | # #Read data | |
1206 | # |
|
1220 | # | |
1207 | # powerdB = dataOut.getPower(channel = channel) |
|
1221 | # powerdB = dataOut.getPower(channel = channel) | |
1208 | # noisedB = dataOut.getNoise(channel = channel)[0] |
|
1222 | # noisedB = dataOut.getNoise(channel = channel)[0] | |
1209 | # |
|
1223 | # | |
1210 | # self.__powBuffer.extend(powerdB.flatten()) |
|
1224 | # self.__powBuffer.extend(powerdB.flatten()) | |
1211 | # |
|
1225 | # | |
1212 | # dataArray = numpy.array(self.__powBuffer) |
|
1226 | # dataArray = numpy.array(self.__powBuffer) | |
1213 | # |
|
1227 | # | |
1214 | # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same") |
|
1228 | # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same") | |
1215 | # |
|
1229 | # | |
1216 | # maxValue = numpy.nanmax(filteredPower) |
|
1230 | # maxValue = numpy.nanmax(filteredPower) | |
1217 | # |
|
1231 | # | |
1218 | # if maxValue < noisedB + 10: |
|
1232 | # if maxValue < noisedB + 10: | |
1219 | # #No se encuentra ningun pulso de transmision |
|
1233 | # #No se encuentra ningun pulso de transmision | |
1220 | # return None |
|
1234 | # return None | |
1221 | # |
|
1235 | # | |
1222 | # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0] |
|
1236 | # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0] | |
1223 | # |
|
1237 | # | |
1224 | # if len(maxValuesIndex) < 2: |
|
1238 | # if len(maxValuesIndex) < 2: | |
1225 | # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX |
|
1239 | # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX | |
1226 | # return None |
|
1240 | # return None | |
1227 | # |
|
1241 | # | |
1228 | # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples |
|
1242 | # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples | |
1229 | # |
|
1243 | # | |
1230 | # #Seleccionar solo valores con un espaciamiento de nSamples |
|
1244 | # #Seleccionar solo valores con un espaciamiento de nSamples | |
1231 | # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex) |
|
1245 | # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex) | |
1232 | # |
|
1246 | # | |
1233 | # if len(pulseIndex) < 2: |
|
1247 | # if len(pulseIndex) < 2: | |
1234 | # #Solo se encontro un pulso de transmision con ancho mayor a 1 |
|
1248 | # #Solo se encontro un pulso de transmision con ancho mayor a 1 | |
1235 | # return None |
|
1249 | # return None | |
1236 | # |
|
1250 | # | |
1237 | # spacing = pulseIndex[1:] - pulseIndex[:-1] |
|
1251 | # spacing = pulseIndex[1:] - pulseIndex[:-1] | |
1238 | # |
|
1252 | # | |
1239 | # #remover senales que se distancien menos de 10 unidades o muestras |
|
1253 | # #remover senales que se distancien menos de 10 unidades o muestras | |
1240 | # #(No deberian existir IPP menor a 10 unidades) |
|
1254 | # #(No deberian existir IPP menor a 10 unidades) | |
1241 | # |
|
1255 | # | |
1242 | # realIndex = numpy.where(spacing > 10 )[0] |
|
1256 | # realIndex = numpy.where(spacing > 10 )[0] | |
1243 | # |
|
1257 | # | |
1244 | # if len(realIndex) < 2: |
|
1258 | # if len(realIndex) < 2: | |
1245 | # #Solo se encontro un pulso de transmision con ancho mayor a 1 |
|
1259 | # #Solo se encontro un pulso de transmision con ancho mayor a 1 | |
1246 | # return None |
|
1260 | # return None | |
1247 | # |
|
1261 | # | |
1248 | # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs) |
|
1262 | # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs) | |
1249 | # realPulseIndex = pulseIndex[realIndex] |
|
1263 | # realPulseIndex = pulseIndex[realIndex] | |
1250 | # |
|
1264 | # | |
1251 | # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0] |
|
1265 | # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0] | |
1252 | # |
|
1266 | # | |
1253 | # print "IPP = %d samples" %period |
|
1267 | # print "IPP = %d samples" %period | |
1254 | # |
|
1268 | # | |
1255 | # self.__newNSamples = dataOut.nHeights #int(period) |
|
1269 | # self.__newNSamples = dataOut.nHeights #int(period) | |
1256 | # self.__startIndex = int(realPulseIndex[0]) |
|
1270 | # self.__startIndex = int(realPulseIndex[0]) | |
1257 | # |
|
1271 | # | |
1258 | # return 1 |
|
1272 | # return 1 | |
1259 | # |
|
1273 | # | |
1260 | # |
|
1274 | # | |
1261 | # def setup(self, nSamples, nChannels, buffer_size = 4): |
|
1275 | # def setup(self, nSamples, nChannels, buffer_size = 4): | |
1262 | # |
|
1276 | # | |
1263 | # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float), |
|
1277 | # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float), | |
1264 | # maxlen = buffer_size*nSamples) |
|
1278 | # maxlen = buffer_size*nSamples) | |
1265 | # |
|
1279 | # | |
1266 | # bufferList = [] |
|
1280 | # bufferList = [] | |
1267 | # |
|
1281 | # | |
1268 | # for i in range(nChannels): |
|
1282 | # for i in range(nChannels): | |
1269 | # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=numpy.complex) + numpy.NAN, |
|
1283 | # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=numpy.complex) + numpy.NAN, | |
1270 | # maxlen = buffer_size*nSamples) |
|
1284 | # maxlen = buffer_size*nSamples) | |
1271 | # |
|
1285 | # | |
1272 | # bufferList.append(bufferByChannel) |
|
1286 | # bufferList.append(bufferByChannel) | |
1273 | # |
|
1287 | # | |
1274 | # self.__nSamples = nSamples |
|
1288 | # self.__nSamples = nSamples | |
1275 | # self.__nChannels = nChannels |
|
1289 | # self.__nChannels = nChannels | |
1276 | # self.__bufferList = bufferList |
|
1290 | # self.__bufferList = bufferList | |
1277 | # |
|
1291 | # | |
1278 | # def run(self, dataOut, channel = 0): |
|
1292 | # def run(self, dataOut, channel = 0): | |
1279 | # |
|
1293 | # | |
1280 | # if not self.isConfig: |
|
1294 | # if not self.isConfig: | |
1281 | # nSamples = dataOut.nHeights |
|
1295 | # nSamples = dataOut.nHeights | |
1282 | # nChannels = dataOut.nChannels |
|
1296 | # nChannels = dataOut.nChannels | |
1283 | # self.setup(nSamples, nChannels) |
|
1297 | # self.setup(nSamples, nChannels) | |
1284 | # self.isConfig = True |
|
1298 | # self.isConfig = True | |
1285 | # |
|
1299 | # | |
1286 | # #Append new data to internal buffer |
|
1300 | # #Append new data to internal buffer | |
1287 | # for thisChannel in range(self.__nChannels): |
|
1301 | # for thisChannel in range(self.__nChannels): | |
1288 | # bufferByChannel = self.__bufferList[thisChannel] |
|
1302 | # bufferByChannel = self.__bufferList[thisChannel] | |
1289 | # bufferByChannel.extend(dataOut.data[thisChannel]) |
|
1303 | # bufferByChannel.extend(dataOut.data[thisChannel]) | |
1290 | # |
|
1304 | # | |
1291 | # if self.__pulseFound: |
|
1305 | # if self.__pulseFound: | |
1292 | # self.__startIndex -= self.__nSamples |
|
1306 | # self.__startIndex -= self.__nSamples | |
1293 | # |
|
1307 | # | |
1294 | # #Finding Tx Pulse |
|
1308 | # #Finding Tx Pulse | |
1295 | # if not self.__pulseFound: |
|
1309 | # if not self.__pulseFound: | |
1296 | # indexFound = self.__findTxPulse(dataOut, channel) |
|
1310 | # indexFound = self.__findTxPulse(dataOut, channel) | |
1297 | # |
|
1311 | # | |
1298 | # if indexFound == None: |
|
1312 | # if indexFound == None: | |
1299 | # dataOut.flagNoData = True |
|
1313 | # dataOut.flagNoData = True | |
1300 | # return |
|
1314 | # return | |
1301 | # |
|
1315 | # | |
1302 | # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = numpy.complex) |
|
1316 | # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = numpy.complex) | |
1303 | # self.__pulseFound = True |
|
1317 | # self.__pulseFound = True | |
1304 | # self.__startIndex = indexFound |
|
1318 | # self.__startIndex = indexFound | |
1305 | # |
|
1319 | # | |
1306 | # #If pulse was found ... |
|
1320 | # #If pulse was found ... | |
1307 | # for thisChannel in range(self.__nChannels): |
|
1321 | # for thisChannel in range(self.__nChannels): | |
1308 | # bufferByChannel = self.__bufferList[thisChannel] |
|
1322 | # bufferByChannel = self.__bufferList[thisChannel] | |
1309 | # #print self.__startIndex |
|
1323 | # #print self.__startIndex | |
1310 | # x = numpy.array(bufferByChannel) |
|
1324 | # x = numpy.array(bufferByChannel) | |
1311 | # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples] |
|
1325 | # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples] | |
1312 | # |
|
1326 | # | |
1313 | # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0] |
|
1327 | # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0] | |
1314 | # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight |
|
1328 | # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight | |
1315 | # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6 |
|
1329 | # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6 | |
1316 | # |
|
1330 | # | |
1317 | # dataOut.data = self.__arrayBuffer |
|
1331 | # dataOut.data = self.__arrayBuffer | |
1318 | # |
|
1332 | # | |
1319 | # self.__startIndex += self.__newNSamples |
|
1333 | # self.__startIndex += self.__newNSamples | |
1320 | # |
|
1334 | # | |
1321 | # return No newline at end of file |
|
1335 | # return |
General Comments 0
You need to be logged in to leave comments.
Login now