@@ -1,1828 +1,1828 | |||||
1 | ''' |
|
1 | ''' | |
2 | Created on Jul 2, 2014 |
|
2 | Created on Jul 2, 2014 | |
3 |
|
3 | |||
4 | @author: roj-idl71 |
|
4 | @author: roj-idl71 | |
5 | ''' |
|
5 | ''' | |
6 | import os |
|
6 | import os | |
7 | import sys |
|
7 | import sys | |
8 | import glob |
|
8 | import glob | |
9 | import time |
|
9 | import time | |
10 | import numpy |
|
10 | import numpy | |
11 | import fnmatch |
|
11 | import fnmatch | |
12 | import inspect |
|
12 | import inspect | |
13 | import time |
|
13 | import time | |
14 | import datetime |
|
14 | import datetime | |
15 | import traceback |
|
15 | import traceback | |
16 | import zmq |
|
16 | import zmq | |
17 |
|
17 | |||
18 | try: |
|
18 | try: | |
19 | from gevent import sleep |
|
19 | from gevent import sleep | |
20 | except: |
|
20 | except: | |
21 | from time import sleep |
|
21 | from time import sleep | |
22 |
|
22 | |||
23 | from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader |
|
23 | from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader | |
24 | from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width |
|
24 | from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width | |
25 | from schainpy.utils import log |
|
25 | from schainpy.utils import log | |
26 | import schainpy.admin |
|
26 | import schainpy.admin | |
27 |
|
27 | |||
28 | LOCALTIME = True |
|
28 | LOCALTIME = True | |
29 |
|
29 | |||
30 |
|
30 | |||
31 | def isNumber(cad): |
|
31 | def isNumber(cad): | |
32 | """ |
|
32 | """ | |
33 | Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero. |
|
33 | Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero. | |
34 |
|
34 | |||
35 | Excepciones: |
|
35 | Excepciones: | |
36 | Si un determinado string no puede ser convertido a numero |
|
36 | Si un determinado string no puede ser convertido a numero | |
37 | Input: |
|
37 | Input: | |
38 | str, string al cual se le analiza para determinar si convertible a un numero o no |
|
38 | str, string al cual se le analiza para determinar si convertible a un numero o no | |
39 |
|
39 | |||
40 | Return: |
|
40 | Return: | |
41 | True : si el string es uno numerico |
|
41 | True : si el string es uno numerico | |
42 | False : no es un string numerico |
|
42 | False : no es un string numerico | |
43 | """ |
|
43 | """ | |
44 | try: |
|
44 | try: | |
45 | float(cad) |
|
45 | float(cad) | |
46 | return True |
|
46 | return True | |
47 | except: |
|
47 | except: | |
48 | return False |
|
48 | return False | |
49 |
|
49 | |||
50 |
|
50 | |||
51 | def isFileInEpoch(filename, startUTSeconds, endUTSeconds): |
|
51 | def isFileInEpoch(filename, startUTSeconds, endUTSeconds): | |
52 | """ |
|
52 | """ | |
53 | Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado. |
|
53 | Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado. | |
54 |
|
54 | |||
55 | Inputs: |
|
55 | Inputs: | |
56 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) |
|
56 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) | |
57 |
|
57 | |||
58 | startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en |
|
58 | startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en | |
59 | segundos contados desde 01/01/1970. |
|
59 | segundos contados desde 01/01/1970. | |
60 | endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en |
|
60 | endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en | |
61 | segundos contados desde 01/01/1970. |
|
61 | segundos contados desde 01/01/1970. | |
62 |
|
62 | |||
63 | Return: |
|
63 | Return: | |
64 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de |
|
64 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de | |
65 | fecha especificado, de lo contrario retorna False. |
|
65 | fecha especificado, de lo contrario retorna False. | |
66 |
|
66 | |||
67 | Excepciones: |
|
67 | Excepciones: | |
68 | Si el archivo no existe o no puede ser abierto |
|
68 | Si el archivo no existe o no puede ser abierto | |
69 | Si la cabecera no puede ser leida. |
|
69 | Si la cabecera no puede ser leida. | |
70 |
|
70 | |||
71 | """ |
|
71 | """ | |
72 | basicHeaderObj = BasicHeader(LOCALTIME) |
|
72 | basicHeaderObj = BasicHeader(LOCALTIME) | |
73 |
|
73 | |||
74 | try: |
|
74 | try: | |
75 | fp = open(filename, 'rb') |
|
75 | fp = open(filename, 'rb') | |
76 | except IOError: |
|
76 | except IOError: | |
77 | print("The file %s can't be opened" % (filename)) |
|
77 | print("The file %s can't be opened" % (filename)) | |
78 | return 0 |
|
78 | return 0 | |
79 |
|
79 | |||
80 | sts = basicHeaderObj.read(fp) |
|
80 | sts = basicHeaderObj.read(fp) | |
81 | fp.close() |
|
81 | fp.close() | |
82 |
|
82 | |||
83 | if not(sts): |
|
83 | if not(sts): | |
84 | print("Skipping the file %s because it has not a valid header" % (filename)) |
|
84 | print("Skipping the file %s because it has not a valid header" % (filename)) | |
85 | return 0 |
|
85 | return 0 | |
86 |
|
86 | |||
87 | if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)): |
|
87 | if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)): | |
88 | return 0 |
|
88 | return 0 | |
89 |
|
89 | |||
90 | return 1 |
|
90 | return 1 | |
91 |
|
91 | |||
92 |
|
92 | |||
93 | def isTimeInRange(thisTime, startTime, endTime): |
|
93 | def isTimeInRange(thisTime, startTime, endTime): | |
94 | if endTime >= startTime: |
|
94 | if endTime >= startTime: | |
95 | if (thisTime < startTime) or (thisTime > endTime): |
|
95 | if (thisTime < startTime) or (thisTime > endTime): | |
96 | return 0 |
|
96 | return 0 | |
97 | return 1 |
|
97 | return 1 | |
98 | else: |
|
98 | else: | |
99 | if (thisTime < startTime) and (thisTime > endTime): |
|
99 | if (thisTime < startTime) and (thisTime > endTime): | |
100 | return 0 |
|
100 | return 0 | |
101 | return 1 |
|
101 | return 1 | |
102 |
|
102 | |||
103 |
|
103 | |||
104 | def isFileInTimeRange(filename, startDate, endDate, startTime, endTime): |
|
104 | def isFileInTimeRange(filename, startDate, endDate, startTime, endTime): | |
105 | """ |
|
105 | """ | |
106 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. |
|
106 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. | |
107 |
|
107 | |||
108 | Inputs: |
|
108 | Inputs: | |
109 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) |
|
109 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) | |
110 |
|
110 | |||
111 | startDate : fecha inicial del rango seleccionado en formato datetime.date |
|
111 | startDate : fecha inicial del rango seleccionado en formato datetime.date | |
112 |
|
112 | |||
113 | endDate : fecha final del rango seleccionado en formato datetime.date |
|
113 | endDate : fecha final del rango seleccionado en formato datetime.date | |
114 |
|
114 | |||
115 | startTime : tiempo inicial del rango seleccionado en formato datetime.time |
|
115 | startTime : tiempo inicial del rango seleccionado en formato datetime.time | |
116 |
|
116 | |||
117 | endTime : tiempo final del rango seleccionado en formato datetime.time |
|
117 | endTime : tiempo final del rango seleccionado en formato datetime.time | |
118 |
|
118 | |||
119 | Return: |
|
119 | Return: | |
120 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de |
|
120 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de | |
121 | fecha especificado, de lo contrario retorna False. |
|
121 | fecha especificado, de lo contrario retorna False. | |
122 |
|
122 | |||
123 | Excepciones: |
|
123 | Excepciones: | |
124 | Si el archivo no existe o no puede ser abierto |
|
124 | Si el archivo no existe o no puede ser abierto | |
125 | Si la cabecera no puede ser leida. |
|
125 | Si la cabecera no puede ser leida. | |
126 |
|
126 | |||
127 | """ |
|
127 | """ | |
128 |
|
128 | |||
129 | try: |
|
129 | try: | |
130 | fp = open(filename, 'rb') |
|
130 | fp = open(filename, 'rb') | |
131 | except IOError: |
|
131 | except IOError: | |
132 | print("The file %s can't be opened" % (filename)) |
|
132 | print("The file %s can't be opened" % (filename)) | |
133 | return None |
|
133 | return None | |
134 |
|
134 | |||
135 | firstBasicHeaderObj = BasicHeader(LOCALTIME) |
|
135 | firstBasicHeaderObj = BasicHeader(LOCALTIME) | |
136 | systemHeaderObj = SystemHeader() |
|
136 | systemHeaderObj = SystemHeader() | |
137 | radarControllerHeaderObj = RadarControllerHeader() |
|
137 | radarControllerHeaderObj = RadarControllerHeader() | |
138 | processingHeaderObj = ProcessingHeader() |
|
138 | processingHeaderObj = ProcessingHeader() | |
139 |
|
139 | |||
140 | lastBasicHeaderObj = BasicHeader(LOCALTIME) |
|
140 | lastBasicHeaderObj = BasicHeader(LOCALTIME) | |
141 |
|
141 | |||
142 | sts = firstBasicHeaderObj.read(fp) |
|
142 | sts = firstBasicHeaderObj.read(fp) | |
143 |
|
143 | |||
144 | if not(sts): |
|
144 | if not(sts): | |
145 | print("[Reading] Skipping the file %s because it has not a valid header" % (filename)) |
|
145 | print("[Reading] Skipping the file %s because it has not a valid header" % (filename)) | |
146 | return None |
|
146 | return None | |
147 |
|
147 | |||
148 | if not systemHeaderObj.read(fp): |
|
148 | if not systemHeaderObj.read(fp): | |
149 | return None |
|
149 | return None | |
150 |
|
150 | |||
151 | if not radarControllerHeaderObj.read(fp): |
|
151 | if not radarControllerHeaderObj.read(fp): | |
152 | return None |
|
152 | return None | |
153 |
|
153 | |||
154 | if not processingHeaderObj.read(fp): |
|
154 | if not processingHeaderObj.read(fp): | |
155 | return None |
|
155 | return None | |
156 |
|
156 | |||
157 | filesize = os.path.getsize(filename) |
|
157 | filesize = os.path.getsize(filename) | |
158 |
|
158 | |||
159 | offset = processingHeaderObj.blockSize + 24 # header size |
|
159 | offset = processingHeaderObj.blockSize + 24 # header size | |
160 |
|
160 | |||
161 | if filesize <= offset: |
|
161 | if filesize <= offset: | |
162 | print("[Reading] %s: This file has not enough data" % filename) |
|
162 | print("[Reading] %s: This file has not enough data" % filename) | |
163 | return None |
|
163 | return None | |
164 |
|
164 | |||
165 | fp.seek(-offset, 2) |
|
165 | fp.seek(-offset, 2) | |
166 |
|
166 | |||
167 | sts = lastBasicHeaderObj.read(fp) |
|
167 | sts = lastBasicHeaderObj.read(fp) | |
168 |
|
168 | |||
169 | fp.close() |
|
169 | fp.close() | |
170 |
|
170 | |||
171 | thisDatetime = lastBasicHeaderObj.datatime |
|
171 | thisDatetime = lastBasicHeaderObj.datatime | |
172 | thisTime_last_block = thisDatetime.time() |
|
172 | thisTime_last_block = thisDatetime.time() | |
173 |
|
173 | |||
174 | thisDatetime = firstBasicHeaderObj.datatime |
|
174 | thisDatetime = firstBasicHeaderObj.datatime | |
175 | thisDate = thisDatetime.date() |
|
175 | thisDate = thisDatetime.date() | |
176 | thisTime_first_block = thisDatetime.time() |
|
176 | thisTime_first_block = thisDatetime.time() | |
177 |
|
177 | |||
178 | # General case |
|
178 | # General case | |
179 | # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o |
|
179 | # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o | |
180 | #-----------o----------------------------o----------- |
|
180 | #-----------o----------------------------o----------- | |
181 | # startTime endTime |
|
181 | # startTime endTime | |
182 |
|
182 | |||
183 | if endTime >= startTime: |
|
183 | if endTime >= startTime: | |
184 | if (thisTime_last_block < startTime) or (thisTime_first_block > endTime): |
|
184 | if (thisTime_last_block < startTime) or (thisTime_first_block > endTime): | |
185 | return None |
|
185 | return None | |
186 |
|
186 | |||
187 | return thisDatetime |
|
187 | return thisDatetime | |
188 |
|
188 | |||
189 | # If endTime < startTime then endTime belongs to the next day |
|
189 | # If endTime < startTime then endTime belongs to the next day | |
190 |
|
190 | |||
191 | #<<<<<<<<<<<o o>>>>>>>>>>> |
|
191 | #<<<<<<<<<<<o o>>>>>>>>>>> | |
192 | #-----------o----------------------------o----------- |
|
192 | #-----------o----------------------------o----------- | |
193 | # endTime startTime |
|
193 | # endTime startTime | |
194 |
|
194 | |||
195 | if (thisDate == startDate) and (thisTime_last_block < startTime): |
|
195 | if (thisDate == startDate) and (thisTime_last_block < startTime): | |
196 | return None |
|
196 | return None | |
197 |
|
197 | |||
198 | if (thisDate == endDate) and (thisTime_first_block > endTime): |
|
198 | if (thisDate == endDate) and (thisTime_first_block > endTime): | |
199 | return None |
|
199 | return None | |
200 |
|
200 | |||
201 | if (thisTime_last_block < startTime) and (thisTime_first_block > endTime): |
|
201 | if (thisTime_last_block < startTime) and (thisTime_first_block > endTime): | |
202 | return None |
|
202 | return None | |
203 |
|
203 | |||
204 | return thisDatetime |
|
204 | return thisDatetime | |
205 |
|
205 | |||
206 |
|
206 | |||
207 | def isFolderInDateRange(folder, startDate=None, endDate=None): |
|
207 | def isFolderInDateRange(folder, startDate=None, endDate=None): | |
208 | """ |
|
208 | """ | |
209 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. |
|
209 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. | |
210 |
|
210 | |||
211 | Inputs: |
|
211 | Inputs: | |
212 | folder : nombre completo del directorio. |
|
212 | folder : nombre completo del directorio. | |
213 | Su formato deberia ser "/path_root/?YYYYDDD" |
|
213 | Su formato deberia ser "/path_root/?YYYYDDD" | |
214 |
|
214 | |||
215 | siendo: |
|
215 | siendo: | |
216 | YYYY : Anio (ejemplo 2015) |
|
216 | YYYY : Anio (ejemplo 2015) | |
217 | DDD : Dia del anio (ejemplo 305) |
|
217 | DDD : Dia del anio (ejemplo 305) | |
218 |
|
218 | |||
219 | startDate : fecha inicial del rango seleccionado en formato datetime.date |
|
219 | startDate : fecha inicial del rango seleccionado en formato datetime.date | |
220 |
|
220 | |||
221 | endDate : fecha final del rango seleccionado en formato datetime.date |
|
221 | endDate : fecha final del rango seleccionado en formato datetime.date | |
222 |
|
222 | |||
223 | Return: |
|
223 | Return: | |
224 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de |
|
224 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de | |
225 | fecha especificado, de lo contrario retorna False. |
|
225 | fecha especificado, de lo contrario retorna False. | |
226 | Excepciones: |
|
226 | Excepciones: | |
227 | Si el directorio no tiene el formato adecuado |
|
227 | Si el directorio no tiene el formato adecuado | |
228 | """ |
|
228 | """ | |
229 |
|
229 | |||
230 | basename = os.path.basename(folder) |
|
230 | basename = os.path.basename(folder) | |
231 |
|
231 | |||
232 | if not isRadarFolder(basename): |
|
232 | if not isRadarFolder(basename): | |
233 | print("The folder %s has not the rigth format" % folder) |
|
233 | print("The folder %s has not the rigth format" % folder) | |
234 | return 0 |
|
234 | return 0 | |
235 |
|
235 | |||
236 | if startDate and endDate: |
|
236 | if startDate and endDate: | |
237 | thisDate = getDateFromRadarFolder(basename) |
|
237 | thisDate = getDateFromRadarFolder(basename) | |
238 |
|
238 | |||
239 | if thisDate < startDate: |
|
239 | if thisDate < startDate: | |
240 | return 0 |
|
240 | return 0 | |
241 |
|
241 | |||
242 | if thisDate > endDate: |
|
242 | if thisDate > endDate: | |
243 | return 0 |
|
243 | return 0 | |
244 |
|
244 | |||
245 | return 1 |
|
245 | return 1 | |
246 |
|
246 | |||
247 |
|
247 | |||
248 | def isFileInDateRange(filename, startDate=None, endDate=None): |
|
248 | def isFileInDateRange(filename, startDate=None, endDate=None): | |
249 | """ |
|
249 | """ | |
250 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. |
|
250 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. | |
251 |
|
251 | |||
252 | Inputs: |
|
252 | Inputs: | |
253 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) |
|
253 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) | |
254 |
|
254 | |||
255 | Su formato deberia ser "?YYYYDDDsss" |
|
255 | Su formato deberia ser "?YYYYDDDsss" | |
256 |
|
256 | |||
257 | siendo: |
|
257 | siendo: | |
258 | YYYY : Anio (ejemplo 2015) |
|
258 | YYYY : Anio (ejemplo 2015) | |
259 | DDD : Dia del anio (ejemplo 305) |
|
259 | DDD : Dia del anio (ejemplo 305) | |
260 | sss : set |
|
260 | sss : set | |
261 |
|
261 | |||
262 | startDate : fecha inicial del rango seleccionado en formato datetime.date |
|
262 | startDate : fecha inicial del rango seleccionado en formato datetime.date | |
263 |
|
263 | |||
264 | endDate : fecha final del rango seleccionado en formato datetime.date |
|
264 | endDate : fecha final del rango seleccionado en formato datetime.date | |
265 |
|
265 | |||
266 | Return: |
|
266 | Return: | |
267 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de |
|
267 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de | |
268 | fecha especificado, de lo contrario retorna False. |
|
268 | fecha especificado, de lo contrario retorna False. | |
269 | Excepciones: |
|
269 | Excepciones: | |
270 | Si el archivo no tiene el formato adecuado |
|
270 | Si el archivo no tiene el formato adecuado | |
271 | """ |
|
271 | """ | |
272 |
|
272 | |||
273 | basename = os.path.basename(filename) |
|
273 | basename = os.path.basename(filename) | |
274 |
|
274 | |||
275 | if not isRadarFile(basename): |
|
275 | if not isRadarFile(basename): | |
276 | print("The filename %s has not the rigth format" % filename) |
|
276 | print("The filename %s has not the rigth format" % filename) | |
277 | return 0 |
|
277 | return 0 | |
278 |
|
278 | |||
279 | if startDate and endDate: |
|
279 | if startDate and endDate: | |
280 | thisDate = getDateFromRadarFile(basename) |
|
280 | thisDate = getDateFromRadarFile(basename) | |
281 |
|
281 | |||
282 | if thisDate < startDate: |
|
282 | if thisDate < startDate: | |
283 | return 0 |
|
283 | return 0 | |
284 |
|
284 | |||
285 | if thisDate > endDate: |
|
285 | if thisDate > endDate: | |
286 | return 0 |
|
286 | return 0 | |
287 |
|
287 | |||
288 | return 1 |
|
288 | return 1 | |
289 |
|
289 | |||
290 |
|
290 | |||
291 | def getFileFromSet(path, ext, set): |
|
291 | def getFileFromSet(path, ext, set): | |
292 | validFilelist = [] |
|
292 | validFilelist = [] | |
293 | fileList = os.listdir(path) |
|
293 | fileList = os.listdir(path) | |
294 |
|
294 | |||
295 | # 0 1234 567 89A BCDE |
|
295 | # 0 1234 567 89A BCDE | |
296 | # H YYYY DDD SSS .ext |
|
296 | # H YYYY DDD SSS .ext | |
297 |
|
297 | |||
298 | for thisFile in fileList: |
|
298 | for thisFile in fileList: | |
299 | try: |
|
299 | try: | |
300 | year = int(thisFile[1:5]) |
|
300 | year = int(thisFile[1:5]) | |
301 | doy = int(thisFile[5:8]) |
|
301 | doy = int(thisFile[5:8]) | |
302 | except: |
|
302 | except: | |
303 | continue |
|
303 | continue | |
304 |
|
304 | |||
305 | if (os.path.splitext(thisFile)[-1].lower() != ext.lower()): |
|
305 | if (os.path.splitext(thisFile)[-1].lower() != ext.lower()): | |
306 | continue |
|
306 | continue | |
307 |
|
307 | |||
308 | validFilelist.append(thisFile) |
|
308 | validFilelist.append(thisFile) | |
309 |
|
309 | |||
310 | myfile = fnmatch.filter( |
|
310 | myfile = fnmatch.filter( | |
311 | validFilelist, '*%4.4d%3.3d%3.3d*' % (year, doy, set)) |
|
311 | validFilelist, '*%4.4d%3.3d%3.3d*' % (year, doy, set)) | |
312 |
|
312 | |||
313 | if len(myfile) != 0: |
|
313 | if len(myfile) != 0: | |
314 | return myfile[0] |
|
314 | return myfile[0] | |
315 | else: |
|
315 | else: | |
316 | filename = '*%4.4d%3.3d%3.3d%s' % (year, doy, set, ext.lower()) |
|
316 | filename = '*%4.4d%3.3d%3.3d%s' % (year, doy, set, ext.lower()) | |
317 | print('the filename %s does not exist' % filename) |
|
317 | print('the filename %s does not exist' % filename) | |
318 | print('...going to the last file: ') |
|
318 | print('...going to the last file: ') | |
319 |
|
319 | |||
320 | if validFilelist: |
|
320 | if validFilelist: | |
321 | validFilelist = sorted(validFilelist, key=str.lower) |
|
321 | validFilelist = sorted(validFilelist, key=str.lower) | |
322 | return validFilelist[-1] |
|
322 | return validFilelist[-1] | |
323 |
|
323 | |||
324 | return None |
|
324 | return None | |
325 |
|
325 | |||
326 |
|
326 | |||
327 | def getlastFileFromPath(path, ext): |
|
327 | def getlastFileFromPath(path, ext): | |
328 | """ |
|
328 | """ | |
329 | Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext" |
|
329 | Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext" | |
330 | al final de la depuracion devuelve el ultimo file de la lista que quedo. |
|
330 | al final de la depuracion devuelve el ultimo file de la lista que quedo. | |
331 |
|
331 | |||
332 | Input: |
|
332 | Input: | |
333 | fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta |
|
333 | fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta | |
334 | ext : extension de los files contenidos en una carpeta |
|
334 | ext : extension de los files contenidos en una carpeta | |
335 |
|
335 | |||
336 | Return: |
|
336 | Return: | |
337 | El ultimo file de una determinada carpeta, no se considera el path. |
|
337 | El ultimo file de una determinada carpeta, no se considera el path. | |
338 | """ |
|
338 | """ | |
339 | validFilelist = [] |
|
339 | validFilelist = [] | |
340 | fileList = os.listdir(path) |
|
340 | fileList = os.listdir(path) | |
341 |
|
341 | |||
342 | # 0 1234 567 89A BCDE |
|
342 | # 0 1234 567 89A BCDE | |
343 | # H YYYY DDD SSS .ext |
|
343 | # H YYYY DDD SSS .ext | |
344 |
|
344 | |||
345 | for thisFile in fileList: |
|
345 | for thisFile in fileList: | |
346 |
|
346 | |||
347 | year = thisFile[1:5] |
|
347 | year = thisFile[1:5] | |
348 | if not isNumber(year): |
|
348 | if not isNumber(year): | |
349 | continue |
|
349 | continue | |
350 |
|
350 | |||
351 | doy = thisFile[5:8] |
|
351 | doy = thisFile[5:8] | |
352 | if not isNumber(doy): |
|
352 | if not isNumber(doy): | |
353 | continue |
|
353 | continue | |
354 |
|
354 | |||
355 | year = int(year) |
|
355 | year = int(year) | |
356 | doy = int(doy) |
|
356 | doy = int(doy) | |
357 |
|
357 | |||
358 | if (os.path.splitext(thisFile)[-1].lower() != ext.lower()): |
|
358 | if (os.path.splitext(thisFile)[-1].lower() != ext.lower()): | |
359 | continue |
|
359 | continue | |
360 |
|
360 | |||
361 | validFilelist.append(thisFile) |
|
361 | validFilelist.append(thisFile) | |
362 |
|
362 | |||
363 | if validFilelist: |
|
363 | if validFilelist: | |
364 | validFilelist = sorted(validFilelist, key=str.lower) |
|
364 | validFilelist = sorted(validFilelist, key=str.lower) | |
365 | return validFilelist[-1] |
|
365 | return validFilelist[-1] | |
366 |
|
366 | |||
367 | return None |
|
367 | return None | |
368 |
|
368 | |||
369 |
|
369 | |||
370 | def checkForRealPath(path, foldercounter, year, doy, set, ext): |
|
370 | def checkForRealPath(path, foldercounter, year, doy, set, ext): | |
371 | """ |
|
371 | """ | |
372 | Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path, |
|
372 | Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path, | |
373 | Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar |
|
373 | Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar | |
374 | el path exacto de un determinado file. |
|
374 | el path exacto de un determinado file. | |
375 |
|
375 | |||
376 | Example : |
|
376 | Example : | |
377 | nombre correcto del file es .../.../D2009307/P2009307367.ext |
|
377 | nombre correcto del file es .../.../D2009307/P2009307367.ext | |
378 |
|
378 | |||
379 | Entonces la funcion prueba con las siguientes combinaciones |
|
379 | Entonces la funcion prueba con las siguientes combinaciones | |
380 | .../.../y2009307367.ext |
|
380 | .../.../y2009307367.ext | |
381 | .../.../Y2009307367.ext |
|
381 | .../.../Y2009307367.ext | |
382 | .../.../x2009307/y2009307367.ext |
|
382 | .../.../x2009307/y2009307367.ext | |
383 | .../.../x2009307/Y2009307367.ext |
|
383 | .../.../x2009307/Y2009307367.ext | |
384 | .../.../X2009307/y2009307367.ext |
|
384 | .../.../X2009307/y2009307367.ext | |
385 | .../.../X2009307/Y2009307367.ext |
|
385 | .../.../X2009307/Y2009307367.ext | |
386 | siendo para este caso, la ultima combinacion de letras, identica al file buscado |
|
386 | siendo para este caso, la ultima combinacion de letras, identica al file buscado | |
387 |
|
387 | |||
388 | Return: |
|
388 | Return: | |
389 | Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file |
|
389 | Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file | |
390 | caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas |
|
390 | caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas | |
391 | para el filename |
|
391 | para el filename | |
392 | """ |
|
392 | """ | |
393 | fullfilename = None |
|
393 | fullfilename = None | |
394 | find_flag = False |
|
394 | find_flag = False | |
395 | filename = None |
|
395 | filename = None | |
396 |
|
396 | |||
397 | prefixDirList = [None, 'd', 'D'] |
|
397 | prefixDirList = [None, 'd', 'D'] | |
398 | if ext.lower() == ".r": # voltage |
|
398 | if ext.lower() == ".r": # voltage | |
399 | prefixFileList = ['d', 'D'] |
|
399 | prefixFileList = ['d', 'D'] | |
400 | elif ext.lower() == ".pdata": # spectra |
|
400 | elif ext.lower() == ".pdata": # spectra | |
401 | prefixFileList = ['p', 'P'] |
|
401 | prefixFileList = ['p', 'P'] | |
402 | else: |
|
402 | else: | |
403 | return None, filename |
|
403 | return None, filename | |
404 |
|
404 | |||
405 | # barrido por las combinaciones posibles |
|
405 | # barrido por las combinaciones posibles | |
406 | for prefixDir in prefixDirList: |
|
406 | for prefixDir in prefixDirList: | |
407 | thispath = path |
|
407 | thispath = path | |
408 | if prefixDir != None: |
|
408 | if prefixDir != None: | |
409 | # formo el nombre del directorio xYYYYDDD (x=d o x=D) |
|
409 | # formo el nombre del directorio xYYYYDDD (x=d o x=D) | |
410 | if foldercounter == 0: |
|
410 | if foldercounter == 0: | |
411 | thispath = os.path.join(path, "%s%04d%03d" % |
|
411 | thispath = os.path.join(path, "%s%04d%03d" % | |
412 | (prefixDir, year, doy)) |
|
412 | (prefixDir, year, doy)) | |
413 | else: |
|
413 | else: | |
414 | thispath = os.path.join(path, "%s%04d%03d_%02d" % ( |
|
414 | thispath = os.path.join(path, "%s%04d%03d_%02d" % ( | |
415 | prefixDir, year, doy, foldercounter)) |
|
415 | prefixDir, year, doy, foldercounter)) | |
416 | for prefixFile in prefixFileList: # barrido por las dos combinaciones posibles de "D" |
|
416 | for prefixFile in prefixFileList: # barrido por las dos combinaciones posibles de "D" | |
417 | # formo el nombre del file xYYYYDDDSSS.ext |
|
417 | # formo el nombre del file xYYYYDDDSSS.ext | |
418 | filename = "%s%04d%03d%03d%s" % (prefixFile, year, doy, set, ext) |
|
418 | filename = "%s%04d%03d%03d%s" % (prefixFile, year, doy, set, ext) | |
419 | fullfilename = os.path.join( |
|
419 | fullfilename = os.path.join( | |
420 | thispath, filename) # formo el path completo |
|
420 | thispath, filename) # formo el path completo | |
421 |
|
421 | |||
422 | if os.path.exists(fullfilename): # verifico que exista |
|
422 | if os.path.exists(fullfilename): # verifico que exista | |
423 | find_flag = True |
|
423 | find_flag = True | |
424 | break |
|
424 | break | |
425 | if find_flag: |
|
425 | if find_flag: | |
426 | break |
|
426 | break | |
427 |
|
427 | |||
428 | if not(find_flag): |
|
428 | if not(find_flag): | |
429 | return None, filename |
|
429 | return None, filename | |
430 |
|
430 | |||
431 | return fullfilename, filename |
|
431 | return fullfilename, filename | |
432 |
|
432 | |||
433 |
|
433 | |||
434 | def isRadarFolder(folder): |
|
434 | def isRadarFolder(folder): | |
435 | try: |
|
435 | try: | |
436 | year = int(folder[1:5]) |
|
436 | year = int(folder[1:5]) | |
437 | doy = int(folder[5:8]) |
|
437 | doy = int(folder[5:8]) | |
438 | except: |
|
438 | except: | |
439 | return 0 |
|
439 | return 0 | |
440 |
|
440 | |||
441 | return 1 |
|
441 | return 1 | |
442 |
|
442 | |||
443 |
|
443 | |||
444 | def isRadarFile(file): |
|
444 | def isRadarFile(file): | |
445 | try: |
|
445 | try: | |
446 | year = int(file[1:5]) |
|
446 | year = int(file[1:5]) | |
447 | doy = int(file[5:8]) |
|
447 | doy = int(file[5:8]) | |
448 | set = int(file[8:11]) |
|
448 | set = int(file[8:11]) | |
449 | except: |
|
449 | except: | |
450 | return 0 |
|
450 | return 0 | |
451 |
|
451 | |||
452 | return 1 |
|
452 | return 1 | |
453 |
|
453 | |||
454 |
|
454 | |||
455 | def getDateFromRadarFile(file): |
|
455 | def getDateFromRadarFile(file): | |
456 | try: |
|
456 | try: | |
457 | year = int(file[1:5]) |
|
457 | year = int(file[1:5]) | |
458 | doy = int(file[5:8]) |
|
458 | doy = int(file[5:8]) | |
459 | set = int(file[8:11]) |
|
459 | set = int(file[8:11]) | |
460 | except: |
|
460 | except: | |
461 | return None |
|
461 | return None | |
462 |
|
462 | |||
463 | thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1) |
|
463 | thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1) | |
464 | return thisDate |
|
464 | return thisDate | |
465 |
|
465 | |||
466 |
|
466 | |||
467 | def getDateFromRadarFolder(folder): |
|
467 | def getDateFromRadarFolder(folder): | |
468 | try: |
|
468 | try: | |
469 | year = int(folder[1:5]) |
|
469 | year = int(folder[1:5]) | |
470 | doy = int(folder[5:8]) |
|
470 | doy = int(folder[5:8]) | |
471 | except: |
|
471 | except: | |
472 | return None |
|
472 | return None | |
473 |
|
473 | |||
474 | thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1) |
|
474 | thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1) | |
475 | return thisDate |
|
475 | return thisDate | |
476 |
|
476 | |||
477 |
|
477 | |||
478 | class JRODataIO: |
|
478 | class JRODataIO: | |
479 |
|
479 | |||
480 | c = 3E8 |
|
480 | c = 3E8 | |
481 |
|
481 | |||
482 | isConfig = False |
|
482 | isConfig = False | |
483 |
|
483 | |||
484 | basicHeaderObj = None |
|
484 | basicHeaderObj = None | |
485 |
|
485 | |||
486 | systemHeaderObj = None |
|
486 | systemHeaderObj = None | |
487 |
|
487 | |||
488 | radarControllerHeaderObj = None |
|
488 | radarControllerHeaderObj = None | |
489 |
|
489 | |||
490 | processingHeaderObj = None |
|
490 | processingHeaderObj = None | |
491 |
|
491 | |||
492 | dtype = None |
|
492 | dtype = None | |
493 |
|
493 | |||
494 | pathList = [] |
|
494 | pathList = [] | |
495 |
|
495 | |||
496 | filenameList = [] |
|
496 | filenameList = [] | |
497 |
|
497 | |||
498 | filename = None |
|
498 | filename = None | |
499 |
|
499 | |||
500 | ext = None |
|
500 | ext = None | |
501 |
|
501 | |||
502 | flagIsNewFile = 1 |
|
502 | flagIsNewFile = 1 | |
503 |
|
503 | |||
504 | flagDiscontinuousBlock = 0 |
|
504 | flagDiscontinuousBlock = 0 | |
505 |
|
505 | |||
506 | flagIsNewBlock = 0 |
|
506 | flagIsNewBlock = 0 | |
507 |
|
507 | |||
508 | fp = None |
|
508 | fp = None | |
509 |
|
509 | |||
510 | firstHeaderSize = 0 |
|
510 | firstHeaderSize = 0 | |
511 |
|
511 | |||
512 | basicHeaderSize = 24 |
|
512 | basicHeaderSize = 24 | |
513 |
|
513 | |||
514 | versionFile = 1103 |
|
514 | versionFile = 1103 | |
515 |
|
515 | |||
516 | fileSize = None |
|
516 | fileSize = None | |
517 |
|
517 | |||
518 | # ippSeconds = None |
|
518 | # ippSeconds = None | |
519 |
|
519 | |||
520 | fileSizeByHeader = None |
|
520 | fileSizeByHeader = None | |
521 |
|
521 | |||
522 | fileIndex = None |
|
522 | fileIndex = None | |
523 |
|
523 | |||
524 | profileIndex = None |
|
524 | profileIndex = None | |
525 |
|
525 | |||
526 | blockIndex = None |
|
526 | blockIndex = None | |
527 |
|
527 | |||
528 | nTotalBlocks = None |
|
528 | nTotalBlocks = None | |
529 |
|
529 | |||
530 | maxTimeStep = 30 |
|
530 | maxTimeStep = 30 | |
531 |
|
531 | |||
532 | lastUTTime = None |
|
532 | lastUTTime = None | |
533 |
|
533 | |||
534 | datablock = None |
|
534 | datablock = None | |
535 |
|
535 | |||
536 | dataOut = None |
|
536 | dataOut = None | |
537 |
|
537 | |||
538 | blocksize = None |
|
538 | blocksize = None | |
539 |
|
539 | |||
540 | getByBlock = False |
|
540 | getByBlock = False | |
541 |
|
541 | |||
542 | def __init__(self): |
|
542 | def __init__(self): | |
543 |
|
543 | |||
544 | raise NotImplementedError |
|
544 | raise NotImplementedError | |
545 |
|
545 | |||
546 | def run(self): |
|
546 | def run(self): | |
547 |
|
547 | |||
548 | raise NotImplementedError |
|
548 | raise NotImplementedError | |
549 |
|
549 | |||
550 | def getDtypeWidth(self): |
|
550 | def getDtypeWidth(self): | |
551 |
|
551 | |||
552 | dtype_index = get_dtype_index(self.dtype) |
|
552 | dtype_index = get_dtype_index(self.dtype) | |
553 | dtype_width = get_dtype_width(dtype_index) |
|
553 | dtype_width = get_dtype_width(dtype_index) | |
554 |
|
554 | |||
555 | return dtype_width |
|
555 | return dtype_width | |
556 |
|
556 | |||
557 | def getAllowedArgs(self): |
|
557 | def getAllowedArgs(self): | |
558 | if hasattr(self, '__attrs__'): |
|
558 | if hasattr(self, '__attrs__'): | |
559 | return self.__attrs__ |
|
559 | return self.__attrs__ | |
560 | else: |
|
560 | else: | |
561 | return inspect.getargspec(self.run).args |
|
561 | return inspect.getargspec(self.run).args | |
562 |
|
562 | |||
563 |
|
563 | |||
564 | class JRODataReader(JRODataIO): |
|
564 | class JRODataReader(JRODataIO): | |
565 |
|
565 | |||
566 | online = 0 |
|
566 | online = 0 | |
567 |
|
567 | |||
568 | realtime = 0 |
|
568 | realtime = 0 | |
569 |
|
569 | |||
570 | nReadBlocks = 0 |
|
570 | nReadBlocks = 0 | |
571 |
|
571 | |||
572 | delay = 10 # number of seconds waiting a new file |
|
572 | delay = 10 # number of seconds waiting a new file | |
573 |
|
573 | |||
574 | nTries = 3 # quantity tries |
|
574 | nTries = 3 # quantity tries | |
575 |
|
575 | |||
576 | nFiles = 3 # number of files for searching |
|
576 | nFiles = 3 # number of files for searching | |
577 |
|
577 | |||
578 | path = None |
|
578 | path = None | |
579 |
|
579 | |||
580 | foldercounter = 0 |
|
580 | foldercounter = 0 | |
581 |
|
581 | |||
582 | flagNoMoreFiles = 0 |
|
582 | flagNoMoreFiles = 0 | |
583 |
|
583 | |||
584 | datetimeList = [] |
|
584 | datetimeList = [] | |
585 |
|
585 | |||
586 | __isFirstTimeOnline = 1 |
|
586 | __isFirstTimeOnline = 1 | |
587 |
|
587 | |||
588 | __printInfo = True |
|
588 | __printInfo = True | |
589 |
|
589 | |||
590 | profileIndex = None |
|
590 | profileIndex = None | |
591 |
|
591 | |||
592 | nTxs = 1 |
|
592 | nTxs = 1 | |
593 |
|
593 | |||
594 | txIndex = None |
|
594 | txIndex = None | |
595 |
|
595 | |||
596 | # Added-------------------- |
|
596 | # Added-------------------- | |
597 |
|
597 | |||
598 | selBlocksize = None |
|
598 | selBlocksize = None | |
599 |
|
599 | |||
600 | selBlocktime = None |
|
600 | selBlocktime = None | |
601 |
|
601 | |||
602 | def __init__(self): |
|
602 | def __init__(self): | |
603 | """ |
|
603 | """ | |
604 | This class is used to find data files |
|
604 | This class is used to find data files | |
605 |
|
605 | |||
606 | Example: |
|
606 | Example: | |
607 | reader = JRODataReader() |
|
607 | reader = JRODataReader() | |
608 | fileList = reader.findDataFiles() |
|
608 | fileList = reader.findDataFiles() | |
609 |
|
609 | |||
610 | """ |
|
610 | """ | |
611 | pass |
|
611 | pass | |
612 |
|
612 | |||
613 | def createObjByDefault(self): |
|
613 | def createObjByDefault(self): | |
614 | """ |
|
614 | """ | |
615 |
|
615 | |||
616 | """ |
|
616 | """ | |
617 | raise NotImplementedError |
|
617 | raise NotImplementedError | |
618 |
|
618 | |||
619 | def getBlockDimension(self): |
|
619 | def getBlockDimension(self): | |
620 |
|
620 | |||
621 | raise NotImplementedError |
|
621 | raise NotImplementedError | |
622 |
|
622 | |||
623 | def searchFilesOffLine(self, |
|
623 | def searchFilesOffLine(self, | |
624 | path, |
|
624 | path, | |
625 | startDate=None, |
|
625 | startDate=None, | |
626 | endDate=None, |
|
626 | endDate=None, | |
627 | startTime=datetime.time(0, 0, 0), |
|
627 | startTime=datetime.time(0, 0, 0), | |
628 | endTime=datetime.time(23, 59, 59), |
|
628 | endTime=datetime.time(23, 59, 59), | |
629 | set=None, |
|
629 | set=None, | |
630 | expLabel='', |
|
630 | expLabel='', | |
631 | ext='.r', |
|
631 | ext='.r', | |
632 | cursor=None, |
|
632 | cursor=None, | |
633 | skip=None, |
|
633 | skip=None, | |
634 | walk=True): |
|
634 | walk=True): | |
635 |
|
635 | |||
636 | self.filenameList = [] |
|
636 | self.filenameList = [] | |
637 | self.datetimeList = [] |
|
637 | self.datetimeList = [] | |
638 |
|
638 | |||
639 | pathList = [] |
|
639 | pathList = [] | |
640 |
|
640 | |||
641 | dateList, pathList = self.findDatafiles( |
|
641 | dateList, pathList = self.findDatafiles( | |
642 | path, startDate, endDate, expLabel, ext, walk, include_path=True) |
|
642 | path, startDate, endDate, expLabel, ext, walk, include_path=True) | |
643 |
|
643 | |||
644 | if dateList == []: |
|
644 | if dateList == []: | |
645 | return [], [] |
|
645 | return [], [] | |
646 |
|
646 | |||
647 | if len(dateList) > 1: |
|
647 | if len(dateList) > 1: | |
648 | print("[Reading] Data found for date range [%s - %s]: total days = %d" % (startDate, endDate, len(dateList))) |
|
648 | print("[Reading] Data found for date range [%s - %s]: total days = %d" % (startDate, endDate, len(dateList))) | |
649 | else: |
|
649 | else: | |
650 | print("[Reading] Data found for date range [%s - %s]: date = %s" % (startDate, endDate, dateList[0])) |
|
650 | print("[Reading] Data found for date range [%s - %s]: date = %s" % (startDate, endDate, dateList[0])) | |
651 |
|
651 | |||
652 | filenameList = [] |
|
652 | filenameList = [] | |
653 | datetimeList = [] |
|
653 | datetimeList = [] | |
654 |
|
654 | |||
655 | for thisPath in pathList: |
|
655 | for thisPath in pathList: | |
656 |
|
656 | |||
657 | fileList = glob.glob1(thisPath, "*%s" % ext) |
|
657 | fileList = glob.glob1(thisPath, "*%s" % ext) | |
658 | fileList.sort() |
|
658 | fileList.sort() | |
659 |
|
659 | |||
660 | for file in fileList: |
|
660 | for file in fileList: | |
661 |
|
661 | |||
662 | filename = os.path.join(thisPath, file) |
|
662 | filename = os.path.join(thisPath, file) | |
663 |
|
663 | |||
664 | if not isFileInDateRange(filename, startDate, endDate): |
|
664 | if not isFileInDateRange(filename, startDate, endDate): | |
665 | continue |
|
665 | continue | |
666 |
|
666 | |||
667 | thisDatetime = isFileInTimeRange( |
|
667 | thisDatetime = isFileInTimeRange( | |
668 | filename, startDate, endDate, startTime, endTime) |
|
668 | filename, startDate, endDate, startTime, endTime) | |
669 |
|
669 | |||
670 | if not(thisDatetime): |
|
670 | if not(thisDatetime): | |
671 | continue |
|
671 | continue | |
672 |
|
672 | |||
673 | filenameList.append(filename) |
|
673 | filenameList.append(filename) | |
674 | datetimeList.append(thisDatetime) |
|
674 | datetimeList.append(thisDatetime) | |
675 |
|
675 | |||
676 | if cursor is not None and skip is not None: |
|
676 | if cursor is not None and skip is not None: | |
677 | filenameList = filenameList[cursor * skip:cursor * skip + skip] |
|
677 | filenameList = filenameList[cursor * skip:cursor * skip + skip] | |
678 | datetimeList = datetimeList[cursor * skip:cursor * skip + skip] |
|
678 | datetimeList = datetimeList[cursor * skip:cursor * skip + skip] | |
679 |
|
679 | |||
680 | if not(filenameList): |
|
680 | if not(filenameList): | |
681 | print("[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" % (startTime, endTime, ext, path)) |
|
681 | print("[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" % (startTime, endTime, ext, path)) | |
682 | return [], [] |
|
682 | return [], [] | |
683 |
|
683 | |||
684 | print("[Reading] %d file(s) was(were) found in time range: %s - %s" % (len(filenameList), startTime, endTime)) |
|
684 | print("[Reading] %d file(s) was(were) found in time range: %s - %s" % (len(filenameList), startTime, endTime)) | |
685 |
|
685 | |||
686 | # for i in range(len(filenameList)): |
|
686 | # for i in range(len(filenameList)): | |
687 | # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime()) |
|
687 | # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime()) | |
688 |
|
688 | |||
689 | self.filenameList = filenameList |
|
689 | self.filenameList = filenameList | |
690 | self.datetimeList = datetimeList |
|
690 | self.datetimeList = datetimeList | |
691 |
|
691 | |||
692 | return pathList, filenameList |
|
692 | return pathList, filenameList | |
693 |
|
693 | |||
694 | def __searchFilesOnLine(self, path, expLabel="", ext=None, walk=True, set=None): |
|
694 | def __searchFilesOnLine(self, path, expLabel="", ext=None, walk=True, set=None): | |
695 | """ |
|
695 | """ | |
696 | Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y |
|
696 | Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y | |
697 | devuelve el archivo encontrado ademas de otros datos. |
|
697 | devuelve el archivo encontrado ademas de otros datos. | |
698 |
|
698 | |||
699 | Input: |
|
699 | Input: | |
700 | path : carpeta donde estan contenidos los files que contiene data |
|
700 | path : carpeta donde estan contenidos los files que contiene data | |
701 |
|
701 | |||
702 | expLabel : Nombre del subexperimento (subfolder) |
|
702 | expLabel : Nombre del subexperimento (subfolder) | |
703 |
|
703 | |||
704 | ext : extension de los files |
|
704 | ext : extension de los files | |
705 |
|
705 | |||
706 | walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath) |
|
706 | walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath) | |
707 |
|
707 | |||
708 | Return: |
|
708 | Return: | |
709 | directory : eL directorio donde esta el file encontrado |
|
709 | directory : eL directorio donde esta el file encontrado | |
710 | filename : el ultimo file de una determinada carpeta |
|
710 | filename : el ultimo file de una determinada carpeta | |
711 | year : el anho |
|
711 | year : el anho | |
712 | doy : el numero de dia del anho |
|
712 | doy : el numero de dia del anho | |
713 | set : el set del archivo |
|
713 | set : el set del archivo | |
714 |
|
714 | |||
715 |
|
715 | |||
716 | """ |
|
716 | """ | |
717 | if not os.path.isdir(path): |
|
717 | if not os.path.isdir(path): | |
718 | return None, None, None, None, None, None |
|
718 | return None, None, None, None, None, None | |
719 |
|
719 | |||
720 | dirList = [] |
|
720 | dirList = [] | |
721 |
|
721 | |||
722 | if not walk: |
|
722 | if not walk: | |
723 | fullpath = path |
|
723 | fullpath = path | |
724 | foldercounter = 0 |
|
724 | foldercounter = 0 | |
725 | else: |
|
725 | else: | |
726 | # Filtra solo los directorios |
|
726 | # Filtra solo los directorios | |
727 | for thisPath in os.listdir(path): |
|
727 | for thisPath in os.listdir(path): | |
728 | if not os.path.isdir(os.path.join(path, thisPath)): |
|
728 | if not os.path.isdir(os.path.join(path, thisPath)): | |
729 | continue |
|
729 | continue | |
730 | if not isRadarFolder(thisPath): |
|
730 | if not isRadarFolder(thisPath): | |
731 | continue |
|
731 | continue | |
732 |
|
732 | |||
733 | dirList.append(thisPath) |
|
733 | dirList.append(thisPath) | |
734 |
|
734 | |||
735 | if not(dirList): |
|
735 | if not(dirList): | |
736 | return None, None, None, None, None, None |
|
736 | return None, None, None, None, None, None | |
737 |
|
737 | |||
738 | dirList = sorted(dirList, key=str.lower) |
|
738 | dirList = sorted(dirList, key=str.lower) | |
739 |
|
739 | |||
740 | doypath = dirList[-1] |
|
740 | doypath = dirList[-1] | |
741 | foldercounter = int(doypath.split('_')[1]) if len( |
|
741 | foldercounter = int(doypath.split('_')[1]) if len( | |
742 | doypath.split('_')) > 1 else 0 |
|
742 | doypath.split('_')) > 1 else 0 | |
743 | fullpath = os.path.join(path, doypath, expLabel) |
|
743 | fullpath = os.path.join(path, doypath, expLabel) | |
744 |
|
744 | |||
745 | print("[Reading] %s folder was found: " % (fullpath)) |
|
745 | print("[Reading] %s folder was found: " % (fullpath)) | |
746 |
|
746 | |||
747 | if set == None: |
|
747 | if set == None: | |
748 | filename = getlastFileFromPath(fullpath, ext) |
|
748 | filename = getlastFileFromPath(fullpath, ext) | |
749 | else: |
|
749 | else: | |
750 | filename = getFileFromSet(fullpath, ext, set) |
|
750 | filename = getFileFromSet(fullpath, ext, set) | |
751 |
|
751 | |||
752 | if not(filename): |
|
752 | if not(filename): | |
753 | return None, None, None, None, None, None |
|
753 | return None, None, None, None, None, None | |
754 |
|
754 | |||
755 | print("[Reading] %s file was found" % (filename)) |
|
755 | print("[Reading] %s file was found" % (filename)) | |
756 |
|
756 | |||
757 | if not(self.__verifyFile(os.path.join(fullpath, filename))): |
|
757 | if not(self.__verifyFile(os.path.join(fullpath, filename))): | |
758 | return None, None, None, None, None, None |
|
758 | return None, None, None, None, None, None | |
759 |
|
759 | |||
760 | year = int(filename[1:5]) |
|
760 | year = int(filename[1:5]) | |
761 | doy = int(filename[5:8]) |
|
761 | doy = int(filename[5:8]) | |
762 | set = int(filename[8:11]) |
|
762 | set = int(filename[8:11]) | |
763 |
|
763 | |||
764 | return fullpath, foldercounter, filename, year, doy, set |
|
764 | return fullpath, foldercounter, filename, year, doy, set | |
765 |
|
765 | |||
766 | def __setNextFileOffline(self): |
|
766 | def __setNextFileOffline(self): | |
767 |
|
767 | |||
768 | idFile = self.fileIndex |
|
768 | idFile = self.fileIndex | |
769 |
|
769 | |||
770 | while (True): |
|
770 | while (True): | |
771 | idFile += 1 |
|
771 | idFile += 1 | |
772 | if not(idFile < len(self.filenameList)): |
|
772 | if not(idFile < len(self.filenameList)): | |
773 | self.flagNoMoreFiles = 1 |
|
773 | self.flagNoMoreFiles = 1 | |
774 | # print "[Reading] No more Files" |
|
774 | # print "[Reading] No more Files" | |
775 | return 0 |
|
775 | return 0 | |
776 |
|
776 | |||
777 | filename = self.filenameList[idFile] |
|
777 | filename = self.filenameList[idFile] | |
778 |
|
778 | |||
779 | if not(self.__verifyFile(filename)): |
|
779 | if not(self.__verifyFile(filename)): | |
780 | continue |
|
780 | continue | |
781 |
|
781 | |||
782 | fileSize = os.path.getsize(filename) |
|
782 | fileSize = os.path.getsize(filename) | |
783 | fp = open(filename, 'rb') |
|
783 | fp = open(filename, 'rb') | |
784 | break |
|
784 | break | |
785 |
|
785 | |||
786 | self.flagIsNewFile = 1 |
|
786 | self.flagIsNewFile = 1 | |
787 | self.fileIndex = idFile |
|
787 | self.fileIndex = idFile | |
788 | self.filename = filename |
|
788 | self.filename = filename | |
789 | self.fileSize = fileSize |
|
789 | self.fileSize = fileSize | |
790 | self.fp = fp |
|
790 | self.fp = fp | |
791 |
|
791 | |||
792 | # print "[Reading] Setting the file: %s"%self.filename |
|
792 | # print "[Reading] Setting the file: %s"%self.filename | |
793 |
|
793 | |||
794 | return 1 |
|
794 | return 1 | |
795 |
|
795 | |||
796 | def __setNextFileOnline(self): |
|
796 | def __setNextFileOnline(self): | |
797 | """ |
|
797 | """ | |
798 | Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si |
|
798 | Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si | |
799 | no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files |
|
799 | no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files | |
800 | siguientes. |
|
800 | siguientes. | |
801 |
|
801 | |||
802 | Affected: |
|
802 | Affected: | |
803 | self.flagIsNewFile |
|
803 | self.flagIsNewFile | |
804 | self.filename |
|
804 | self.filename | |
805 | self.fileSize |
|
805 | self.fileSize | |
806 | self.fp |
|
806 | self.fp | |
807 | self.set |
|
807 | self.set | |
808 | self.flagNoMoreFiles |
|
808 | self.flagNoMoreFiles | |
809 |
|
809 | |||
810 | Return: |
|
810 | Return: | |
811 | 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado |
|
811 | 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado | |
812 | 1 : si el file fue abierto con exito y esta listo a ser leido |
|
812 | 1 : si el file fue abierto con exito y esta listo a ser leido | |
813 |
|
813 | |||
814 | Excepciones: |
|
814 | Excepciones: | |
815 | Si un determinado file no puede ser abierto |
|
815 | Si un determinado file no puede ser abierto | |
816 | """ |
|
816 | """ | |
817 | nFiles = 0 |
|
817 | nFiles = 0 | |
818 | fileOk_flag = False |
|
818 | fileOk_flag = False | |
819 | firstTime_flag = True |
|
819 | firstTime_flag = True | |
820 |
|
820 | |||
821 | self.set += 1 |
|
821 | self.set += 1 | |
822 |
|
822 | |||
823 | if self.set > 999: |
|
823 | if self.set > 999: | |
824 | self.set = 0 |
|
824 | self.set = 0 | |
825 | self.foldercounter += 1 |
|
825 | self.foldercounter += 1 | |
826 |
|
826 | |||
827 | # busca el 1er file disponible |
|
827 | # busca el 1er file disponible | |
828 | fullfilename, filename = checkForRealPath( |
|
828 | fullfilename, filename = checkForRealPath( | |
829 | self.path, self.foldercounter, self.year, self.doy, self.set, self.ext) |
|
829 | self.path, self.foldercounter, self.year, self.doy, self.set, self.ext) | |
830 | if fullfilename: |
|
830 | if fullfilename: | |
831 | if self.__verifyFile(fullfilename, False): |
|
831 | if self.__verifyFile(fullfilename, False): | |
832 | fileOk_flag = True |
|
832 | fileOk_flag = True | |
833 |
|
833 | |||
834 | # si no encuentra un file entonces espera y vuelve a buscar |
|
834 | # si no encuentra un file entonces espera y vuelve a buscar | |
835 | if not(fileOk_flag): |
|
835 | if not(fileOk_flag): | |
836 | # busco en los siguientes self.nFiles+1 files posibles |
|
836 | # busco en los siguientes self.nFiles+1 files posibles | |
837 | for nFiles in range(self.nFiles + 1): |
|
837 | for nFiles in range(self.nFiles + 1): | |
838 |
|
838 | |||
839 | if firstTime_flag: # si es la 1era vez entonces hace el for self.nTries veces |
|
839 | if firstTime_flag: # si es la 1era vez entonces hace el for self.nTries veces | |
840 | tries = self.nTries |
|
840 | tries = self.nTries | |
841 | else: |
|
841 | else: | |
842 | tries = 1 # si no es la 1era vez entonces solo lo hace una vez |
|
842 | tries = 1 # si no es la 1era vez entonces solo lo hace una vez | |
843 |
|
843 | |||
844 | for nTries in range(tries): |
|
844 | for nTries in range(tries): | |
845 | if firstTime_flag: |
|
845 | if firstTime_flag: | |
846 | print("\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % (self.delay, filename, nTries + 1)) |
|
846 | print("\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % (self.delay, filename, nTries + 1)) | |
847 | sleep(self.delay) |
|
847 | sleep(self.delay) | |
848 | else: |
|
848 | else: | |
849 | print("\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)) |
|
849 | print("\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)) | |
850 |
|
850 | |||
851 | fullfilename, filename = checkForRealPath( |
|
851 | fullfilename, filename = checkForRealPath( | |
852 | self.path, self.foldercounter, self.year, self.doy, self.set, self.ext) |
|
852 | self.path, self.foldercounter, self.year, self.doy, self.set, self.ext) | |
853 | if fullfilename: |
|
853 | if fullfilename: | |
854 | if self.__verifyFile(fullfilename): |
|
854 | if self.__verifyFile(fullfilename): | |
855 | fileOk_flag = True |
|
855 | fileOk_flag = True | |
856 | break |
|
856 | break | |
857 |
|
857 | |||
858 | if fileOk_flag: |
|
858 | if fileOk_flag: | |
859 | break |
|
859 | break | |
860 |
|
860 | |||
861 | firstTime_flag = False |
|
861 | firstTime_flag = False | |
862 |
|
862 | |||
863 | log.warning('Skipping the file {} due to this file doesn\'t exist'.format(filename)) |
|
863 | log.warning('Skipping the file {} due to this file doesn\'t exist'.format(filename)) | |
864 | self.set += 1 |
|
864 | self.set += 1 | |
865 |
|
865 | |||
866 | # si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta |
|
866 | # si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta | |
867 | if nFiles == (self.nFiles - 1): |
|
867 | if nFiles == (self.nFiles - 1): | |
868 | self.set = 0 |
|
868 | self.set = 0 | |
869 | self.doy += 1 |
|
869 | self.doy += 1 | |
870 | self.foldercounter = 0 |
|
870 | self.foldercounter = 0 | |
871 |
|
871 | |||
872 | if fileOk_flag: |
|
872 | if fileOk_flag: | |
873 | self.fileSize = os.path.getsize(fullfilename) |
|
873 | self.fileSize = os.path.getsize(fullfilename) | |
874 | self.filename = fullfilename |
|
874 | self.filename = fullfilename | |
875 | self.flagIsNewFile = 1 |
|
875 | self.flagIsNewFile = 1 | |
876 | if self.fp != None: |
|
876 | if self.fp != None: | |
877 | self.fp.close() |
|
877 | self.fp.close() | |
878 | self.fp = open(fullfilename, 'rb') |
|
878 | self.fp = open(fullfilename, 'rb') | |
879 | self.flagNoMoreFiles = 0 |
|
879 | self.flagNoMoreFiles = 0 | |
880 | # print '[Reading] Setting the file: %s' % fullfilename |
|
880 | # print '[Reading] Setting the file: %s' % fullfilename | |
881 | else: |
|
881 | else: | |
882 | self.fileSize = 0 |
|
882 | self.fileSize = 0 | |
883 | self.filename = None |
|
883 | self.filename = None | |
884 | self.flagIsNewFile = 0 |
|
884 | self.flagIsNewFile = 0 | |
885 | self.fp = None |
|
885 | self.fp = None | |
886 | self.flagNoMoreFiles = 1 |
|
886 | self.flagNoMoreFiles = 1 | |
887 | # print '[Reading] No more files to read' |
|
887 | # print '[Reading] No more files to read' | |
888 |
|
888 | |||
889 | return fileOk_flag |
|
889 | return fileOk_flag | |
890 |
|
890 | |||
891 | def setNextFile(self): |
|
891 | def setNextFile(self): | |
892 | if self.fp != None: |
|
892 | if self.fp != None: | |
893 | self.fp.close() |
|
893 | self.fp.close() | |
894 |
|
894 | |||
895 | if self.online: |
|
895 | if self.online: | |
896 | newFile = self.__setNextFileOnline() |
|
896 | newFile = self.__setNextFileOnline() | |
897 | else: |
|
897 | else: | |
898 | newFile = self.__setNextFileOffline() |
|
898 | newFile = self.__setNextFileOffline() | |
899 |
|
899 | |||
900 | if not(newFile): |
|
900 | if not(newFile): | |
901 | self.dataOut.error = 'No more files to read' |
|
901 | self.dataOut.error = 'No more files to read' | |
902 | return 0 |
|
902 | return 0 | |
903 |
|
903 | |||
904 | if self.verbose: |
|
904 | if self.verbose: | |
905 | print('[Reading] Setting the file: %s' % self.filename) |
|
905 | print('[Reading] Setting the file: %s' % self.filename) | |
906 |
|
906 | |||
907 | self.__readFirstHeader() |
|
907 | self.__readFirstHeader() | |
908 | self.nReadBlocks = 0 |
|
908 | self.nReadBlocks = 0 | |
909 | return 1 |
|
909 | return 1 | |
910 |
|
910 | |||
911 | def __waitNewBlock(self): |
|
911 | def __waitNewBlock(self): | |
912 | """ |
|
912 | """ | |
913 | Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma. |
|
913 | Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma. | |
914 |
|
914 | |||
915 | Si el modo de lectura es OffLine siempre retorn 0 |
|
915 | Si el modo de lectura es OffLine siempre retorn 0 | |
916 | """ |
|
916 | """ | |
917 | if not self.online: |
|
917 | if not self.online: | |
918 | return 0 |
|
918 | return 0 | |
919 |
|
919 | |||
920 | if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile): |
|
920 | if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile): | |
921 | return 0 |
|
921 | return 0 | |
922 |
|
922 | |||
923 | currentPointer = self.fp.tell() |
|
923 | currentPointer = self.fp.tell() | |
924 |
|
924 | |||
925 | neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize |
|
925 | neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize | |
926 |
|
926 | |||
927 | for nTries in range(self.nTries): |
|
927 | for nTries in range(self.nTries): | |
928 |
|
928 | |||
929 | self.fp.close() |
|
929 | self.fp.close() | |
930 | self.fp = open(self.filename, 'rb') |
|
930 | self.fp = open(self.filename, 'rb') | |
931 | self.fp.seek(currentPointer) |
|
931 | self.fp.seek(currentPointer) | |
932 |
|
932 | |||
933 | self.fileSize = os.path.getsize(self.filename) |
|
933 | self.fileSize = os.path.getsize(self.filename) | |
934 | currentSize = self.fileSize - currentPointer |
|
934 | currentSize = self.fileSize - currentPointer | |
935 |
|
935 | |||
936 | if (currentSize >= neededSize): |
|
936 | if (currentSize >= neededSize): | |
937 | self.basicHeaderObj.read(self.fp) |
|
937 | self.basicHeaderObj.read(self.fp) | |
938 | return 1 |
|
938 | return 1 | |
939 |
|
939 | |||
940 | if self.fileSize == self.fileSizeByHeader: |
|
940 | if self.fileSize == self.fileSizeByHeader: | |
941 | # self.flagEoF = True |
|
941 | # self.flagEoF = True | |
942 | return 0 |
|
942 | return 0 | |
943 |
|
943 | |||
944 | print("[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1)) |
|
944 | print("[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1)) | |
945 | sleep(self.delay) |
|
945 | sleep(self.delay) | |
946 |
|
946 | |||
947 | return 0 |
|
947 | return 0 | |
948 |
|
948 | |||
949 | def waitDataBlock(self, pointer_location): |
|
949 | def waitDataBlock(self, pointer_location): | |
950 |
|
950 | |||
951 | currentPointer = pointer_location |
|
951 | currentPointer = pointer_location | |
952 |
|
952 | |||
953 | neededSize = self.processingHeaderObj.blockSize # + self.basicHeaderSize |
|
953 | neededSize = self.processingHeaderObj.blockSize # + self.basicHeaderSize | |
954 |
|
954 | |||
955 | for nTries in range(self.nTries): |
|
955 | for nTries in range(self.nTries): | |
956 | self.fp.close() |
|
956 | self.fp.close() | |
957 | self.fp = open(self.filename, 'rb') |
|
957 | self.fp = open(self.filename, 'rb') | |
958 | self.fp.seek(currentPointer) |
|
958 | self.fp.seek(currentPointer) | |
959 |
|
959 | |||
960 | self.fileSize = os.path.getsize(self.filename) |
|
960 | self.fileSize = os.path.getsize(self.filename) | |
961 | currentSize = self.fileSize - currentPointer |
|
961 | currentSize = self.fileSize - currentPointer | |
962 |
|
962 | |||
963 | if (currentSize >= neededSize): |
|
963 | if (currentSize >= neededSize): | |
964 | return 1 |
|
964 | return 1 | |
965 |
|
965 | |||
966 | print("[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1)) |
|
966 | print("[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1)) | |
967 | sleep(self.delay) |
|
967 | sleep(self.delay) | |
968 |
|
968 | |||
969 | return 0 |
|
969 | return 0 | |
970 |
|
970 | |||
971 | def __jumpToLastBlock(self): |
|
971 | def __jumpToLastBlock(self): | |
972 |
|
972 | |||
973 | if not(self.__isFirstTimeOnline): |
|
973 | if not(self.__isFirstTimeOnline): | |
974 | return |
|
974 | return | |
975 |
|
975 | |||
976 | csize = self.fileSize - self.fp.tell() |
|
976 | csize = self.fileSize - self.fp.tell() | |
977 | blocksize = self.processingHeaderObj.blockSize |
|
977 | blocksize = self.processingHeaderObj.blockSize | |
978 |
|
978 | |||
979 | # salta el primer bloque de datos |
|
979 | # salta el primer bloque de datos | |
980 | if csize > self.processingHeaderObj.blockSize: |
|
980 | if csize > self.processingHeaderObj.blockSize: | |
981 | self.fp.seek(self.fp.tell() + blocksize) |
|
981 | self.fp.seek(self.fp.tell() + blocksize) | |
982 | else: |
|
982 | else: | |
983 | return |
|
983 | return | |
984 |
|
984 | |||
985 | csize = self.fileSize - self.fp.tell() |
|
985 | csize = self.fileSize - self.fp.tell() | |
986 | neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize |
|
986 | neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize | |
987 | while True: |
|
987 | while True: | |
988 |
|
988 | |||
989 | if self.fp.tell() < self.fileSize: |
|
989 | if self.fp.tell() < self.fileSize: | |
990 | self.fp.seek(self.fp.tell() + neededsize) |
|
990 | self.fp.seek(self.fp.tell() + neededsize) | |
991 | else: |
|
991 | else: | |
992 | self.fp.seek(self.fp.tell() - neededsize) |
|
992 | self.fp.seek(self.fp.tell() - neededsize) | |
993 | break |
|
993 | break | |
994 |
|
994 | |||
995 | # csize = self.fileSize - self.fp.tell() |
|
995 | # csize = self.fileSize - self.fp.tell() | |
996 | # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize |
|
996 | # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize | |
997 | # factor = int(csize/neededsize) |
|
997 | # factor = int(csize/neededsize) | |
998 | # if factor > 0: |
|
998 | # if factor > 0: | |
999 | # self.fp.seek(self.fp.tell() + factor*neededsize) |
|
999 | # self.fp.seek(self.fp.tell() + factor*neededsize) | |
1000 |
|
1000 | |||
1001 | self.flagIsNewFile = 0 |
|
1001 | self.flagIsNewFile = 0 | |
1002 | self.__isFirstTimeOnline = 0 |
|
1002 | self.__isFirstTimeOnline = 0 | |
1003 |
|
1003 | |||
1004 | def __setNewBlock(self): |
|
1004 | def __setNewBlock(self): | |
1005 | # if self.server is None: |
|
1005 | # if self.server is None: | |
1006 | if self.fp == None: |
|
1006 | if self.fp == None: | |
1007 | return 0 |
|
1007 | return 0 | |
1008 |
|
1008 | |||
1009 | # if self.online: |
|
1009 | # if self.online: | |
1010 | # self.__jumpToLastBlock() |
|
1010 | # self.__jumpToLastBlock() | |
1011 |
|
1011 | |||
1012 | if self.flagIsNewFile: |
|
1012 | if self.flagIsNewFile: | |
1013 | self.lastUTTime = self.basicHeaderObj.utc |
|
1013 | self.lastUTTime = self.basicHeaderObj.utc | |
1014 | return 1 |
|
1014 | return 1 | |
1015 |
|
1015 | |||
1016 | if self.realtime: |
|
1016 | if self.realtime: | |
1017 | self.flagDiscontinuousBlock = 1 |
|
1017 | self.flagDiscontinuousBlock = 1 | |
1018 | if not(self.setNextFile()): |
|
1018 | if not(self.setNextFile()): | |
1019 | return 0 |
|
1019 | return 0 | |
1020 | else: |
|
1020 | else: | |
1021 | return 1 |
|
1021 | return 1 | |
1022 | # if self.server is None: |
|
1022 | # if self.server is None: | |
1023 | currentSize = self.fileSize - self.fp.tell() |
|
1023 | currentSize = self.fileSize - self.fp.tell() | |
1024 | neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize |
|
1024 | neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize | |
1025 | if (currentSize >= neededSize): |
|
1025 | if (currentSize >= neededSize): | |
1026 | self.basicHeaderObj.read(self.fp) |
|
1026 | self.basicHeaderObj.read(self.fp) | |
1027 | self.lastUTTime = self.basicHeaderObj.utc |
|
1027 | self.lastUTTime = self.basicHeaderObj.utc | |
1028 | return 1 |
|
1028 | return 1 | |
1029 | # else: |
|
1029 | # else: | |
1030 | # self.basicHeaderObj.read(self.zHeader) |
|
1030 | # self.basicHeaderObj.read(self.zHeader) | |
1031 | # self.lastUTTime = self.basicHeaderObj.utc |
|
1031 | # self.lastUTTime = self.basicHeaderObj.utc | |
1032 | # return 1 |
|
1032 | # return 1 | |
1033 | if self.__waitNewBlock(): |
|
1033 | if self.__waitNewBlock(): | |
1034 | self.lastUTTime = self.basicHeaderObj.utc |
|
1034 | self.lastUTTime = self.basicHeaderObj.utc | |
1035 | return 1 |
|
1035 | return 1 | |
1036 | # if self.server is None: |
|
1036 | # if self.server is None: | |
1037 | if not(self.setNextFile()): |
|
1037 | if not(self.setNextFile()): | |
1038 | return 0 |
|
1038 | return 0 | |
1039 |
|
1039 | |||
1040 | deltaTime = self.basicHeaderObj.utc - self.lastUTTime |
|
1040 | deltaTime = self.basicHeaderObj.utc - self.lastUTTime | |
1041 | self.lastUTTime = self.basicHeaderObj.utc |
|
1041 | self.lastUTTime = self.basicHeaderObj.utc | |
1042 |
|
1042 | |||
1043 | self.flagDiscontinuousBlock = 0 |
|
1043 | self.flagDiscontinuousBlock = 0 | |
1044 |
|
1044 | |||
1045 | if deltaTime > self.maxTimeStep: |
|
1045 | if deltaTime > self.maxTimeStep: | |
1046 | self.flagDiscontinuousBlock = 1 |
|
1046 | self.flagDiscontinuousBlock = 1 | |
1047 |
|
1047 | |||
1048 | return 1 |
|
1048 | return 1 | |
1049 |
|
1049 | |||
1050 | def readNextBlock(self): |
|
1050 | def readNextBlock(self): | |
1051 |
|
1051 | |||
1052 | # Skip block out of startTime and endTime |
|
1052 | # Skip block out of startTime and endTime | |
1053 | while True: |
|
1053 | while True: | |
1054 | if not(self.__setNewBlock()): |
|
1054 | if not(self.__setNewBlock()): | |
1055 | self.dataOut.error = 'No more files to read' |
|
1055 | self.dataOut.error = 'No more files to read' | |
1056 | return 0 |
|
1056 | return 0 | |
1057 |
|
1057 | |||
1058 | if not(self.readBlock()): |
|
1058 | if not(self.readBlock()): | |
1059 | return 0 |
|
1059 | return 0 | |
1060 |
|
1060 | |||
1061 | self.getBasicHeader() |
|
1061 | self.getBasicHeader() | |
1062 | if (self.dataOut.datatime < datetime.datetime.combine(self.startDate, self.startTime)) or (self.dataOut.datatime > datetime.datetime.combine(self.endDate, self.endTime)): |
|
1062 | if (self.dataOut.datatime < datetime.datetime.combine(self.startDate, self.startTime)) or (self.dataOut.datatime > datetime.datetime.combine(self.endDate, self.endTime)): | |
1063 | print("[Reading] Block No. %d/%d -> %s [Skipping]" % (self.nReadBlocks, |
|
1063 | print("[Reading] Block No. %d/%d -> %s [Skipping]" % (self.nReadBlocks, | |
1064 | self.processingHeaderObj.dataBlocksPerFile, |
|
1064 | self.processingHeaderObj.dataBlocksPerFile, | |
1065 | self.dataOut.datatime.ctime())) |
|
1065 | self.dataOut.datatime.ctime())) | |
1066 | continue |
|
1066 | continue | |
1067 |
|
1067 | |||
1068 | break |
|
1068 | break | |
1069 |
|
1069 | |||
1070 | if self.verbose: |
|
1070 | if self.verbose: | |
1071 | print("[Reading] Block No. %d/%d -> %s" % (self.nReadBlocks, |
|
1071 | print("[Reading] Block No. %d/%d -> %s" % (self.nReadBlocks, | |
1072 | self.processingHeaderObj.dataBlocksPerFile, |
|
1072 | self.processingHeaderObj.dataBlocksPerFile, | |
1073 | self.dataOut.datatime.ctime())) |
|
1073 | self.dataOut.datatime.ctime())) | |
1074 | return 1 |
|
1074 | return 1 | |
1075 |
|
1075 | |||
1076 | def __readFirstHeader(self): |
|
1076 | def __readFirstHeader(self): | |
1077 |
|
1077 | |||
1078 | self.basicHeaderObj.read(self.fp) |
|
1078 | self.basicHeaderObj.read(self.fp) | |
1079 | self.systemHeaderObj.read(self.fp) |
|
1079 | self.systemHeaderObj.read(self.fp) | |
1080 | self.radarControllerHeaderObj.read(self.fp) |
|
1080 | self.radarControllerHeaderObj.read(self.fp) | |
1081 | self.processingHeaderObj.read(self.fp) |
|
1081 | self.processingHeaderObj.read(self.fp) | |
1082 |
|
1082 | |||
1083 | self.firstHeaderSize = self.basicHeaderObj.size |
|
1083 | self.firstHeaderSize = self.basicHeaderObj.size | |
1084 |
|
1084 | |||
1085 | datatype = int(numpy.log2((self.processingHeaderObj.processFlags & |
|
1085 | datatype = int(numpy.log2((self.processingHeaderObj.processFlags & | |
1086 | PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR)) |
|
1086 | PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR)) | |
1087 | if datatype == 0: |
|
1087 | if datatype == 0: | |
1088 | datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')]) |
|
1088 | datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')]) | |
1089 | elif datatype == 1: |
|
1089 | elif datatype == 1: | |
1090 | datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')]) |
|
1090 | datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')]) | |
1091 | elif datatype == 2: |
|
1091 | elif datatype == 2: | |
1092 | datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')]) |
|
1092 | datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')]) | |
1093 | elif datatype == 3: |
|
1093 | elif datatype == 3: | |
1094 | datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')]) |
|
1094 | datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')]) | |
1095 | elif datatype == 4: |
|
1095 | elif datatype == 4: | |
1096 | datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')]) |
|
1096 | datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')]) | |
1097 | elif datatype == 5: |
|
1097 | elif datatype == 5: | |
1098 | datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')]) |
|
1098 | datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')]) | |
1099 | else: |
|
1099 | else: | |
1100 | raise ValueError('Data type was not defined') |
|
1100 | raise ValueError('Data type was not defined') | |
1101 |
|
1101 | |||
1102 | self.dtype = datatype_str |
|
1102 | self.dtype = datatype_str | |
1103 | #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c |
|
1103 | #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c | |
1104 | self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \ |
|
1104 | self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \ | |
1105 | self.firstHeaderSize + self.basicHeaderSize * \ |
|
1105 | self.firstHeaderSize + self.basicHeaderSize * \ | |
1106 | (self.processingHeaderObj.dataBlocksPerFile - 1) |
|
1106 | (self.processingHeaderObj.dataBlocksPerFile - 1) | |
1107 | # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels) |
|
1107 | # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels) | |
1108 | # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels) |
|
1108 | # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels) | |
1109 | self.getBlockDimension() |
|
1109 | self.getBlockDimension() | |
1110 |
|
1110 | |||
1111 | def __verifyFile(self, filename, msgFlag=True): |
|
1111 | def __verifyFile(self, filename, msgFlag=True): | |
1112 |
|
1112 | |||
1113 | msg = None |
|
1113 | msg = None | |
1114 |
|
1114 | |||
1115 | try: |
|
1115 | try: | |
1116 | fp = open(filename, 'rb') |
|
1116 | fp = open(filename, 'rb') | |
1117 | except IOError: |
|
1117 | except IOError: | |
1118 |
|
1118 | |||
1119 | if msgFlag: |
|
1119 | if msgFlag: | |
1120 | print("[Reading] File %s can't be opened" % (filename)) |
|
1120 | print("[Reading] File %s can't be opened" % (filename)) | |
1121 |
|
1121 | |||
1122 | return False |
|
1122 | return False | |
1123 |
|
1123 | |||
1124 | currentPosition = fp.tell() |
|
1124 | currentPosition = fp.tell() | |
1125 | neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize |
|
1125 | neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize | |
1126 |
|
1126 | |||
1127 | if neededSize == 0: |
|
1127 | if neededSize == 0: | |
1128 | basicHeaderObj = BasicHeader(LOCALTIME) |
|
1128 | basicHeaderObj = BasicHeader(LOCALTIME) | |
1129 | systemHeaderObj = SystemHeader() |
|
1129 | systemHeaderObj = SystemHeader() | |
1130 | radarControllerHeaderObj = RadarControllerHeader() |
|
1130 | radarControllerHeaderObj = RadarControllerHeader() | |
1131 | processingHeaderObj = ProcessingHeader() |
|
1131 | processingHeaderObj = ProcessingHeader() | |
1132 |
|
1132 | |||
1133 | if not(basicHeaderObj.read(fp)): |
|
1133 | if not(basicHeaderObj.read(fp)): | |
1134 | fp.close() |
|
1134 | fp.close() | |
1135 | return False |
|
1135 | return False | |
1136 |
|
1136 | |||
1137 | if not(systemHeaderObj.read(fp)): |
|
1137 | if not(systemHeaderObj.read(fp)): | |
1138 | fp.close() |
|
1138 | fp.close() | |
1139 | return False |
|
1139 | return False | |
1140 |
|
1140 | |||
1141 | if not(radarControllerHeaderObj.read(fp)): |
|
1141 | if not(radarControllerHeaderObj.read(fp)): | |
1142 | fp.close() |
|
1142 | fp.close() | |
1143 | return False |
|
1143 | return False | |
1144 |
|
1144 | |||
1145 | if not(processingHeaderObj.read(fp)): |
|
1145 | if not(processingHeaderObj.read(fp)): | |
1146 | fp.close() |
|
1146 | fp.close() | |
1147 | return False |
|
1147 | return False | |
1148 |
|
1148 | |||
1149 | neededSize = processingHeaderObj.blockSize + basicHeaderObj.size |
|
1149 | neededSize = processingHeaderObj.blockSize + basicHeaderObj.size | |
1150 | else: |
|
1150 | else: | |
1151 | msg = "[Reading] Skipping the file %s due to it hasn't enough data" % filename |
|
1151 | msg = "[Reading] Skipping the file %s due to it hasn't enough data" % filename | |
1152 |
|
1152 | |||
1153 | fp.close() |
|
1153 | fp.close() | |
1154 |
|
1154 | |||
1155 | fileSize = os.path.getsize(filename) |
|
1155 | fileSize = os.path.getsize(filename) | |
1156 | currentSize = fileSize - currentPosition |
|
1156 | currentSize = fileSize - currentPosition | |
1157 |
|
1157 | |||
1158 | if currentSize < neededSize: |
|
1158 | if currentSize < neededSize: | |
1159 | if msgFlag and (msg != None): |
|
1159 | if msgFlag and (msg != None): | |
1160 | print(msg) |
|
1160 | print(msg) | |
1161 | return False |
|
1161 | return False | |
1162 |
|
1162 | |||
1163 | return True |
|
1163 | return True | |
1164 |
|
1164 | |||
1165 | def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False): |
|
1165 | def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False): | |
1166 |
|
1166 | |||
1167 | path_empty = True |
|
1167 | path_empty = True | |
1168 |
|
1168 | |||
1169 | dateList = [] |
|
1169 | dateList = [] | |
1170 | pathList = [] |
|
1170 | pathList = [] | |
1171 |
|
1171 | |||
1172 | multi_path = path.split(',') |
|
1172 | multi_path = path.split(',') | |
1173 |
|
1173 | |||
1174 | if not walk: |
|
1174 | if not walk: | |
1175 |
|
1175 | |||
1176 | for single_path in multi_path: |
|
1176 | for single_path in multi_path: | |
1177 |
|
1177 | |||
1178 | if not os.path.isdir(single_path): |
|
1178 | if not os.path.isdir(single_path): | |
1179 | continue |
|
1179 | continue | |
1180 |
|
1180 | |||
1181 | fileList = glob.glob1(single_path, "*" + ext) |
|
1181 | fileList = glob.glob1(single_path, "*" + ext) | |
1182 |
|
1182 | |||
1183 | if not fileList: |
|
1183 | if not fileList: | |
1184 | continue |
|
1184 | continue | |
1185 |
|
1185 | |||
1186 | path_empty = False |
|
1186 | path_empty = False | |
1187 |
|
1187 | |||
1188 | fileList.sort() |
|
1188 | fileList.sort() | |
1189 |
|
1189 | |||
1190 | for thisFile in fileList: |
|
1190 | for thisFile in fileList: | |
1191 |
|
1191 | |||
1192 | if not os.path.isfile(os.path.join(single_path, thisFile)): |
|
1192 | if not os.path.isfile(os.path.join(single_path, thisFile)): | |
1193 | continue |
|
1193 | continue | |
1194 |
|
1194 | |||
1195 | if not isRadarFile(thisFile): |
|
1195 | if not isRadarFile(thisFile): | |
1196 | continue |
|
1196 | continue | |
1197 |
|
1197 | |||
1198 | if not isFileInDateRange(thisFile, startDate, endDate): |
|
1198 | if not isFileInDateRange(thisFile, startDate, endDate): | |
1199 | continue |
|
1199 | continue | |
1200 |
|
1200 | |||
1201 | thisDate = getDateFromRadarFile(thisFile) |
|
1201 | thisDate = getDateFromRadarFile(thisFile) | |
1202 |
|
1202 | |||
1203 | if thisDate in dateList: |
|
1203 | if thisDate in dateList: | |
1204 | continue |
|
1204 | continue | |
1205 |
|
1205 | |||
1206 | dateList.append(thisDate) |
|
1206 | dateList.append(thisDate) | |
1207 | pathList.append(single_path) |
|
1207 | pathList.append(single_path) | |
1208 |
|
1208 | |||
1209 | else: |
|
1209 | else: | |
1210 | for single_path in multi_path: |
|
1210 | for single_path in multi_path: | |
1211 |
|
1211 | |||
1212 | if not os.path.isdir(single_path): |
|
1212 | if not os.path.isdir(single_path): | |
1213 | continue |
|
1213 | continue | |
1214 |
|
1214 | |||
1215 | dirList = [] |
|
1215 | dirList = [] | |
1216 |
|
1216 | |||
1217 | for thisPath in os.listdir(single_path): |
|
1217 | for thisPath in os.listdir(single_path): | |
1218 |
|
1218 | |||
1219 | if not os.path.isdir(os.path.join(single_path, thisPath)): |
|
1219 | if not os.path.isdir(os.path.join(single_path, thisPath)): | |
1220 | continue |
|
1220 | continue | |
1221 |
|
1221 | |||
1222 | if not isRadarFolder(thisPath): |
|
1222 | if not isRadarFolder(thisPath): | |
1223 | continue |
|
1223 | continue | |
1224 |
|
1224 | |||
1225 | if not isFolderInDateRange(thisPath, startDate, endDate): |
|
1225 | if not isFolderInDateRange(thisPath, startDate, endDate): | |
1226 | continue |
|
1226 | continue | |
1227 |
|
1227 | |||
1228 | dirList.append(thisPath) |
|
1228 | dirList.append(thisPath) | |
1229 |
|
1229 | |||
1230 | if not dirList: |
|
1230 | if not dirList: | |
1231 | continue |
|
1231 | continue | |
1232 |
|
1232 | |||
1233 | dirList.sort() |
|
1233 | dirList.sort() | |
1234 |
|
1234 | |||
1235 | for thisDir in dirList: |
|
1235 | for thisDir in dirList: | |
1236 |
|
1236 | |||
1237 | datapath = os.path.join(single_path, thisDir, expLabel) |
|
1237 | datapath = os.path.join(single_path, thisDir, expLabel) | |
1238 | fileList = glob.glob1(datapath, "*" + ext) |
|
1238 | fileList = glob.glob1(datapath, "*" + ext) | |
1239 |
|
1239 | |||
1240 | if not fileList: |
|
1240 | if not fileList: | |
1241 | continue |
|
1241 | continue | |
1242 |
|
1242 | |||
1243 | path_empty = False |
|
1243 | path_empty = False | |
1244 |
|
1244 | |||
1245 | thisDate = getDateFromRadarFolder(thisDir) |
|
1245 | thisDate = getDateFromRadarFolder(thisDir) | |
1246 |
|
1246 | |||
1247 | pathList.append(datapath) |
|
1247 | pathList.append(datapath) | |
1248 | dateList.append(thisDate) |
|
1248 | dateList.append(thisDate) | |
1249 |
|
1249 | |||
1250 | dateList.sort() |
|
1250 | dateList.sort() | |
1251 |
|
1251 | |||
1252 | if walk: |
|
1252 | if walk: | |
1253 | pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel) |
|
1253 | pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel) | |
1254 | else: |
|
1254 | else: | |
1255 | pattern_path = multi_path[0] |
|
1255 | pattern_path = multi_path[0] | |
1256 |
|
1256 | |||
1257 | if path_empty: |
|
1257 | if path_empty: | |
1258 | print("[Reading] No *%s files in %s for %s to %s" % (ext, pattern_path, startDate, endDate)) |
|
1258 | print("[Reading] No *%s files in %s for %s to %s" % (ext, pattern_path, startDate, endDate)) | |
1259 | else: |
|
1259 | else: | |
1260 | if not dateList: |
|
1260 | if not dateList: | |
1261 | print("[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" % (startDate, endDate, ext, path)) |
|
1261 | print("[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" % (startDate, endDate, ext, path)) | |
1262 |
|
1262 | |||
1263 | if include_path: |
|
1263 | if include_path: | |
1264 | return dateList, pathList |
|
1264 | return dateList, pathList | |
1265 |
|
1265 | |||
1266 | return dateList |
|
1266 | return dateList | |
1267 |
|
1267 | |||
1268 | def setup(self, |
|
1268 | def setup(self, | |
1269 | path=None, |
|
1269 | path=None, | |
1270 | startDate=None, |
|
1270 | startDate=None, | |
1271 | endDate=None, |
|
1271 | endDate=None, | |
1272 | startTime=datetime.time(0, 0, 0), |
|
1272 | startTime=datetime.time(0, 0, 0), | |
1273 | endTime=datetime.time(23, 59, 59), |
|
1273 | endTime=datetime.time(23, 59, 59), | |
1274 | set=None, |
|
1274 | set=None, | |
1275 | expLabel="", |
|
1275 | expLabel="", | |
1276 | ext=None, |
|
1276 | ext=None, | |
1277 | online=False, |
|
1277 | online=False, | |
1278 | delay=60, |
|
1278 | delay=60, | |
1279 | walk=True, |
|
1279 | walk=True, | |
1280 | getblock=False, |
|
1280 | getblock=False, | |
1281 | nTxs=1, |
|
1281 | nTxs=1, | |
1282 | realtime=False, |
|
1282 | realtime=False, | |
1283 | blocksize=None, |
|
1283 | blocksize=None, | |
1284 | blocktime=None, |
|
1284 | blocktime=None, | |
1285 | skip=None, |
|
1285 | skip=None, | |
1286 | cursor=None, |
|
1286 | cursor=None, | |
1287 | warnings=True, |
|
1287 | warnings=True, | |
1288 | verbose=True, |
|
1288 | verbose=True, | |
1289 | server=None, |
|
1289 | server=None, | |
1290 | format=None, |
|
1290 | format=None, | |
1291 | oneDDict=None, |
|
1291 | oneDDict=None, | |
1292 | twoDDict=None, |
|
1292 | twoDDict=None, | |
1293 |
ind |
|
1293 | independentParam=None): | |
1294 | if server is not None: |
|
1294 | if server is not None: | |
1295 | if 'tcp://' in server: |
|
1295 | if 'tcp://' in server: | |
1296 | address = server |
|
1296 | address = server | |
1297 | else: |
|
1297 | else: | |
1298 | address = 'ipc:///tmp/%s' % server |
|
1298 | address = 'ipc:///tmp/%s' % server | |
1299 | self.server = address |
|
1299 | self.server = address | |
1300 | self.context = zmq.Context() |
|
1300 | self.context = zmq.Context() | |
1301 | self.receiver = self.context.socket(zmq.PULL) |
|
1301 | self.receiver = self.context.socket(zmq.PULL) | |
1302 | self.receiver.connect(self.server) |
|
1302 | self.receiver.connect(self.server) | |
1303 | time.sleep(0.5) |
|
1303 | time.sleep(0.5) | |
1304 | print('[Starting] ReceiverData from {}'.format(self.server)) |
|
1304 | print('[Starting] ReceiverData from {}'.format(self.server)) | |
1305 | else: |
|
1305 | else: | |
1306 | self.server = None |
|
1306 | self.server = None | |
1307 | if path == None: |
|
1307 | if path == None: | |
1308 | raise ValueError("[Reading] The path is not valid") |
|
1308 | raise ValueError("[Reading] The path is not valid") | |
1309 |
|
1309 | |||
1310 | if ext == None: |
|
1310 | if ext == None: | |
1311 | ext = self.ext |
|
1311 | ext = self.ext | |
1312 |
|
1312 | |||
1313 | if online: |
|
1313 | if online: | |
1314 | print("[Reading] Searching files in online mode...") |
|
1314 | print("[Reading] Searching files in online mode...") | |
1315 |
|
1315 | |||
1316 | for nTries in range(self.nTries): |
|
1316 | for nTries in range(self.nTries): | |
1317 | fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine( |
|
1317 | fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine( | |
1318 | path=path, expLabel=expLabel, ext=ext, walk=walk, set=set) |
|
1318 | path=path, expLabel=expLabel, ext=ext, walk=walk, set=set) | |
1319 |
|
1319 | |||
1320 | if fullpath: |
|
1320 | if fullpath: | |
1321 | break |
|
1321 | break | |
1322 |
|
1322 | |||
1323 | print('[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries + 1)) |
|
1323 | print('[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries + 1)) | |
1324 | sleep(self.delay) |
|
1324 | sleep(self.delay) | |
1325 |
|
1325 | |||
1326 | if not(fullpath): |
|
1326 | if not(fullpath): | |
1327 | self.dataOut.error = 'There isn\'t any valid file in {}'.format(path) |
|
1327 | self.dataOut.error = 'There isn\'t any valid file in {}'.format(path) | |
1328 | return |
|
1328 | return | |
1329 |
|
1329 | |||
1330 | self.year = year |
|
1330 | self.year = year | |
1331 | self.doy = doy |
|
1331 | self.doy = doy | |
1332 | self.set = set - 1 |
|
1332 | self.set = set - 1 | |
1333 | self.path = path |
|
1333 | self.path = path | |
1334 | self.foldercounter = foldercounter |
|
1334 | self.foldercounter = foldercounter | |
1335 | last_set = None |
|
1335 | last_set = None | |
1336 | else: |
|
1336 | else: | |
1337 | print("[Reading] Searching files in offline mode ...") |
|
1337 | print("[Reading] Searching files in offline mode ...") | |
1338 | pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate, |
|
1338 | pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate, | |
1339 | startTime=startTime, endTime=endTime, |
|
1339 | startTime=startTime, endTime=endTime, | |
1340 | set=set, expLabel=expLabel, ext=ext, |
|
1340 | set=set, expLabel=expLabel, ext=ext, | |
1341 | walk=walk, cursor=cursor, |
|
1341 | walk=walk, cursor=cursor, | |
1342 | skip=skip) |
|
1342 | skip=skip) | |
1343 |
|
1343 | |||
1344 | if not(pathList): |
|
1344 | if not(pathList): | |
1345 | self.fileIndex = -1 |
|
1345 | self.fileIndex = -1 | |
1346 | self.pathList = [] |
|
1346 | self.pathList = [] | |
1347 | self.filenameList = [] |
|
1347 | self.filenameList = [] | |
1348 | return |
|
1348 | return | |
1349 |
|
1349 | |||
1350 | self.fileIndex = -1 |
|
1350 | self.fileIndex = -1 | |
1351 | self.pathList = pathList |
|
1351 | self.pathList = pathList | |
1352 | self.filenameList = filenameList |
|
1352 | self.filenameList = filenameList | |
1353 | file_name = os.path.basename(filenameList[-1]) |
|
1353 | file_name = os.path.basename(filenameList[-1]) | |
1354 | basename, ext = os.path.splitext(file_name) |
|
1354 | basename, ext = os.path.splitext(file_name) | |
1355 | last_set = int(basename[-3:]) |
|
1355 | last_set = int(basename[-3:]) | |
1356 |
|
1356 | |||
1357 | self.online = online |
|
1357 | self.online = online | |
1358 | self.realtime = realtime |
|
1358 | self.realtime = realtime | |
1359 | self.delay = delay |
|
1359 | self.delay = delay | |
1360 | ext = ext.lower() |
|
1360 | ext = ext.lower() | |
1361 | self.ext = ext |
|
1361 | self.ext = ext | |
1362 | self.getByBlock = getblock |
|
1362 | self.getByBlock = getblock | |
1363 | self.nTxs = nTxs |
|
1363 | self.nTxs = nTxs | |
1364 | self.startTime = startTime |
|
1364 | self.startTime = startTime | |
1365 | self.endTime = endTime |
|
1365 | self.endTime = endTime | |
1366 | self.endDate = endDate |
|
1366 | self.endDate = endDate | |
1367 | self.startDate = startDate |
|
1367 | self.startDate = startDate | |
1368 | # Added----------------- |
|
1368 | # Added----------------- | |
1369 | self.selBlocksize = blocksize |
|
1369 | self.selBlocksize = blocksize | |
1370 | self.selBlocktime = blocktime |
|
1370 | self.selBlocktime = blocktime | |
1371 |
|
1371 | |||
1372 | # Verbose----------- |
|
1372 | # Verbose----------- | |
1373 | self.verbose = verbose |
|
1373 | self.verbose = verbose | |
1374 | self.warnings = warnings |
|
1374 | self.warnings = warnings | |
1375 |
|
1375 | |||
1376 | if not(self.setNextFile()): |
|
1376 | if not(self.setNextFile()): | |
1377 | if (startDate != None) and (endDate != None): |
|
1377 | if (startDate != None) and (endDate != None): | |
1378 | print("[Reading] No files in range: %s - %s" % (datetime.datetime.combine(startDate, startTime).ctime(), datetime.datetime.combine(endDate, endTime).ctime())) |
|
1378 | print("[Reading] No files in range: %s - %s" % (datetime.datetime.combine(startDate, startTime).ctime(), datetime.datetime.combine(endDate, endTime).ctime())) | |
1379 | elif startDate != None: |
|
1379 | elif startDate != None: | |
1380 | print("[Reading] No files in range: %s" % (datetime.datetime.combine(startDate, startTime).ctime())) |
|
1380 | print("[Reading] No files in range: %s" % (datetime.datetime.combine(startDate, startTime).ctime())) | |
1381 | else: |
|
1381 | else: | |
1382 | print("[Reading] No files") |
|
1382 | print("[Reading] No files") | |
1383 |
|
1383 | |||
1384 | self.fileIndex = -1 |
|
1384 | self.fileIndex = -1 | |
1385 | self.pathList = [] |
|
1385 | self.pathList = [] | |
1386 | self.filenameList = [] |
|
1386 | self.filenameList = [] | |
1387 | return |
|
1387 | return | |
1388 |
|
1388 | |||
1389 | # self.getBasicHeader() |
|
1389 | # self.getBasicHeader() | |
1390 |
|
1390 | |||
1391 | if last_set != None: |
|
1391 | if last_set != None: | |
1392 | self.dataOut.last_block = last_set * \ |
|
1392 | self.dataOut.last_block = last_set * \ | |
1393 | self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock |
|
1393 | self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock | |
1394 | return |
|
1394 | return | |
1395 |
|
1395 | |||
1396 | def getBasicHeader(self): |
|
1396 | def getBasicHeader(self): | |
1397 |
|
1397 | |||
1398 | self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond / \ |
|
1398 | self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond / \ | |
1399 | 1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds |
|
1399 | 1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds | |
1400 |
|
1400 | |||
1401 | self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock |
|
1401 | self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock | |
1402 |
|
1402 | |||
1403 | self.dataOut.timeZone = self.basicHeaderObj.timeZone |
|
1403 | self.dataOut.timeZone = self.basicHeaderObj.timeZone | |
1404 |
|
1404 | |||
1405 | self.dataOut.dstFlag = self.basicHeaderObj.dstFlag |
|
1405 | self.dataOut.dstFlag = self.basicHeaderObj.dstFlag | |
1406 |
|
1406 | |||
1407 | self.dataOut.errorCount = self.basicHeaderObj.errorCount |
|
1407 | self.dataOut.errorCount = self.basicHeaderObj.errorCount | |
1408 |
|
1408 | |||
1409 | self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime |
|
1409 | self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime | |
1410 |
|
1410 | |||
1411 | self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs |
|
1411 | self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs | |
1412 |
|
1412 | |||
1413 | # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs |
|
1413 | # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs | |
1414 |
|
1414 | |||
1415 | def getFirstHeader(self): |
|
1415 | def getFirstHeader(self): | |
1416 |
|
1416 | |||
1417 | raise NotImplementedError |
|
1417 | raise NotImplementedError | |
1418 |
|
1418 | |||
1419 | def getData(self): |
|
1419 | def getData(self): | |
1420 |
|
1420 | |||
1421 | raise NotImplementedError |
|
1421 | raise NotImplementedError | |
1422 |
|
1422 | |||
1423 | def hasNotDataInBuffer(self): |
|
1423 | def hasNotDataInBuffer(self): | |
1424 |
|
1424 | |||
1425 | raise NotImplementedError |
|
1425 | raise NotImplementedError | |
1426 |
|
1426 | |||
1427 | def readBlock(self): |
|
1427 | def readBlock(self): | |
1428 |
|
1428 | |||
1429 | raise NotImplementedError |
|
1429 | raise NotImplementedError | |
1430 |
|
1430 | |||
1431 | def isEndProcess(self): |
|
1431 | def isEndProcess(self): | |
1432 |
|
1432 | |||
1433 | return self.flagNoMoreFiles |
|
1433 | return self.flagNoMoreFiles | |
1434 |
|
1434 | |||
1435 | def printReadBlocks(self): |
|
1435 | def printReadBlocks(self): | |
1436 |
|
1436 | |||
1437 | print("[Reading] Number of read blocks per file %04d" % self.nReadBlocks) |
|
1437 | print("[Reading] Number of read blocks per file %04d" % self.nReadBlocks) | |
1438 |
|
1438 | |||
1439 | def printTotalBlocks(self): |
|
1439 | def printTotalBlocks(self): | |
1440 |
|
1440 | |||
1441 | print("[Reading] Number of read blocks %04d" % self.nTotalBlocks) |
|
1441 | print("[Reading] Number of read blocks %04d" % self.nTotalBlocks) | |
1442 |
|
1442 | |||
1443 | def printNumberOfBlock(self): |
|
1443 | def printNumberOfBlock(self): | |
1444 | 'SPAM!' |
|
1444 | 'SPAM!' | |
1445 |
|
1445 | |||
1446 | # if self.flagIsNewBlock: |
|
1446 | # if self.flagIsNewBlock: | |
1447 | # print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks, |
|
1447 | # print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks, | |
1448 | # self.processingHeaderObj.dataBlocksPerFile, |
|
1448 | # self.processingHeaderObj.dataBlocksPerFile, | |
1449 | # self.dataOut.datatime.ctime()) |
|
1449 | # self.dataOut.datatime.ctime()) | |
1450 |
|
1450 | |||
1451 | def printInfo(self): |
|
1451 | def printInfo(self): | |
1452 |
|
1452 | |||
1453 | if self.__printInfo == False: |
|
1453 | if self.__printInfo == False: | |
1454 | return |
|
1454 | return | |
1455 |
|
1455 | |||
1456 | self.basicHeaderObj.printInfo() |
|
1456 | self.basicHeaderObj.printInfo() | |
1457 | self.systemHeaderObj.printInfo() |
|
1457 | self.systemHeaderObj.printInfo() | |
1458 | self.radarControllerHeaderObj.printInfo() |
|
1458 | self.radarControllerHeaderObj.printInfo() | |
1459 | self.processingHeaderObj.printInfo() |
|
1459 | self.processingHeaderObj.printInfo() | |
1460 |
|
1460 | |||
1461 | self.__printInfo = False |
|
1461 | self.__printInfo = False | |
1462 |
|
1462 | |||
1463 | def run(self, |
|
1463 | def run(self, | |
1464 | path=None, |
|
1464 | path=None, | |
1465 | startDate=None, |
|
1465 | startDate=None, | |
1466 | endDate=None, |
|
1466 | endDate=None, | |
1467 | startTime=datetime.time(0, 0, 0), |
|
1467 | startTime=datetime.time(0, 0, 0), | |
1468 | endTime=datetime.time(23, 59, 59), |
|
1468 | endTime=datetime.time(23, 59, 59), | |
1469 | set=None, |
|
1469 | set=None, | |
1470 | expLabel="", |
|
1470 | expLabel="", | |
1471 | ext=None, |
|
1471 | ext=None, | |
1472 | online=False, |
|
1472 | online=False, | |
1473 | delay=60, |
|
1473 | delay=60, | |
1474 | walk=True, |
|
1474 | walk=True, | |
1475 | getblock=False, |
|
1475 | getblock=False, | |
1476 | nTxs=1, |
|
1476 | nTxs=1, | |
1477 | realtime=False, |
|
1477 | realtime=False, | |
1478 | blocksize=None, |
|
1478 | blocksize=None, | |
1479 | blocktime=None, |
|
1479 | blocktime=None, | |
1480 | skip=None, |
|
1480 | skip=None, | |
1481 | cursor=None, |
|
1481 | cursor=None, | |
1482 | warnings=True, |
|
1482 | warnings=True, | |
1483 | server=None, |
|
1483 | server=None, | |
1484 | verbose=True, |
|
1484 | verbose=True, | |
1485 | format=None, |
|
1485 | format=None, | |
1486 | oneDDict=None, |
|
1486 | oneDDict=None, | |
1487 | twoDDict=None, |
|
1487 | twoDDict=None, | |
1488 |
ind |
|
1488 | independentParam=None, **kwargs): | |
1489 |
|
1489 | |||
1490 | if not(self.isConfig): |
|
1490 | if not(self.isConfig): | |
1491 | self.setup(path=path, |
|
1491 | self.setup(path=path, | |
1492 | startDate=startDate, |
|
1492 | startDate=startDate, | |
1493 | endDate=endDate, |
|
1493 | endDate=endDate, | |
1494 | startTime=startTime, |
|
1494 | startTime=startTime, | |
1495 | endTime=endTime, |
|
1495 | endTime=endTime, | |
1496 | set=set, |
|
1496 | set=set, | |
1497 | expLabel=expLabel, |
|
1497 | expLabel=expLabel, | |
1498 | ext=ext, |
|
1498 | ext=ext, | |
1499 | online=online, |
|
1499 | online=online, | |
1500 | delay=delay, |
|
1500 | delay=delay, | |
1501 | walk=walk, |
|
1501 | walk=walk, | |
1502 | getblock=getblock, |
|
1502 | getblock=getblock, | |
1503 | nTxs=nTxs, |
|
1503 | nTxs=nTxs, | |
1504 | realtime=realtime, |
|
1504 | realtime=realtime, | |
1505 | blocksize=blocksize, |
|
1505 | blocksize=blocksize, | |
1506 | blocktime=blocktime, |
|
1506 | blocktime=blocktime, | |
1507 | skip=skip, |
|
1507 | skip=skip, | |
1508 | cursor=cursor, |
|
1508 | cursor=cursor, | |
1509 | warnings=warnings, |
|
1509 | warnings=warnings, | |
1510 | server=server, |
|
1510 | server=server, | |
1511 | verbose=verbose, |
|
1511 | verbose=verbose, | |
1512 | format=format, |
|
1512 | format=format, | |
1513 | oneDDict=oneDDict, |
|
1513 | oneDDict=oneDDict, | |
1514 | twoDDict=twoDDict, |
|
1514 | twoDDict=twoDDict, | |
1515 |
ind |
|
1515 | independentParam=independentParam) | |
1516 | self.isConfig = True |
|
1516 | self.isConfig = True | |
1517 | if server is None: |
|
1517 | if server is None: | |
1518 | self.getData() |
|
1518 | self.getData() | |
1519 | else: |
|
1519 | else: | |
1520 | self.getFromServer() |
|
1520 | self.getFromServer() | |
1521 |
|
1521 | |||
1522 |
|
1522 | |||
1523 | class JRODataWriter(JRODataIO): |
|
1523 | class JRODataWriter(JRODataIO): | |
1524 |
|
1524 | |||
1525 | """ |
|
1525 | """ | |
1526 | Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura |
|
1526 | Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura | |
1527 | de los datos siempre se realiza por bloques. |
|
1527 | de los datos siempre se realiza por bloques. | |
1528 | """ |
|
1528 | """ | |
1529 |
|
1529 | |||
1530 | blockIndex = 0 |
|
1530 | blockIndex = 0 | |
1531 |
|
1531 | |||
1532 | path = None |
|
1532 | path = None | |
1533 |
|
1533 | |||
1534 | setFile = None |
|
1534 | setFile = None | |
1535 |
|
1535 | |||
1536 | profilesPerBlock = None |
|
1536 | profilesPerBlock = None | |
1537 |
|
1537 | |||
1538 | blocksPerFile = None |
|
1538 | blocksPerFile = None | |
1539 |
|
1539 | |||
1540 | nWriteBlocks = 0 |
|
1540 | nWriteBlocks = 0 | |
1541 |
|
1541 | |||
1542 | fileDate = None |
|
1542 | fileDate = None | |
1543 |
|
1543 | |||
1544 | def __init__(self, dataOut=None): |
|
1544 | def __init__(self, dataOut=None): | |
1545 | raise NotImplementedError |
|
1545 | raise NotImplementedError | |
1546 |
|
1546 | |||
1547 | def hasAllDataInBuffer(self): |
|
1547 | def hasAllDataInBuffer(self): | |
1548 | raise NotImplementedError |
|
1548 | raise NotImplementedError | |
1549 |
|
1549 | |||
1550 | def setBlockDimension(self): |
|
1550 | def setBlockDimension(self): | |
1551 | raise NotImplementedError |
|
1551 | raise NotImplementedError | |
1552 |
|
1552 | |||
1553 | def writeBlock(self): |
|
1553 | def writeBlock(self): | |
1554 | raise NotImplementedError |
|
1554 | raise NotImplementedError | |
1555 |
|
1555 | |||
1556 | def putData(self): |
|
1556 | def putData(self): | |
1557 | raise NotImplementedError |
|
1557 | raise NotImplementedError | |
1558 |
|
1558 | |||
1559 | def getProcessFlags(self): |
|
1559 | def getProcessFlags(self): | |
1560 |
|
1560 | |||
1561 | processFlags = 0 |
|
1561 | processFlags = 0 | |
1562 |
|
1562 | |||
1563 | dtype_index = get_dtype_index(self.dtype) |
|
1563 | dtype_index = get_dtype_index(self.dtype) | |
1564 | procflag_dtype = get_procflag_dtype(dtype_index) |
|
1564 | procflag_dtype = get_procflag_dtype(dtype_index) | |
1565 |
|
1565 | |||
1566 | processFlags += procflag_dtype |
|
1566 | processFlags += procflag_dtype | |
1567 |
|
1567 | |||
1568 | if self.dataOut.flagDecodeData: |
|
1568 | if self.dataOut.flagDecodeData: | |
1569 | processFlags += PROCFLAG.DECODE_DATA |
|
1569 | processFlags += PROCFLAG.DECODE_DATA | |
1570 |
|
1570 | |||
1571 | if self.dataOut.flagDeflipData: |
|
1571 | if self.dataOut.flagDeflipData: | |
1572 | processFlags += PROCFLAG.DEFLIP_DATA |
|
1572 | processFlags += PROCFLAG.DEFLIP_DATA | |
1573 |
|
1573 | |||
1574 | if self.dataOut.code is not None: |
|
1574 | if self.dataOut.code is not None: | |
1575 | processFlags += PROCFLAG.DEFINE_PROCESS_CODE |
|
1575 | processFlags += PROCFLAG.DEFINE_PROCESS_CODE | |
1576 |
|
1576 | |||
1577 | if self.dataOut.nCohInt > 1: |
|
1577 | if self.dataOut.nCohInt > 1: | |
1578 | processFlags += PROCFLAG.COHERENT_INTEGRATION |
|
1578 | processFlags += PROCFLAG.COHERENT_INTEGRATION | |
1579 |
|
1579 | |||
1580 | if self.dataOut.type == "Spectra": |
|
1580 | if self.dataOut.type == "Spectra": | |
1581 | if self.dataOut.nIncohInt > 1: |
|
1581 | if self.dataOut.nIncohInt > 1: | |
1582 | processFlags += PROCFLAG.INCOHERENT_INTEGRATION |
|
1582 | processFlags += PROCFLAG.INCOHERENT_INTEGRATION | |
1583 |
|
1583 | |||
1584 | if self.dataOut.data_dc is not None: |
|
1584 | if self.dataOut.data_dc is not None: | |
1585 | processFlags += PROCFLAG.SAVE_CHANNELS_DC |
|
1585 | processFlags += PROCFLAG.SAVE_CHANNELS_DC | |
1586 |
|
1586 | |||
1587 | if self.dataOut.flagShiftFFT: |
|
1587 | if self.dataOut.flagShiftFFT: | |
1588 | processFlags += PROCFLAG.SHIFT_FFT_DATA |
|
1588 | processFlags += PROCFLAG.SHIFT_FFT_DATA | |
1589 |
|
1589 | |||
1590 | return processFlags |
|
1590 | return processFlags | |
1591 |
|
1591 | |||
1592 | def setBasicHeader(self): |
|
1592 | def setBasicHeader(self): | |
1593 |
|
1593 | |||
1594 | self.basicHeaderObj.size = self.basicHeaderSize # bytes |
|
1594 | self.basicHeaderObj.size = self.basicHeaderSize # bytes | |
1595 | self.basicHeaderObj.version = self.versionFile |
|
1595 | self.basicHeaderObj.version = self.versionFile | |
1596 | self.basicHeaderObj.dataBlock = self.nTotalBlocks |
|
1596 | self.basicHeaderObj.dataBlock = self.nTotalBlocks | |
1597 |
|
1597 | |||
1598 | utc = numpy.floor(self.dataOut.utctime) |
|
1598 | utc = numpy.floor(self.dataOut.utctime) | |
1599 | milisecond = (self.dataOut.utctime - utc) * 1000.0 |
|
1599 | milisecond = (self.dataOut.utctime - utc) * 1000.0 | |
1600 |
|
1600 | |||
1601 | self.basicHeaderObj.utc = utc |
|
1601 | self.basicHeaderObj.utc = utc | |
1602 | self.basicHeaderObj.miliSecond = milisecond |
|
1602 | self.basicHeaderObj.miliSecond = milisecond | |
1603 | self.basicHeaderObj.timeZone = self.dataOut.timeZone |
|
1603 | self.basicHeaderObj.timeZone = self.dataOut.timeZone | |
1604 | self.basicHeaderObj.dstFlag = self.dataOut.dstFlag |
|
1604 | self.basicHeaderObj.dstFlag = self.dataOut.dstFlag | |
1605 | self.basicHeaderObj.errorCount = self.dataOut.errorCount |
|
1605 | self.basicHeaderObj.errorCount = self.dataOut.errorCount | |
1606 |
|
1606 | |||
1607 | def setFirstHeader(self): |
|
1607 | def setFirstHeader(self): | |
1608 | """ |
|
1608 | """ | |
1609 | Obtiene una copia del First Header |
|
1609 | Obtiene una copia del First Header | |
1610 |
|
1610 | |||
1611 | Affected: |
|
1611 | Affected: | |
1612 |
|
1612 | |||
1613 | self.basicHeaderObj |
|
1613 | self.basicHeaderObj | |
1614 | self.systemHeaderObj |
|
1614 | self.systemHeaderObj | |
1615 | self.radarControllerHeaderObj |
|
1615 | self.radarControllerHeaderObj | |
1616 | self.processingHeaderObj self. |
|
1616 | self.processingHeaderObj self. | |
1617 |
|
1617 | |||
1618 | Return: |
|
1618 | Return: | |
1619 | None |
|
1619 | None | |
1620 | """ |
|
1620 | """ | |
1621 |
|
1621 | |||
1622 | raise NotImplementedError |
|
1622 | raise NotImplementedError | |
1623 |
|
1623 | |||
1624 | def __writeFirstHeader(self): |
|
1624 | def __writeFirstHeader(self): | |
1625 | """ |
|
1625 | """ | |
1626 | Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader) |
|
1626 | Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader) | |
1627 |
|
1627 | |||
1628 | Affected: |
|
1628 | Affected: | |
1629 | __dataType |
|
1629 | __dataType | |
1630 |
|
1630 | |||
1631 | Return: |
|
1631 | Return: | |
1632 | None |
|
1632 | None | |
1633 | """ |
|
1633 | """ | |
1634 |
|
1634 | |||
1635 | # CALCULAR PARAMETROS |
|
1635 | # CALCULAR PARAMETROS | |
1636 |
|
1636 | |||
1637 | sizeLongHeader = self.systemHeaderObj.size + \ |
|
1637 | sizeLongHeader = self.systemHeaderObj.size + \ | |
1638 | self.radarControllerHeaderObj.size + self.processingHeaderObj.size |
|
1638 | self.radarControllerHeaderObj.size + self.processingHeaderObj.size | |
1639 | self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader |
|
1639 | self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader | |
1640 |
|
1640 | |||
1641 | self.basicHeaderObj.write(self.fp) |
|
1641 | self.basicHeaderObj.write(self.fp) | |
1642 | self.systemHeaderObj.write(self.fp) |
|
1642 | self.systemHeaderObj.write(self.fp) | |
1643 | self.radarControllerHeaderObj.write(self.fp) |
|
1643 | self.radarControllerHeaderObj.write(self.fp) | |
1644 | self.processingHeaderObj.write(self.fp) |
|
1644 | self.processingHeaderObj.write(self.fp) | |
1645 |
|
1645 | |||
1646 | def __setNewBlock(self): |
|
1646 | def __setNewBlock(self): | |
1647 | """ |
|
1647 | """ | |
1648 | Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header |
|
1648 | Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header | |
1649 |
|
1649 | |||
1650 | Return: |
|
1650 | Return: | |
1651 | 0 : si no pudo escribir nada |
|
1651 | 0 : si no pudo escribir nada | |
1652 | 1 : Si escribio el Basic el First Header |
|
1652 | 1 : Si escribio el Basic el First Header | |
1653 | """ |
|
1653 | """ | |
1654 | if self.fp == None: |
|
1654 | if self.fp == None: | |
1655 | self.setNextFile() |
|
1655 | self.setNextFile() | |
1656 |
|
1656 | |||
1657 | if self.flagIsNewFile: |
|
1657 | if self.flagIsNewFile: | |
1658 | return 1 |
|
1658 | return 1 | |
1659 |
|
1659 | |||
1660 | if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile: |
|
1660 | if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile: | |
1661 | self.basicHeaderObj.write(self.fp) |
|
1661 | self.basicHeaderObj.write(self.fp) | |
1662 | return 1 |
|
1662 | return 1 | |
1663 |
|
1663 | |||
1664 | if not(self.setNextFile()): |
|
1664 | if not(self.setNextFile()): | |
1665 | return 0 |
|
1665 | return 0 | |
1666 |
|
1666 | |||
1667 | return 1 |
|
1667 | return 1 | |
1668 |
|
1668 | |||
1669 | def writeNextBlock(self): |
|
1669 | def writeNextBlock(self): | |
1670 | """ |
|
1670 | """ | |
1671 | Selecciona el bloque siguiente de datos y los escribe en un file |
|
1671 | Selecciona el bloque siguiente de datos y los escribe en un file | |
1672 |
|
1672 | |||
1673 | Return: |
|
1673 | Return: | |
1674 | 0 : Si no hizo pudo escribir el bloque de datos |
|
1674 | 0 : Si no hizo pudo escribir el bloque de datos | |
1675 | 1 : Si no pudo escribir el bloque de datos |
|
1675 | 1 : Si no pudo escribir el bloque de datos | |
1676 | """ |
|
1676 | """ | |
1677 | if not(self.__setNewBlock()): |
|
1677 | if not(self.__setNewBlock()): | |
1678 | return 0 |
|
1678 | return 0 | |
1679 |
|
1679 | |||
1680 | self.writeBlock() |
|
1680 | self.writeBlock() | |
1681 |
|
1681 | |||
1682 | print("[Writing] Block No. %d/%d" % (self.blockIndex, |
|
1682 | print("[Writing] Block No. %d/%d" % (self.blockIndex, | |
1683 | self.processingHeaderObj.dataBlocksPerFile)) |
|
1683 | self.processingHeaderObj.dataBlocksPerFile)) | |
1684 |
|
1684 | |||
1685 | return 1 |
|
1685 | return 1 | |
1686 |
|
1686 | |||
1687 | def setNextFile(self): |
|
1687 | def setNextFile(self): | |
1688 | """ |
|
1688 | """ | |
1689 | Determina el siguiente file que sera escrito |
|
1689 | Determina el siguiente file que sera escrito | |
1690 |
|
1690 | |||
1691 | Affected: |
|
1691 | Affected: | |
1692 | self.filename |
|
1692 | self.filename | |
1693 | self.subfolder |
|
1693 | self.subfolder | |
1694 | self.fp |
|
1694 | self.fp | |
1695 | self.setFile |
|
1695 | self.setFile | |
1696 | self.flagIsNewFile |
|
1696 | self.flagIsNewFile | |
1697 |
|
1697 | |||
1698 | Return: |
|
1698 | Return: | |
1699 | 0 : Si el archivo no puede ser escrito |
|
1699 | 0 : Si el archivo no puede ser escrito | |
1700 | 1 : Si el archivo esta listo para ser escrito |
|
1700 | 1 : Si el archivo esta listo para ser escrito | |
1701 | """ |
|
1701 | """ | |
1702 | ext = self.ext |
|
1702 | ext = self.ext | |
1703 | path = self.path |
|
1703 | path = self.path | |
1704 |
|
1704 | |||
1705 | if self.fp != None: |
|
1705 | if self.fp != None: | |
1706 | self.fp.close() |
|
1706 | self.fp.close() | |
1707 |
|
1707 | |||
1708 | timeTuple = time.localtime(self.dataOut.utctime) |
|
1708 | timeTuple = time.localtime(self.dataOut.utctime) | |
1709 | subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year, timeTuple.tm_yday) |
|
1709 | subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year, timeTuple.tm_yday) | |
1710 |
|
1710 | |||
1711 | fullpath = os.path.join(path, subfolder) |
|
1711 | fullpath = os.path.join(path, subfolder) | |
1712 | setFile = self.setFile |
|
1712 | setFile = self.setFile | |
1713 |
|
1713 | |||
1714 | if not(os.path.exists(fullpath)): |
|
1714 | if not(os.path.exists(fullpath)): | |
1715 | os.mkdir(fullpath) |
|
1715 | os.mkdir(fullpath) | |
1716 | setFile = -1 # inicializo mi contador de seteo |
|
1716 | setFile = -1 # inicializo mi contador de seteo | |
1717 | else: |
|
1717 | else: | |
1718 | filesList = os.listdir(fullpath) |
|
1718 | filesList = os.listdir(fullpath) | |
1719 | if len(filesList) > 0: |
|
1719 | if len(filesList) > 0: | |
1720 | filesList = sorted(filesList, key=str.lower) |
|
1720 | filesList = sorted(filesList, key=str.lower) | |
1721 | filen = filesList[-1] |
|
1721 | filen = filesList[-1] | |
1722 | # el filename debera tener el siguiente formato |
|
1722 | # el filename debera tener el siguiente formato | |
1723 | # 0 1234 567 89A BCDE (hex) |
|
1723 | # 0 1234 567 89A BCDE (hex) | |
1724 | # x YYYY DDD SSS .ext |
|
1724 | # x YYYY DDD SSS .ext | |
1725 | if isNumber(filen[8:11]): |
|
1725 | if isNumber(filen[8:11]): | |
1726 | # inicializo mi contador de seteo al seteo del ultimo file |
|
1726 | # inicializo mi contador de seteo al seteo del ultimo file | |
1727 | setFile = int(filen[8:11]) |
|
1727 | setFile = int(filen[8:11]) | |
1728 | else: |
|
1728 | else: | |
1729 | setFile = -1 |
|
1729 | setFile = -1 | |
1730 | else: |
|
1730 | else: | |
1731 | setFile = -1 # inicializo mi contador de seteo |
|
1731 | setFile = -1 # inicializo mi contador de seteo | |
1732 |
|
1732 | |||
1733 | setFile += 1 |
|
1733 | setFile += 1 | |
1734 |
|
1734 | |||
1735 | # If this is a new day it resets some values |
|
1735 | # If this is a new day it resets some values | |
1736 | if self.dataOut.datatime.date() > self.fileDate: |
|
1736 | if self.dataOut.datatime.date() > self.fileDate: | |
1737 | setFile = 0 |
|
1737 | setFile = 0 | |
1738 | self.nTotalBlocks = 0 |
|
1738 | self.nTotalBlocks = 0 | |
1739 |
|
1739 | |||
1740 | filen = '{}{:04d}{:03d}{:03d}{}'.format( |
|
1740 | filen = '{}{:04d}{:03d}{:03d}{}'.format( | |
1741 | self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext) |
|
1741 | self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext) | |
1742 |
|
1742 | |||
1743 | filename = os.path.join(path, subfolder, filen) |
|
1743 | filename = os.path.join(path, subfolder, filen) | |
1744 |
|
1744 | |||
1745 | fp = open(filename, 'wb') |
|
1745 | fp = open(filename, 'wb') | |
1746 |
|
1746 | |||
1747 | self.blockIndex = 0 |
|
1747 | self.blockIndex = 0 | |
1748 |
|
1748 | |||
1749 | # guardando atributos |
|
1749 | # guardando atributos | |
1750 | self.filename = filename |
|
1750 | self.filename = filename | |
1751 | self.subfolder = subfolder |
|
1751 | self.subfolder = subfolder | |
1752 | self.fp = fp |
|
1752 | self.fp = fp | |
1753 | self.setFile = setFile |
|
1753 | self.setFile = setFile | |
1754 | self.flagIsNewFile = 1 |
|
1754 | self.flagIsNewFile = 1 | |
1755 | self.fileDate = self.dataOut.datatime.date() |
|
1755 | self.fileDate = self.dataOut.datatime.date() | |
1756 |
|
1756 | |||
1757 | self.setFirstHeader() |
|
1757 | self.setFirstHeader() | |
1758 |
|
1758 | |||
1759 | print('[Writing] Opening file: %s' % self.filename) |
|
1759 | print('[Writing] Opening file: %s' % self.filename) | |
1760 |
|
1760 | |||
1761 | self.__writeFirstHeader() |
|
1761 | self.__writeFirstHeader() | |
1762 |
|
1762 | |||
1763 | return 1 |
|
1763 | return 1 | |
1764 |
|
1764 | |||
1765 | def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4): |
|
1765 | def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4): | |
1766 | """ |
|
1766 | """ | |
1767 | Setea el tipo de formato en la cual sera guardada la data y escribe el First Header |
|
1767 | Setea el tipo de formato en la cual sera guardada la data y escribe el First Header | |
1768 |
|
1768 | |||
1769 | Inputs: |
|
1769 | Inputs: | |
1770 | path : directory where data will be saved |
|
1770 | path : directory where data will be saved | |
1771 | profilesPerBlock : number of profiles per block |
|
1771 | profilesPerBlock : number of profiles per block | |
1772 | set : initial file set |
|
1772 | set : initial file set | |
1773 | datatype : An integer number that defines data type: |
|
1773 | datatype : An integer number that defines data type: | |
1774 | 0 : int8 (1 byte) |
|
1774 | 0 : int8 (1 byte) | |
1775 | 1 : int16 (2 bytes) |
|
1775 | 1 : int16 (2 bytes) | |
1776 | 2 : int32 (4 bytes) |
|
1776 | 2 : int32 (4 bytes) | |
1777 | 3 : int64 (8 bytes) |
|
1777 | 3 : int64 (8 bytes) | |
1778 | 4 : float32 (4 bytes) |
|
1778 | 4 : float32 (4 bytes) | |
1779 | 5 : double64 (8 bytes) |
|
1779 | 5 : double64 (8 bytes) | |
1780 |
|
1780 | |||
1781 | Return: |
|
1781 | Return: | |
1782 | 0 : Si no realizo un buen seteo |
|
1782 | 0 : Si no realizo un buen seteo | |
1783 | 1 : Si realizo un buen seteo |
|
1783 | 1 : Si realizo un buen seteo | |
1784 | """ |
|
1784 | """ | |
1785 |
|
1785 | |||
1786 | if ext == None: |
|
1786 | if ext == None: | |
1787 | ext = self.ext |
|
1787 | ext = self.ext | |
1788 |
|
1788 | |||
1789 | self.ext = ext.lower() |
|
1789 | self.ext = ext.lower() | |
1790 |
|
1790 | |||
1791 | self.path = path |
|
1791 | self.path = path | |
1792 |
|
1792 | |||
1793 | if set is None: |
|
1793 | if set is None: | |
1794 | self.setFile = -1 |
|
1794 | self.setFile = -1 | |
1795 | else: |
|
1795 | else: | |
1796 | self.setFile = set - 1 |
|
1796 | self.setFile = set - 1 | |
1797 |
|
1797 | |||
1798 | self.blocksPerFile = blocksPerFile |
|
1798 | self.blocksPerFile = blocksPerFile | |
1799 |
|
1799 | |||
1800 | self.profilesPerBlock = profilesPerBlock |
|
1800 | self.profilesPerBlock = profilesPerBlock | |
1801 |
|
1801 | |||
1802 | self.dataOut = dataOut |
|
1802 | self.dataOut = dataOut | |
1803 | self.fileDate = self.dataOut.datatime.date() |
|
1803 | self.fileDate = self.dataOut.datatime.date() | |
1804 | # By default |
|
1804 | # By default | |
1805 | self.dtype = self.dataOut.dtype |
|
1805 | self.dtype = self.dataOut.dtype | |
1806 |
|
1806 | |||
1807 | if datatype is not None: |
|
1807 | if datatype is not None: | |
1808 | self.dtype = get_numpy_dtype(datatype) |
|
1808 | self.dtype = get_numpy_dtype(datatype) | |
1809 |
|
1809 | |||
1810 | if not(self.setNextFile()): |
|
1810 | if not(self.setNextFile()): | |
1811 | print("[Writing] There isn't a next file") |
|
1811 | print("[Writing] There isn't a next file") | |
1812 | return 0 |
|
1812 | return 0 | |
1813 |
|
1813 | |||
1814 | self.setBlockDimension() |
|
1814 | self.setBlockDimension() | |
1815 |
|
1815 | |||
1816 | return 1 |
|
1816 | return 1 | |
1817 |
|
1817 | |||
1818 | def run(self, dataOut, path, blocksPerFile=100, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs): |
|
1818 | def run(self, dataOut, path, blocksPerFile=100, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs): | |
1819 |
|
1819 | |||
1820 | if not(self.isConfig): |
|
1820 | if not(self.isConfig): | |
1821 |
|
1821 | |||
1822 | self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock, |
|
1822 | self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock, | |
1823 | set=set, ext=ext, datatype=datatype, **kwargs) |
|
1823 | set=set, ext=ext, datatype=datatype, **kwargs) | |
1824 | self.isConfig = True |
|
1824 | self.isConfig = True | |
1825 |
|
1825 | |||
1826 | self.dataOut = dataOut |
|
1826 | self.dataOut = dataOut | |
1827 | self.putData() |
|
1827 | self.putData() | |
1828 | return self.dataOut No newline at end of file |
|
1828 | return self.dataOut |
@@ -1,645 +1,637 | |||||
1 | ''' |
|
1 | ''' | |
2 | Created on Aug 1, 2017 |
|
2 | Created on Aug 1, 2017 | |
3 |
|
3 | |||
4 | @author: Juan C. Espinoza |
|
4 | @author: Juan C. Espinoza | |
5 | ''' |
|
5 | ''' | |
6 |
|
6 | |||
7 | import os |
|
7 | import os | |
8 | import sys |
|
8 | import sys | |
9 | import time |
|
9 | import time | |
10 | import json |
|
10 | import json | |
11 | import glob |
|
11 | import glob | |
12 | import datetime |
|
12 | import datetime | |
13 |
|
13 | |||
14 | import numpy |
|
14 | import numpy | |
15 | import h5py |
|
15 | import h5py | |
16 | from schainpy.model.io.jroIO_base import LOCALTIME, JRODataReader, JRODataWriter |
|
16 | from schainpy.model.io.jroIO_base import LOCALTIME, JRODataReader, JRODataWriter | |
17 | from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator |
|
17 | from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator | |
18 | from schainpy.model.data.jrodata import Parameters |
|
18 | from schainpy.model.data.jrodata import Parameters | |
19 | from schainpy.utils import log |
|
19 | from schainpy.utils import log | |
20 |
|
20 | |||
21 | try: |
|
21 | try: | |
22 | import madrigal.cedar |
|
22 | import madrigal.cedar | |
23 | except: |
|
23 | except: | |
24 | log.warning( |
|
24 | log.warning( | |
25 | 'You should install "madrigal library" module if you want to read/write Madrigal data' |
|
25 | 'You should install "madrigal library" module if you want to read/write Madrigal data' | |
26 | ) |
|
26 | ) | |
27 |
|
27 | |||
|
28 | try: | |||
|
29 | basestring | |||
|
30 | except: | |||
|
31 | basestring = str | |||
|
32 | ||||
28 | DEF_CATALOG = { |
|
33 | DEF_CATALOG = { | |
29 | 'principleInvestigator': 'Marco Milla', |
|
34 | 'principleInvestigator': 'Marco Milla', | |
30 | 'expPurpose': '', |
|
35 | 'expPurpose': '', | |
31 | 'cycleTime': '', |
|
36 | 'cycleTime': '', | |
32 | 'correlativeExp': '', |
|
37 | 'correlativeExp': '', | |
33 | 'sciRemarks': '', |
|
38 | 'sciRemarks': '', | |
34 | 'instRemarks': '' |
|
39 | 'instRemarks': '' | |
35 | } |
|
40 | } | |
36 |
|
41 | |||
37 | DEF_HEADER = { |
|
42 | DEF_HEADER = { | |
38 | 'kindatDesc': '', |
|
43 | 'kindatDesc': '', | |
39 | 'analyst': 'Jicamarca User', |
|
44 | 'analyst': 'Jicamarca User', | |
40 | 'comments': '', |
|
45 | 'comments': '', | |
41 | 'history': '' |
|
46 | 'history': '' | |
42 | } |
|
47 | } | |
43 |
|
48 | |||
44 | MNEMONICS = { |
|
49 | MNEMONICS = { | |
45 | 10: 'jro', |
|
50 | 10: 'jro', | |
46 | 11: 'jbr', |
|
51 | 11: 'jbr', | |
47 | 840: 'jul', |
|
52 | 840: 'jul', | |
48 | 13: 'jas', |
|
53 | 13: 'jas', | |
49 | 1000: 'pbr', |
|
54 | 1000: 'pbr', | |
50 | 1001: 'hbr', |
|
55 | 1001: 'hbr', | |
51 | 1002: 'obr', |
|
56 | 1002: 'obr', | |
52 | 400: 'clr' |
|
57 | 400: 'clr' | |
53 |
|
58 | |||
54 | } |
|
59 | } | |
55 |
|
60 | |||
56 | UT1970 = datetime.datetime(1970, 1, 1) - datetime.timedelta(seconds=time.timezone) |
|
61 | UT1970 = datetime.datetime(1970, 1, 1) - datetime.timedelta(seconds=time.timezone) | |
57 |
|
62 | |||
58 | def load_json(obj): |
|
63 | def load_json(obj): | |
59 | ''' |
|
64 | ''' | |
60 | Parse json as string instead of unicode |
|
65 | Parse json as string instead of unicode | |
61 | ''' |
|
66 | ''' | |
62 |
|
67 | |||
63 | if isinstance(obj, str): |
|
68 | if isinstance(obj, str): | |
64 | iterable = json.loads(obj) |
|
69 | iterable = json.loads(obj) | |
65 | else: |
|
70 | else: | |
66 | iterable = obj |
|
71 | iterable = obj | |
67 |
|
72 | |||
68 | if isinstance(iterable, dict): |
|
73 | if isinstance(iterable, dict): | |
69 |
return {str(k): load_json(v) if isinstance(v, dict) else str(v) if isinstance(v, |
|
74 | return {str(k): load_json(v) if isinstance(v, dict) else str(v) if isinstance(v, basestring) else v | |
70 | for k, v in list(iterable.items())} |
|
75 | for k, v in list(iterable.items())} | |
71 | elif isinstance(iterable, (list, tuple)): |
|
76 | elif isinstance(iterable, (list, tuple)): | |
72 | return [str(v) if isinstance(v, str) else v for v in iterable] |
|
77 | return [str(v) if isinstance(v, basestring) else v for v in iterable] | |
73 |
|
78 | |||
74 | return iterable |
|
79 | return iterable | |
75 |
|
80 | |||
76 | @MPDecorator |
|
81 | @MPDecorator | |
77 | class MADReader(JRODataReader, ProcessingUnit): |
|
82 | class MADReader(JRODataReader, ProcessingUnit): | |
78 |
|
83 | |||
79 | def __init__(self): |
|
84 | def __init__(self): | |
80 |
|
85 | |||
81 | ProcessingUnit.__init__(self) |
|
86 | ProcessingUnit.__init__(self) | |
82 |
|
87 | |||
83 | self.dataOut = Parameters() |
|
88 | self.dataOut = Parameters() | |
84 | self.counter_records = 0 |
|
89 | self.counter_records = 0 | |
85 | self.nrecords = None |
|
90 | self.nrecords = None | |
86 | self.flagNoMoreFiles = 0 |
|
91 | self.flagNoMoreFiles = 0 | |
87 | self.isConfig = False |
|
92 | self.isConfig = False | |
88 | self.filename = None |
|
93 | self.filename = None | |
89 | self.intervals = set() |
|
94 | self.intervals = set() | |
90 |
|
95 | |||
91 | def setup(self, |
|
96 | def setup(self, | |
92 | path=None, |
|
97 | path=None, | |
93 | startDate=None, |
|
98 | startDate=None, | |
94 | endDate=None, |
|
99 | endDate=None, | |
95 | format=None, |
|
100 | format=None, | |
96 | startTime=datetime.time(0, 0, 0), |
|
101 | startTime=datetime.time(0, 0, 0), | |
97 | endTime=datetime.time(23, 59, 59), |
|
102 | endTime=datetime.time(23, 59, 59), | |
98 | **kwargs): |
|
103 | **kwargs): | |
99 |
|
104 | |||
100 | self.path = path |
|
105 | self.path = path | |
101 | self.startDate = startDate |
|
106 | self.startDate = startDate | |
102 | self.endDate = endDate |
|
107 | self.endDate = endDate | |
103 | self.startTime = startTime |
|
108 | self.startTime = startTime | |
104 | self.endTime = endTime |
|
109 | self.endTime = endTime | |
105 | self.datatime = datetime.datetime(1900,1,1) |
|
110 | self.datatime = datetime.datetime(1900,1,1) | |
106 | self.oneDDict = load_json(kwargs.get('oneDDict', |
|
111 | self.oneDDict = load_json(kwargs.get('oneDDict', | |
107 | "{\"GDLATR\":\"lat\", \"GDLONR\":\"lon\"}")) |
|
112 | "{\"GDLATR\":\"lat\", \"GDLONR\":\"lon\"}")) | |
108 | self.twoDDict = load_json(kwargs.get('twoDDict', |
|
113 | self.twoDDict = load_json(kwargs.get('twoDDict', | |
109 | "{\"GDALT\": \"heightList\"}")) |
|
114 | "{\"GDALT\": \"heightList\"}")) | |
110 | self.ind2DList = load_json(kwargs.get('ind2DList', |
|
115 | self.independentParam = 'GDALT' | |
111 | "[\"GDALT\"]")) |
|
116 | ||
112 | if self.path is None: |
|
117 | if self.path is None: | |
113 | raise ValueError('The path is not valid') |
|
118 | raise ValueError('The path is not valid') | |
114 |
|
119 | |||
115 | if format is None: |
|
120 | if format is None: | |
116 | raise ValueError('The format is not valid choose simple or hdf5') |
|
121 | raise ValueError('The format is not valid choose simple or hdf5') | |
117 | elif format.lower() in ('simple', 'txt'): |
|
122 | elif format.lower() in ('simple', 'txt'): | |
118 | self.ext = '.txt' |
|
123 | self.ext = '.txt' | |
119 | elif format.lower() in ('cedar',): |
|
124 | elif format.lower() in ('cedar',): | |
120 | self.ext = '.001' |
|
125 | self.ext = '.001' | |
121 | else: |
|
126 | else: | |
122 | self.ext = '.hdf5' |
|
127 | self.ext = '.hdf5' | |
123 |
|
128 | |||
124 | self.search_files(self.path) |
|
129 | self.search_files(self.path) | |
125 | self.fileId = 0 |
|
130 | self.fileId = 0 | |
126 |
|
131 | |||
127 | if not self.fileList: |
|
132 | if not self.fileList: | |
128 | raise Warning('There is no files matching these date in the folder: {}. \n Check startDate and endDate'.format(path)) |
|
133 | raise Warning('There is no files matching these date in the folder: {}. \n Check startDate and endDate'.format(path)) | |
129 |
|
134 | |||
130 | self.setNextFile() |
|
135 | self.setNextFile() | |
131 |
|
136 | |||
132 | def search_files(self, path): |
|
137 | def search_files(self, path): | |
133 | ''' |
|
138 | ''' | |
134 | Searching for madrigal files in path |
|
139 | Searching for madrigal files in path | |
135 | Creating a list of files to procces included in [startDate,endDate] |
|
140 | Creating a list of files to procces included in [startDate,endDate] | |
136 |
|
141 | |||
137 | Input: |
|
142 | Input: | |
138 | path - Path to find files |
|
143 | path - Path to find files | |
139 | ''' |
|
144 | ''' | |
140 |
|
145 | |||
141 | log.log('Searching files {} in {} '.format(self.ext, path), 'MADReader') |
|
146 | log.log('Searching files {} in {} '.format(self.ext, path), 'MADReader') | |
142 | foldercounter = 0 |
|
|||
143 | fileList0 = glob.glob1(path, '*{}'.format(self.ext)) |
|
147 | fileList0 = glob.glob1(path, '*{}'.format(self.ext)) | |
144 | fileList0.sort() |
|
148 | fileList0.sort() | |
145 |
|
149 | |||
146 | self.fileList = [] |
|
150 | self.fileList = [] | |
147 | self.dateFileList = [] |
|
151 | self.dateFileList = [] | |
148 |
|
152 | |||
149 | startDate = self.startDate - datetime.timedelta(1) |
|
153 | startDate = self.startDate - datetime.timedelta(1) | |
150 | endDate = self.endDate + datetime.timedelta(1) |
|
154 | endDate = self.endDate + datetime.timedelta(1) | |
151 |
|
155 | |||
152 | for thisFile in fileList0: |
|
156 | for thisFile in fileList0: | |
153 | year = thisFile[3:7] |
|
157 | year = thisFile[3:7] | |
154 | if not year.isdigit(): |
|
158 | if not year.isdigit(): | |
155 | continue |
|
159 | continue | |
156 |
|
160 | |||
157 | month = thisFile[7:9] |
|
161 | month = thisFile[7:9] | |
158 | if not month.isdigit(): |
|
162 | if not month.isdigit(): | |
159 | continue |
|
163 | continue | |
160 |
|
164 | |||
161 | day = thisFile[9:11] |
|
165 | day = thisFile[9:11] | |
162 | if not day.isdigit(): |
|
166 | if not day.isdigit(): | |
163 | continue |
|
167 | continue | |
164 |
|
168 | |||
165 | year, month, day = int(year), int(month), int(day) |
|
169 | year, month, day = int(year), int(month), int(day) | |
166 | dateFile = datetime.date(year, month, day) |
|
170 | dateFile = datetime.date(year, month, day) | |
167 |
|
171 | |||
168 | if (startDate > dateFile) or (endDate < dateFile): |
|
172 | if (startDate > dateFile) or (endDate < dateFile): | |
169 | continue |
|
173 | continue | |
170 |
|
174 | |||
171 | self.fileList.append(thisFile) |
|
175 | self.fileList.append(thisFile) | |
172 | self.dateFileList.append(dateFile) |
|
176 | self.dateFileList.append(dateFile) | |
173 |
|
177 | |||
174 | return |
|
178 | return | |
175 |
|
179 | |||
176 | def parseHeader(self): |
|
180 | def parseHeader(self): | |
177 | ''' |
|
181 | ''' | |
178 | ''' |
|
182 | ''' | |
179 |
|
183 | |||
180 | self.output = {} |
|
184 | self.output = {} | |
181 | self.version = '2' |
|
185 | self.version = '2' | |
182 | s_parameters = None |
|
186 | s_parameters = None | |
183 | if self.ext == '.txt': |
|
187 | if self.ext == '.txt': | |
184 | self.parameters = [s.strip().lower() for s in self.fp.readline().strip().split(' ') if s] |
|
188 | self.parameters = [s.strip().lower() for s in self.fp.readline().decode().strip().split(' ') if s] | |
185 | elif self.ext == '.hdf5': |
|
189 | elif self.ext == '.hdf5': | |
186 | metadata = self.fp['Metadata'] |
|
190 | self.metadata = self.fp['Metadata'] | |
187 | data = self.fp['Data']['Array Layout'] |
|
191 | if '_record_layout' in self.metadata: | |
188 | if 'Independent Spatial Parameters' in metadata: |
|
192 | s_parameters = [s[0].lower().decode() for s in self.metadata['Independent Spatial Parameters']] | |
189 | s_parameters = [s[0].lower() for s in metadata['Independent Spatial Parameters']] |
|
|||
190 | self.version = '3' |
|
193 | self.version = '3' | |
191 |
|
|
194 | self.parameters = [s[0].lower().decode() for s in self.metadata['Data Parameters']] | |
192 | one_d = [1 for s in one] |
|
|||
193 | two = [s[0].lower() for s in data['2D Parameters']['Data Parameters']] |
|
|||
194 | two_d = [2 for s in two] |
|
|||
195 | self.parameters = one + two |
|
|||
196 | self.parameters_d = one_d + two_d |
|
|||
197 |
|
195 | |||
198 | log.success('Parameters found: {}'.format(self.parameters), |
|
196 | log.success('Parameters found: {}'.format(self.parameters), | |
199 | 'MADReader') |
|
197 | 'MADReader') | |
200 | if s_parameters: |
|
198 | if s_parameters: | |
201 |
log.success('Spatial parameters: {}'.format( |
|
199 | log.success('Spatial parameters found: {}'.format(s_parameters), | |
202 | 'MADReader') |
|
200 | 'MADReader') | |
203 |
|
201 | |||
204 | for param in list(self.oneDDict.keys()): |
|
202 | for param in list(self.oneDDict.keys()): | |
205 | if param.lower() not in self.parameters: |
|
203 | if param.lower() not in self.parameters: | |
206 | log.warning( |
|
204 | log.warning( | |
207 | 'Parameter {} not found will be ignored'.format( |
|
205 | 'Parameter {} not found will be ignored'.format( | |
208 | param), |
|
206 | param), | |
209 | 'MADReader') |
|
207 | 'MADReader') | |
210 | self.oneDDict.pop(param, None) |
|
208 | self.oneDDict.pop(param, None) | |
211 |
|
209 | |||
212 | for param, value in list(self.twoDDict.items()): |
|
210 | for param, value in list(self.twoDDict.items()): | |
213 | if param.lower() not in self.parameters: |
|
211 | if param.lower() not in self.parameters: | |
214 | log.warning( |
|
212 | log.warning( | |
215 | 'Parameter {} not found, it will be ignored'.format( |
|
213 | 'Parameter {} not found, it will be ignored'.format( | |
216 | param), |
|
214 | param), | |
217 | 'MADReader') |
|
215 | 'MADReader') | |
218 | self.twoDDict.pop(param, None) |
|
216 | self.twoDDict.pop(param, None) | |
219 | continue |
|
217 | continue | |
220 | if isinstance(value, list): |
|
218 | if isinstance(value, list): | |
221 | if value[0] not in self.output: |
|
219 | if value[0] not in self.output: | |
222 | self.output[value[0]] = [] |
|
220 | self.output[value[0]] = [] | |
223 |
self.output[value[0]].append( |
|
221 | self.output[value[0]].append([]) | |
224 |
|
222 | |||
225 | def parseData(self): |
|
223 | def parseData(self): | |
226 | ''' |
|
224 | ''' | |
227 | ''' |
|
225 | ''' | |
228 |
|
226 | |||
229 | if self.ext == '.txt': |
|
227 | if self.ext == '.txt': | |
230 | self.data = numpy.genfromtxt(self.fp, missing_values=('missing')) |
|
228 | self.data = numpy.genfromtxt(self.fp, missing_values=('missing')) | |
231 | self.nrecords = self.data.shape[0] |
|
229 | self.nrecords = self.data.shape[0] | |
232 |
self.ranges = numpy.unique(self.data[:,self.parameters.index(self.ind |
|
230 | self.ranges = numpy.unique(self.data[:,self.parameters.index(self.independentParam.lower())]) | |
|
231 | self.counter_records = 0 | |||
233 | elif self.ext == '.hdf5': |
|
232 | elif self.ext == '.hdf5': | |
234 |
self.data = self.fp['Data'] |
|
233 | self.data = self.fp['Data'] | |
235 | self.nrecords = len(self.data['timestamps'].value) |
|
234 | self.ranges = numpy.unique(self.data['Table Layout'][self.independentParam.lower()]) | |
236 |
self. |
|
235 | self.times = numpy.unique(self.data['Table Layout']['ut1_unix']) | |
237 |
|
236 | self.counter_records = int(self.data['Table Layout']['recno'][0]) | ||
|
237 | self.nrecords = int(self.data['Table Layout']['recno'][-1]) | |||
|
238 | ||||
238 | def setNextFile(self): |
|
239 | def setNextFile(self): | |
239 | ''' |
|
240 | ''' | |
240 | ''' |
|
241 | ''' | |
241 |
|
242 | |||
242 | file_id = self.fileId |
|
243 | file_id = self.fileId | |
243 |
|
244 | |||
244 | if file_id == len(self.fileList): |
|
245 | if file_id == len(self.fileList): | |
245 | log.success('No more files', 'MADReader') |
|
246 | log.success('No more files', 'MADReader') | |
246 | self.flagNoMoreFiles = 1 |
|
247 | self.flagNoMoreFiles = 1 | |
247 | return 0 |
|
248 | return 0 | |
248 |
|
249 | |||
249 | log.success( |
|
250 | log.success( | |
250 | 'Opening: {}'.format(self.fileList[file_id]), |
|
251 | 'Opening: {}'.format(self.fileList[file_id]), | |
251 | 'MADReader' |
|
252 | 'MADReader' | |
252 | ) |
|
253 | ) | |
253 |
|
254 | |||
254 | filename = os.path.join(self.path, self.fileList[file_id]) |
|
255 | filename = os.path.join(self.path, self.fileList[file_id]) | |
255 |
|
256 | |||
256 | if self.filename is not None: |
|
257 | if self.filename is not None: | |
257 | self.fp.close() |
|
258 | self.fp.close() | |
258 |
|
259 | |||
259 | self.filename = filename |
|
260 | self.filename = filename | |
260 | self.filedate = self.dateFileList[file_id] |
|
261 | self.filedate = self.dateFileList[file_id] | |
261 |
|
262 | |||
262 | if self.ext=='.hdf5': |
|
263 | if self.ext=='.hdf5': | |
263 | self.fp = h5py.File(self.filename, 'r') |
|
264 | self.fp = h5py.File(self.filename, 'r') | |
264 | else: |
|
265 | else: | |
265 | self.fp = open(self.filename, 'rb') |
|
266 | self.fp = open(self.filename, 'rb') | |
266 |
|
267 | |||
267 | self.parseHeader() |
|
268 | self.parseHeader() | |
268 | self.parseData() |
|
269 | self.parseData() | |
269 | self.sizeOfFile = os.path.getsize(self.filename) |
|
270 | self.sizeOfFile = os.path.getsize(self.filename) | |
270 | self.counter_records = 0 |
|
|||
271 | self.flagIsNewFile = 0 |
|
271 | self.flagIsNewFile = 0 | |
272 | self.fileId += 1 |
|
272 | self.fileId += 1 | |
273 |
|
273 | |||
274 | return 1 |
|
274 | return 1 | |
275 |
|
275 | |||
276 | def readNextBlock(self): |
|
276 | def readNextBlock(self): | |
277 |
|
277 | |||
278 | while True: |
|
278 | while True: | |
279 | self.flagDiscontinuousBlock = 0 |
|
279 | self.flagDiscontinuousBlock = 0 | |
280 | if self.flagIsNewFile: |
|
280 | if self.flagIsNewFile: | |
281 | if not self.setNextFile(): |
|
281 | if not self.setNextFile(): | |
282 | return 0 |
|
282 | return 0 | |
283 |
|
283 | |||
284 | self.readBlock() |
|
284 | self.readBlock() | |
285 |
|
285 | |||
286 | if (self.datatime < datetime.datetime.combine(self.startDate, self.startTime)) or \ |
|
286 | if (self.datatime < datetime.datetime.combine(self.startDate, self.startTime)) or \ | |
287 | (self.datatime > datetime.datetime.combine(self.endDate, self.endTime)): |
|
287 | (self.datatime > datetime.datetime.combine(self.endDate, self.endTime)): | |
288 | log.warning( |
|
288 | log.warning( | |
289 | 'Reading Record No. {}/{} -> {} [Skipping]'.format( |
|
289 | 'Reading Record No. {}/{} -> {} [Skipping]'.format( | |
290 | self.counter_records, |
|
290 | self.counter_records, | |
291 | self.nrecords, |
|
291 | self.nrecords, | |
292 | self.datatime.ctime()), |
|
292 | self.datatime.ctime()), | |
293 | 'MADReader') |
|
293 | 'MADReader') | |
294 | continue |
|
294 | continue | |
295 | break |
|
295 | break | |
296 |
|
296 | |||
297 | log.log( |
|
297 | log.log( | |
298 | 'Reading Record No. {}/{} -> {}'.format( |
|
298 | 'Reading Record No. {}/{} -> {}'.format( | |
299 | self.counter_records, |
|
299 | self.counter_records, | |
300 | self.nrecords, |
|
300 | self.nrecords, | |
301 | self.datatime.ctime()), |
|
301 | self.datatime.ctime()), | |
302 | 'MADReader') |
|
302 | 'MADReader') | |
303 |
|
303 | |||
304 | return 1 |
|
304 | return 1 | |
305 |
|
305 | |||
306 | def readBlock(self): |
|
306 | def readBlock(self): | |
307 | ''' |
|
307 | ''' | |
308 | ''' |
|
308 | ''' | |
309 | dum = [] |
|
309 | dum = [] | |
310 | if self.ext == '.txt': |
|
310 | if self.ext == '.txt': | |
311 | dt = self.data[self.counter_records][:6].astype(int) |
|
311 | dt = self.data[self.counter_records][:6].astype(int) | |
312 | if datetime.datetime(dt[0], dt[1], dt[2], dt[3], dt[4], dt[5]).date() > self.datatime.date(): |
|
312 | if datetime.datetime(dt[0], dt[1], dt[2], dt[3], dt[4], dt[5]).date() > self.datatime.date(): | |
313 | self.flagDiscontinuousBlock = 1 |
|
313 | self.flagDiscontinuousBlock = 1 | |
314 | self.datatime = datetime.datetime(dt[0], dt[1], dt[2], dt[3], dt[4], dt[5]) |
|
314 | self.datatime = datetime.datetime(dt[0], dt[1], dt[2], dt[3], dt[4], dt[5]) | |
315 | while True: |
|
315 | while True: | |
316 | dt = self.data[self.counter_records][:6].astype(int) |
|
316 | dt = self.data[self.counter_records][:6].astype(int) | |
317 | datatime = datetime.datetime(dt[0], dt[1], dt[2], dt[3], dt[4], dt[5]) |
|
317 | datatime = datetime.datetime(dt[0], dt[1], dt[2], dt[3], dt[4], dt[5]) | |
318 | if datatime == self.datatime: |
|
318 | if datatime == self.datatime: | |
319 | dum.append(self.data[self.counter_records]) |
|
319 | dum.append(self.data[self.counter_records]) | |
320 | self.counter_records += 1 |
|
320 | self.counter_records += 1 | |
321 | if self.counter_records == self.nrecords: |
|
321 | if self.counter_records == self.nrecords: | |
322 | self.flagIsNewFile = True |
|
322 | self.flagIsNewFile = True | |
323 | break |
|
323 | break | |
324 | continue |
|
324 | continue | |
325 | self.intervals.add((datatime-self.datatime).seconds) |
|
325 | self.intervals.add((datatime-self.datatime).seconds) | |
326 | break |
|
326 | break | |
327 | elif self.ext == '.hdf5': |
|
327 | elif self.ext == '.hdf5': | |
328 | datatime = datetime.datetime.utcfromtimestamp( |
|
328 | datatime = datetime.datetime.utcfromtimestamp( | |
329 |
self. |
|
329 | self.times[self.counter_records]) | |
330 | nHeights = len(self.ranges) |
|
330 | dum = self.data['Table Layout'][self.data['Table Layout']['recno']==self.counter_records] | |
331 | for n, param in enumerate(self.parameters): |
|
|||
332 | if self.parameters_d[n] == 1: |
|
|||
333 | dum.append(numpy.ones(nHeights)*self.data['1D Parameters'][param][self.counter_records]) |
|
|||
334 | else: |
|
|||
335 | if self.version == '2': |
|
|||
336 | dum.append(self.data['2D Parameters'][param][self.counter_records]) |
|
|||
337 | else: |
|
|||
338 | tmp = self.data['2D Parameters'][param].value.T |
|
|||
339 | dum.append(tmp[self.counter_records]) |
|
|||
340 | self.intervals.add((datatime-self.datatime).seconds) |
|
331 | self.intervals.add((datatime-self.datatime).seconds) | |
341 | if datatime.date()>self.datatime.date(): |
|
332 | if datatime.date()>self.datatime.date(): | |
342 | self.flagDiscontinuousBlock = 1 |
|
333 | self.flagDiscontinuousBlock = 1 | |
343 | self.datatime = datatime |
|
334 | self.datatime = datatime | |
344 | self.counter_records += 1 |
|
335 | self.counter_records += 1 | |
345 | if self.counter_records == self.nrecords: |
|
336 | if self.counter_records == self.nrecords: | |
346 | self.flagIsNewFile = True |
|
337 | self.flagIsNewFile = True | |
347 |
|
338 | |||
348 | self.buffer = numpy.array(dum) |
|
339 | self.buffer = numpy.array(dum) | |
349 | return |
|
340 | return | |
350 |
|
341 | |||
351 | def set_output(self): |
|
342 | def set_output(self): | |
352 | ''' |
|
343 | ''' | |
353 | Storing data from buffer to dataOut object |
|
344 | Storing data from buffer to dataOut object | |
354 | ''' |
|
345 | ''' | |
355 |
|
346 | |||
356 | parameters = [None for __ in self.parameters] |
|
347 | parameters = [None for __ in self.parameters] | |
357 |
|
348 | |||
358 | for param, attr in list(self.oneDDict.items()): |
|
349 | for param, attr in list(self.oneDDict.items()): | |
359 | x = self.parameters.index(param.lower()) |
|
350 | x = self.parameters.index(param.lower()) | |
360 | setattr(self.dataOut, attr, self.buffer[0][x]) |
|
351 | setattr(self.dataOut, attr, self.buffer[0][x]) | |
361 |
|
352 | |||
362 |
for param, value in list(self.twoDDict.items()): |
|
353 | for param, value in list(self.twoDDict.items()): | |
363 | x = self.parameters.index(param.lower()) |
|
354 | dummy = numpy.zeros(self.ranges.shape) + numpy.nan | |
364 | if self.ext == '.txt': |
|
355 | if self.ext == '.txt': | |
365 |
|
|
356 | x = self.parameters.index(param.lower()) | |
|
357 | y = self.parameters.index(self.independentParam.lower()) | |||
366 | ranges = self.buffer[:,y] |
|
358 | ranges = self.buffer[:,y] | |
367 | #if self.ranges.size == ranges.size: |
|
359 | #if self.ranges.size == ranges.size: | |
368 | # continue |
|
360 | # continue | |
369 | index = numpy.where(numpy.in1d(self.ranges, ranges))[0] |
|
361 | index = numpy.where(numpy.in1d(self.ranges, ranges))[0] | |
370 | dummy = numpy.zeros(self.ranges.shape) + numpy.nan |
|
|||
371 | dummy[index] = self.buffer[:,x] |
|
362 | dummy[index] = self.buffer[:,x] | |
372 |
else: |
|
363 | else: | |
373 | dummy = self.buffer[x] |
|
364 | ranges = self.buffer[self.independentParam.lower()] | |
|
365 | index = numpy.where(numpy.in1d(self.ranges, ranges))[0] | |||
|
366 | dummy[index] = self.buffer[param.lower()] | |||
374 |
|
367 | |||
375 | if isinstance(value, str): |
|
368 | if isinstance(value, str): | |
376 |
if value not in self.ind |
|
369 | if value not in self.independentParam: | |
377 | setattr(self.dataOut, value, dummy.reshape(1,-1)) |
|
370 | setattr(self.dataOut, value, dummy.reshape(1,-1)) | |
378 | elif isinstance(value, list): |
|
371 | elif isinstance(value, list): | |
379 | self.output[value[0]][value[1]] = dummy |
|
372 | self.output[value[0]][value[1]] = dummy | |
380 | parameters[value[1]] = param |
|
373 | parameters[value[1]] = param | |
381 |
|
||||
382 | for key, value in list(self.output.items()): |
|
374 | for key, value in list(self.output.items()): | |
383 | setattr(self.dataOut, key, numpy.array(value)) |
|
375 | setattr(self.dataOut, key, numpy.array(value)) | |
384 |
|
376 | |||
385 | self.dataOut.parameters = [s for s in parameters if s] |
|
377 | self.dataOut.parameters = [s for s in parameters if s] | |
386 | self.dataOut.heightList = self.ranges |
|
378 | self.dataOut.heightList = self.ranges | |
387 | self.dataOut.utctime = (self.datatime - datetime.datetime(1970, 1, 1)).total_seconds() |
|
379 | self.dataOut.utctime = (self.datatime - datetime.datetime(1970, 1, 1)).total_seconds() | |
388 | self.dataOut.utctimeInit = self.dataOut.utctime |
|
380 | self.dataOut.utctimeInit = self.dataOut.utctime | |
389 | self.dataOut.paramInterval = min(self.intervals) |
|
381 | self.dataOut.paramInterval = min(self.intervals) | |
390 | self.dataOut.useLocalTime = False |
|
382 | self.dataOut.useLocalTime = False | |
391 | self.dataOut.flagNoData = False |
|
383 | self.dataOut.flagNoData = False | |
392 | self.dataOut.nrecords = self.nrecords |
|
384 | self.dataOut.nrecords = self.nrecords | |
393 | self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock |
|
385 | self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock | |
394 |
|
386 | |||
395 | def getData(self): |
|
387 | def getData(self): | |
396 | ''' |
|
388 | ''' | |
397 | Storing data from databuffer to dataOut object |
|
389 | Storing data from databuffer to dataOut object | |
398 | ''' |
|
390 | ''' | |
399 | if self.flagNoMoreFiles: |
|
391 | if self.flagNoMoreFiles: | |
400 | self.dataOut.flagNoData = True |
|
392 | self.dataOut.flagNoData = True | |
401 | self.dataOut.error = 'No file left to process' |
|
393 | self.dataOut.error = 'No file left to process' | |
402 | return 0 |
|
394 | return 0 | |
403 |
|
395 | |||
404 | if not self.readNextBlock(): |
|
396 | if not self.readNextBlock(): | |
405 | self.dataOut.flagNoData = True |
|
397 | self.dataOut.flagNoData = True | |
406 | return 0 |
|
398 | return 0 | |
407 |
|
399 | |||
408 | self.set_output() |
|
400 | self.set_output() | |
409 |
|
401 | |||
410 | return 1 |
|
402 | return 1 | |
411 |
|
403 | |||
412 | @MPDecorator |
|
404 | @MPDecorator | |
413 | class MADWriter(Operation): |
|
405 | class MADWriter(Operation): | |
414 |
|
406 | |||
415 | missing = -32767 |
|
407 | missing = -32767 | |
416 |
|
408 | |||
417 | def __init__(self): |
|
409 | def __init__(self): | |
418 |
|
410 | |||
419 | Operation.__init__(self) |
|
411 | Operation.__init__(self) | |
420 | self.dataOut = Parameters() |
|
412 | self.dataOut = Parameters() | |
421 | self.counter = 0 |
|
413 | self.counter = 0 | |
422 | self.path = None |
|
414 | self.path = None | |
423 | self.fp = None |
|
415 | self.fp = None | |
424 |
|
416 | |||
425 |
def run(self, dataOut, path, oneDDict, ind |
|
417 | def run(self, dataOut, path, oneDDict, independentParam='[]', twoDDict='{}', | |
426 | metadata='{}', format='cedar', **kwargs): |
|
418 | metadata='{}', format='cedar', **kwargs): | |
427 | ''' |
|
419 | ''' | |
428 | Inputs: |
|
420 | Inputs: | |
429 | path - path where files will be created |
|
421 | path - path where files will be created | |
430 | oneDDict - json of one-dimensional parameters in record where keys |
|
422 | oneDDict - json of one-dimensional parameters in record where keys | |
431 | are Madrigal codes (integers or mnemonics) and values the corresponding |
|
423 | are Madrigal codes (integers or mnemonics) and values the corresponding | |
432 | dataOut attribute e.g: { |
|
424 | dataOut attribute e.g: { | |
433 | 'gdlatr': 'lat', |
|
425 | 'gdlatr': 'lat', | |
434 | 'gdlonr': 'lon', |
|
426 | 'gdlonr': 'lon', | |
435 | 'gdlat2':'lat', |
|
427 | 'gdlat2':'lat', | |
436 | 'glon2':'lon'} |
|
428 | 'glon2':'lon'} | |
437 |
ind |
|
429 | independentParam - list of independent spatial two-dimensional parameters e.g: | |
438 | ['heighList'] |
|
430 | ['heigthList'] | |
439 | twoDDict - json of two-dimensional parameters in record where keys |
|
431 | twoDDict - json of two-dimensional parameters in record where keys | |
440 | are Madrigal codes (integers or mnemonics) and values the corresponding |
|
432 | are Madrigal codes (integers or mnemonics) and values the corresponding | |
441 | dataOut attribute if multidimensional array specify as tupple |
|
433 | dataOut attribute if multidimensional array specify as tupple | |
442 | ('attr', pos) e.g: { |
|
434 | ('attr', pos) e.g: { | |
443 | 'gdalt': 'heightList', |
|
435 | 'gdalt': 'heightList', | |
444 | 'vn1p2': ('data_output', 0), |
|
436 | 'vn1p2': ('data_output', 0), | |
445 | 'vn2p2': ('data_output', 1), |
|
437 | 'vn2p2': ('data_output', 1), | |
446 | 'vn3': ('data_output', 2), |
|
438 | 'vn3': ('data_output', 2), | |
447 | 'snl': ('data_SNR', 'db') |
|
439 | 'snl': ('data_SNR', 'db') | |
448 | } |
|
440 | } | |
449 | metadata - json of madrigal metadata (kinst, kindat, catalog and header) |
|
441 | metadata - json of madrigal metadata (kinst, kindat, catalog and header) | |
450 | ''' |
|
442 | ''' | |
451 | if not self.isConfig: |
|
443 | if not self.isConfig: | |
452 |
self.setup(path, oneDDict, ind |
|
444 | self.setup(path, oneDDict, independentParam, twoDDict, metadata, format, **kwargs) | |
453 | self.isConfig = True |
|
445 | self.isConfig = True | |
454 |
|
446 | |||
455 | self.dataOut = dataOut |
|
447 | self.dataOut = dataOut | |
456 | self.putData() |
|
448 | self.putData() | |
457 | return 1 |
|
449 | return 1 | |
458 |
|
450 | |||
459 |
def setup(self, path, oneDDict, ind |
|
451 | def setup(self, path, oneDDict, independentParam, twoDDict, metadata, format, **kwargs): | |
460 | ''' |
|
452 | ''' | |
461 | Configure Operation |
|
453 | Configure Operation | |
462 | ''' |
|
454 | ''' | |
463 |
|
455 | |||
464 | self.path = path |
|
456 | self.path = path | |
465 | self.blocks = kwargs.get('blocks', None) |
|
457 | self.blocks = kwargs.get('blocks', None) | |
466 | self.counter = 0 |
|
458 | self.counter = 0 | |
467 | self.oneDDict = load_json(oneDDict) |
|
459 | self.oneDDict = load_json(oneDDict) | |
468 | self.twoDDict = load_json(twoDDict) |
|
460 | self.twoDDict = load_json(twoDDict) | |
469 |
self.ind |
|
461 | self.independentParam = load_json(independentParam) | |
470 | meta = load_json(metadata) |
|
462 | meta = load_json(metadata) | |
471 | self.kinst = meta.get('kinst') |
|
463 | self.kinst = meta.get('kinst') | |
472 | self.kindat = meta.get('kindat') |
|
464 | self.kindat = meta.get('kindat') | |
473 | self.catalog = meta.get('catalog', DEF_CATALOG) |
|
465 | self.catalog = meta.get('catalog', DEF_CATALOG) | |
474 | self.header = meta.get('header', DEF_HEADER) |
|
466 | self.header = meta.get('header', DEF_HEADER) | |
475 | if format == 'cedar': |
|
467 | if format == 'cedar': | |
476 | self.ext = '.dat' |
|
468 | self.ext = '.dat' | |
477 | self.extra_args = {} |
|
469 | self.extra_args = {} | |
478 | elif format == 'hdf5': |
|
470 | elif format == 'hdf5': | |
479 | self.ext = '.hdf5' |
|
471 | self.ext = '.hdf5' | |
480 |
self.extra_args = {'ind |
|
472 | self.extra_args = {'independentParam': self.independentParam} | |
481 |
|
473 | |||
482 | self.keys = [k.lower() for k in self.twoDDict] |
|
474 | self.keys = [k.lower() for k in self.twoDDict] | |
483 | if 'range' in self.keys: |
|
475 | if 'range' in self.keys: | |
484 | self.keys.remove('range') |
|
476 | self.keys.remove('range') | |
485 | if 'gdalt' in self.keys: |
|
477 | if 'gdalt' in self.keys: | |
486 | self.keys.remove('gdalt') |
|
478 | self.keys.remove('gdalt') | |
487 |
|
479 | |||
488 | def setFile(self): |
|
480 | def setFile(self): | |
489 | ''' |
|
481 | ''' | |
490 | Create new cedar file object |
|
482 | Create new cedar file object | |
491 | ''' |
|
483 | ''' | |
492 |
|
484 | |||
493 | self.mnemonic = MNEMONICS[self.kinst] #TODO get mnemonic from madrigal |
|
485 | self.mnemonic = MNEMONICS[self.kinst] #TODO get mnemonic from madrigal | |
494 | date = datetime.datetime.utcfromtimestamp(self.dataOut.utctime) |
|
486 | date = datetime.datetime.utcfromtimestamp(self.dataOut.utctime) | |
495 |
|
487 | |||
496 | filename = '{}{}{}'.format(self.mnemonic, |
|
488 | filename = '{}{}{}'.format(self.mnemonic, | |
497 | date.strftime('%Y%m%d_%H%M%S'), |
|
489 | date.strftime('%Y%m%d_%H%M%S'), | |
498 | self.ext) |
|
490 | self.ext) | |
499 |
|
491 | |||
500 | self.fullname = os.path.join(self.path, filename) |
|
492 | self.fullname = os.path.join(self.path, filename) | |
501 |
|
493 | |||
502 | if os.path.isfile(self.fullname) : |
|
494 | if os.path.isfile(self.fullname) : | |
503 | log.warning( |
|
495 | log.warning( | |
504 | 'Destination file {} already exists, previous file deleted.'.format( |
|
496 | 'Destination file {} already exists, previous file deleted.'.format( | |
505 | self.fullname), |
|
497 | self.fullname), | |
506 | 'MADWriter') |
|
498 | 'MADWriter') | |
507 | os.remove(self.fullname) |
|
499 | os.remove(self.fullname) | |
508 |
|
500 | |||
509 | try: |
|
501 | try: | |
510 | log.success( |
|
502 | log.success( | |
511 | 'Creating file: {}'.format(self.fullname), |
|
503 | 'Creating file: {}'.format(self.fullname), | |
512 | 'MADWriter') |
|
504 | 'MADWriter') | |
513 | self.fp = madrigal.cedar.MadrigalCedarFile(self.fullname, True) |
|
505 | self.fp = madrigal.cedar.MadrigalCedarFile(self.fullname, True) | |
514 | except ValueError as e: |
|
506 | except ValueError as e: | |
515 | log.error( |
|
507 | log.error( | |
516 | 'Impossible to create a cedar object with "madrigal.cedar.MadrigalCedarFile"', |
|
508 | 'Impossible to create a cedar object with "madrigal.cedar.MadrigalCedarFile"', | |
517 | 'MADWriter') |
|
509 | 'MADWriter') | |
518 | return |
|
510 | return | |
519 |
|
511 | |||
520 | return 1 |
|
512 | return 1 | |
521 |
|
513 | |||
522 | def writeBlock(self): |
|
514 | def writeBlock(self): | |
523 | ''' |
|
515 | ''' | |
524 | Add data records to cedar file taking data from oneDDict and twoDDict |
|
516 | Add data records to cedar file taking data from oneDDict and twoDDict | |
525 | attributes. |
|
517 | attributes. | |
526 | Allowed parameters in: parcodes.tab |
|
518 | Allowed parameters in: parcodes.tab | |
527 | ''' |
|
519 | ''' | |
528 |
|
520 | |||
529 | startTime = datetime.datetime.utcfromtimestamp(self.dataOut.utctime) |
|
521 | startTime = datetime.datetime.utcfromtimestamp(self.dataOut.utctime) | |
530 | endTime = startTime + datetime.timedelta(seconds=self.dataOut.paramInterval) |
|
522 | endTime = startTime + datetime.timedelta(seconds=self.dataOut.paramInterval) | |
531 | heights = self.dataOut.heightList |
|
523 | heights = self.dataOut.heightList | |
532 |
|
524 | |||
533 | if self.ext == '.dat': |
|
525 | if self.ext == '.dat': | |
534 | for key, value in list(self.twoDDict.items()): |
|
526 | for key, value in list(self.twoDDict.items()): | |
535 | if isinstance(value, str): |
|
527 | if isinstance(value, str): | |
536 | data = getattr(self.dataOut, value) |
|
528 | data = getattr(self.dataOut, value) | |
537 | invalid = numpy.isnan(data) |
|
529 | invalid = numpy.isnan(data) | |
538 | data[invalid] = self.missing |
|
530 | data[invalid] = self.missing | |
539 | elif isinstance(value, (tuple, list)): |
|
531 | elif isinstance(value, (tuple, list)): | |
540 | attr, key = value |
|
532 | attr, key = value | |
541 | data = getattr(self.dataOut, attr) |
|
533 | data = getattr(self.dataOut, attr) | |
542 | invalid = numpy.isnan(data) |
|
534 | invalid = numpy.isnan(data) | |
543 | data[invalid] = self.missing |
|
535 | data[invalid] = self.missing | |
544 |
|
536 | |||
545 | out = {} |
|
537 | out = {} | |
546 | for key, value in list(self.twoDDict.items()): |
|
538 | for key, value in list(self.twoDDict.items()): | |
547 | key = key.lower() |
|
539 | key = key.lower() | |
548 | if isinstance(value, str): |
|
540 | if isinstance(value, str): | |
549 | if 'db' in value.lower(): |
|
541 | if 'db' in value.lower(): | |
550 | tmp = getattr(self.dataOut, value.replace('_db', '')) |
|
542 | tmp = getattr(self.dataOut, value.replace('_db', '')) | |
551 | SNRavg = numpy.average(tmp, axis=0) |
|
543 | SNRavg = numpy.average(tmp, axis=0) | |
552 | tmp = 10*numpy.log10(SNRavg) |
|
544 | tmp = 10*numpy.log10(SNRavg) | |
553 | else: |
|
545 | else: | |
554 | tmp = getattr(self.dataOut, value) |
|
546 | tmp = getattr(self.dataOut, value) | |
555 | out[key] = tmp.flatten() |
|
547 | out[key] = tmp.flatten() | |
556 | elif isinstance(value, (tuple, list)): |
|
548 | elif isinstance(value, (tuple, list)): | |
557 | attr, x = value |
|
549 | attr, x = value | |
558 | data = getattr(self.dataOut, attr) |
|
550 | data = getattr(self.dataOut, attr) | |
559 | out[key] = data[int(x)] |
|
551 | out[key] = data[int(x)] | |
560 |
|
552 | |||
561 | a = numpy.array([out[k] for k in self.keys]) |
|
553 | a = numpy.array([out[k] for k in self.keys]) | |
562 | nrows = numpy.array([numpy.isnan(a[:, x]).all() for x in range(len(heights))]) |
|
554 | nrows = numpy.array([numpy.isnan(a[:, x]).all() for x in range(len(heights))]) | |
563 | index = numpy.where(nrows == False)[0] |
|
555 | index = numpy.where(nrows == False)[0] | |
564 |
|
556 | |||
565 | rec = madrigal.cedar.MadrigalDataRecord( |
|
557 | rec = madrigal.cedar.MadrigalDataRecord( | |
566 | self.kinst, |
|
558 | self.kinst, | |
567 | self.kindat, |
|
559 | self.kindat, | |
568 | startTime.year, |
|
560 | startTime.year, | |
569 | startTime.month, |
|
561 | startTime.month, | |
570 | startTime.day, |
|
562 | startTime.day, | |
571 | startTime.hour, |
|
563 | startTime.hour, | |
572 | startTime.minute, |
|
564 | startTime.minute, | |
573 | startTime.second, |
|
565 | startTime.second, | |
574 | startTime.microsecond/10000, |
|
566 | startTime.microsecond/10000, | |
575 | endTime.year, |
|
567 | endTime.year, | |
576 | endTime.month, |
|
568 | endTime.month, | |
577 | endTime.day, |
|
569 | endTime.day, | |
578 | endTime.hour, |
|
570 | endTime.hour, | |
579 | endTime.minute, |
|
571 | endTime.minute, | |
580 | endTime.second, |
|
572 | endTime.second, | |
581 | endTime.microsecond/10000, |
|
573 | endTime.microsecond/10000, | |
582 | list(self.oneDDict.keys()), |
|
574 | list(self.oneDDict.keys()), | |
583 | list(self.twoDDict.keys()), |
|
575 | list(self.twoDDict.keys()), | |
584 | len(index), |
|
576 | len(index), | |
585 | **self.extra_args |
|
577 | **self.extra_args | |
586 | ) |
|
578 | ) | |
587 |
|
579 | |||
588 | # Setting 1d values |
|
580 | # Setting 1d values | |
589 | for key in self.oneDDict: |
|
581 | for key in self.oneDDict: | |
590 | rec.set1D(key, getattr(self.dataOut, self.oneDDict[key])) |
|
582 | rec.set1D(key, getattr(self.dataOut, self.oneDDict[key])) | |
591 |
|
583 | |||
592 | # Setting 2d values |
|
584 | # Setting 2d values | |
593 | nrec = 0 |
|
585 | nrec = 0 | |
594 | for n in index: |
|
586 | for n in index: | |
595 | for key in out: |
|
587 | for key in out: | |
596 | rec.set2D(key, nrec, out[key][n]) |
|
588 | rec.set2D(key, nrec, out[key][n]) | |
597 | nrec += 1 |
|
589 | nrec += 1 | |
598 |
|
590 | |||
599 | self.fp.append(rec) |
|
591 | self.fp.append(rec) | |
600 | if self.ext == '.hdf5' and self.counter % 500 == 0 and self.counter > 0: |
|
592 | if self.ext == '.hdf5' and self.counter % 500 == 0 and self.counter > 0: | |
601 | self.fp.dump() |
|
593 | self.fp.dump() | |
602 | if self.counter % 20 == 0 and self.counter > 0: |
|
594 | if self.counter % 20 == 0 and self.counter > 0: | |
603 | log.log( |
|
595 | log.log( | |
604 | 'Writing {} records'.format( |
|
596 | 'Writing {} records'.format( | |
605 | self.counter), |
|
597 | self.counter), | |
606 | 'MADWriter') |
|
598 | 'MADWriter') | |
607 |
|
599 | |||
608 | def setHeader(self): |
|
600 | def setHeader(self): | |
609 | ''' |
|
601 | ''' | |
610 | Create an add catalog and header to cedar file |
|
602 | Create an add catalog and header to cedar file | |
611 | ''' |
|
603 | ''' | |
612 |
|
604 | |||
613 | log.success('Closing file {}'.format(self.fullname), 'MADWriter') |
|
605 | log.success('Closing file {}'.format(self.fullname), 'MADWriter') | |
614 |
|
606 | |||
615 | if self.ext == '.dat': |
|
607 | if self.ext == '.dat': | |
616 | self.fp.write() |
|
608 | self.fp.write() | |
617 | else: |
|
609 | else: | |
618 | self.fp.dump() |
|
610 | self.fp.dump() | |
619 | self.fp.close() |
|
611 | self.fp.close() | |
620 |
|
612 | |||
621 | header = madrigal.cedar.CatalogHeaderCreator(self.fullname) |
|
613 | header = madrigal.cedar.CatalogHeaderCreator(self.fullname) | |
622 | header.createCatalog(**self.catalog) |
|
614 | header.createCatalog(**self.catalog) | |
623 | header.createHeader(**self.header) |
|
615 | header.createHeader(**self.header) | |
624 | header.write() |
|
616 | header.write() | |
625 |
|
617 | |||
626 | def putData(self): |
|
618 | def putData(self): | |
627 |
|
619 | |||
628 | if self.dataOut.flagNoData: |
|
620 | if self.dataOut.flagNoData: | |
629 | return 0 |
|
621 | return 0 | |
630 |
|
622 | |||
631 | if self.dataOut.flagDiscontinuousBlock or self.counter == self.blocks: |
|
623 | if self.dataOut.flagDiscontinuousBlock or self.counter == self.blocks: | |
632 | if self.counter > 0: |
|
624 | if self.counter > 0: | |
633 | self.setHeader() |
|
625 | self.setHeader() | |
634 | self.counter = 0 |
|
626 | self.counter = 0 | |
635 |
|
627 | |||
636 | if self.counter == 0: |
|
628 | if self.counter == 0: | |
637 | self.setFile() |
|
629 | self.setFile() | |
638 |
|
630 | |||
639 | self.writeBlock() |
|
631 | self.writeBlock() | |
640 | self.counter += 1 |
|
632 | self.counter += 1 | |
641 |
|
633 | |||
642 | def close(self): |
|
634 | def close(self): | |
643 |
|
635 | |||
644 | if self.counter > 0: |
|
636 | if self.counter > 0: | |
645 | self.setHeader() No newline at end of file |
|
637 | self.setHeader() |
General Comments 0
You need to be logged in to leave comments.
Login now