##// END OF EJS Templates
Cleaning IO modules (base, voltaje and spectra)
jespinoza -
r1251:6d7191c1eaa6
parent child
Show More
@@ -1,12 +1,6
1 #from schainpy.model.data.jrodata import *
2 # from schainpy.model.io.jrodataIO import *
3 # from schainpy.model.proc.jroprocessing import *
4 # from schainpy.model.graphics.jroplot import *
5 # from schainpy.model.utils.jroutils import *
6 # from schainpy.serializer import *
7
1
8 from .graphics import *
2 from .graphics import *
9 from .data import *
3 from .data import *
10 from .io import *
4 from .io import *
11 from .proc import *
5 from .proc import *
12 from .utils import *
6 from .utils import *
@@ -1,810 +1,810
1
1
2 import os
2 import os
3 import sys
3 import sys
4 import zmq
4 import zmq
5 import time
5 import time
6 import numpy
6 import numpy
7 import datetime
7 import datetime
8 from functools import wraps
8 from functools import wraps
9 from threading import Thread
9 from threading import Thread
10 import matplotlib
10 import matplotlib
11
11
12 if 'BACKEND' in os.environ:
12 if 'BACKEND' in os.environ:
13 matplotlib.use(os.environ['BACKEND'])
13 matplotlib.use(os.environ['BACKEND'])
14 elif 'linux' in sys.platform:
14 elif 'linux' in sys.platform:
15 matplotlib.use("TkAgg")
15 matplotlib.use("TkAgg")
16 elif 'darwin' in sys.platform:
16 elif 'darwin' in sys.platform:
17 matplotlib.use('WxAgg')
17 matplotlib.use('WxAgg')
18 else:
18 else:
19 from schainpy.utils import log
19 from schainpy.utils import log
20 log.warning('Using default Backend="Agg"', 'INFO')
20 log.warning('Using default Backend="Agg"', 'INFO')
21 matplotlib.use('Agg')
21 matplotlib.use('Agg')
22
22
23 import matplotlib.pyplot as plt
23 import matplotlib.pyplot as plt
24 from matplotlib.patches import Polygon
24 from matplotlib.patches import Polygon
25 from mpl_toolkits.axes_grid1 import make_axes_locatable
25 from mpl_toolkits.axes_grid1 import make_axes_locatable
26 from matplotlib.ticker import FuncFormatter, LinearLocator, MultipleLocator
26 from matplotlib.ticker import FuncFormatter, LinearLocator, MultipleLocator
27
27
28 from schainpy.model.data.jrodata import PlotterData
28 from schainpy.model.data.jrodata import PlotterData
29 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
29 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
30 from schainpy.utils import log
30 from schainpy.utils import log
31
31
32 jet_values = matplotlib.pyplot.get_cmap('jet', 100)(numpy.arange(100))[10:90]
32 jet_values = matplotlib.pyplot.get_cmap('jet', 100)(numpy.arange(100))[10:90]
33 blu_values = matplotlib.pyplot.get_cmap(
33 blu_values = matplotlib.pyplot.get_cmap(
34 'seismic_r', 20)(numpy.arange(20))[10:15]
34 'seismic_r', 20)(numpy.arange(20))[10:15]
35 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list(
35 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list(
36 'jro', numpy.vstack((blu_values, jet_values)))
36 'jro', numpy.vstack((blu_values, jet_values)))
37 matplotlib.pyplot.register_cmap(cmap=ncmap)
37 matplotlib.pyplot.register_cmap(cmap=ncmap)
38
38
39 CMAPS = [plt.get_cmap(s) for s in ('jro', 'jet', 'viridis',
39 CMAPS = [plt.get_cmap(s) for s in ('jro', 'jet', 'viridis',
40 'plasma', 'inferno', 'Greys', 'seismic', 'bwr', 'coolwarm')]
40 'plasma', 'inferno', 'Greys', 'seismic', 'bwr', 'coolwarm')]
41
41
42 EARTH_RADIUS = 6.3710e3
42 EARTH_RADIUS = 6.3710e3
43
43
44 def ll2xy(lat1, lon1, lat2, lon2):
44 def ll2xy(lat1, lon1, lat2, lon2):
45
45
46 p = 0.017453292519943295
46 p = 0.017453292519943295
47 a = 0.5 - numpy.cos((lat2 - lat1) * p)/2 + numpy.cos(lat1 * p) * \
47 a = 0.5 - numpy.cos((lat2 - lat1) * p)/2 + numpy.cos(lat1 * p) * \
48 numpy.cos(lat2 * p) * (1 - numpy.cos((lon2 - lon1) * p)) / 2
48 numpy.cos(lat2 * p) * (1 - numpy.cos((lon2 - lon1) * p)) / 2
49 r = 12742 * numpy.arcsin(numpy.sqrt(a))
49 r = 12742 * numpy.arcsin(numpy.sqrt(a))
50 theta = numpy.arctan2(numpy.sin((lon2-lon1)*p)*numpy.cos(lat2*p), numpy.cos(lat1*p)
50 theta = numpy.arctan2(numpy.sin((lon2-lon1)*p)*numpy.cos(lat2*p), numpy.cos(lat1*p)
51 * numpy.sin(lat2*p)-numpy.sin(lat1*p)*numpy.cos(lat2*p)*numpy.cos((lon2-lon1)*p))
51 * numpy.sin(lat2*p)-numpy.sin(lat1*p)*numpy.cos(lat2*p)*numpy.cos((lon2-lon1)*p))
52 theta = -theta + numpy.pi/2
52 theta = -theta + numpy.pi/2
53 return r*numpy.cos(theta), r*numpy.sin(theta)
53 return r*numpy.cos(theta), r*numpy.sin(theta)
54
54
55
55
56 def km2deg(km):
56 def km2deg(km):
57 '''
57 '''
58 Convert distance in km to degrees
58 Convert distance in km to degrees
59 '''
59 '''
60
60
61 return numpy.rad2deg(km/EARTH_RADIUS)
61 return numpy.rad2deg(km/EARTH_RADIUS)
62
62
63
63
64 def figpause(interval):
64 def figpause(interval):
65 backend = plt.rcParams['backend']
65 backend = plt.rcParams['backend']
66 if backend in matplotlib.rcsetup.interactive_bk:
66 if backend in matplotlib.rcsetup.interactive_bk:
67 figManager = matplotlib._pylab_helpers.Gcf.get_active()
67 figManager = matplotlib._pylab_helpers.Gcf.get_active()
68 if figManager is not None:
68 if figManager is not None:
69 canvas = figManager.canvas
69 canvas = figManager.canvas
70 if canvas.figure.stale:
70 if canvas.figure.stale:
71 canvas.draw()
71 canvas.draw()
72 try:
72 try:
73 canvas.start_event_loop(interval)
73 canvas.start_event_loop(interval)
74 except:
74 except:
75 pass
75 pass
76 return
76 return
77
77
78
78
79 def popup(message):
79 def popup(message):
80 '''
80 '''
81 '''
81 '''
82
82
83 fig = plt.figure(figsize=(12, 8), facecolor='r')
83 fig = plt.figure(figsize=(12, 8), facecolor='r')
84 text = '\n'.join([s.strip() for s in message.split(':')])
84 text = '\n'.join([s.strip() for s in message.split(':')])
85 fig.text(0.01, 0.5, text, ha='left', va='center',
85 fig.text(0.01, 0.5, text, ha='left', va='center',
86 size='20', weight='heavy', color='w')
86 size='20', weight='heavy', color='w')
87 fig.show()
87 fig.show()
88 figpause(1000)
88 figpause(1000)
89
89
90
90
91 class Throttle(object):
91 class Throttle(object):
92 '''
92 '''
93 Decorator that prevents a function from being called more than once every
93 Decorator that prevents a function from being called more than once every
94 time period.
94 time period.
95 To create a function that cannot be called more than once a minute, but
95 To create a function that cannot be called more than once a minute, but
96 will sleep until it can be called:
96 will sleep until it can be called:
97 @Throttle(minutes=1)
97 @Throttle(minutes=1)
98 def foo():
98 def foo():
99 pass
99 pass
100
100
101 for i in range(10):
101 for i in range(10):
102 foo()
102 foo()
103 print "This function has run %s times." % i
103 print "This function has run %s times." % i
104 '''
104 '''
105
105
106 def __init__(self, seconds=0, minutes=0, hours=0):
106 def __init__(self, seconds=0, minutes=0, hours=0):
107 self.throttle_period = datetime.timedelta(
107 self.throttle_period = datetime.timedelta(
108 seconds=seconds, minutes=minutes, hours=hours
108 seconds=seconds, minutes=minutes, hours=hours
109 )
109 )
110
110
111 self.time_of_last_call = datetime.datetime.min
111 self.time_of_last_call = datetime.datetime.min
112
112
113 def __call__(self, fn):
113 def __call__(self, fn):
114 @wraps(fn)
114 @wraps(fn)
115 def wrapper(*args, **kwargs):
115 def wrapper(*args, **kwargs):
116 coerce = kwargs.pop('coerce', None)
116 coerce = kwargs.pop('coerce', None)
117 if coerce:
117 if coerce:
118 self.time_of_last_call = datetime.datetime.now()
118 self.time_of_last_call = datetime.datetime.now()
119 return fn(*args, **kwargs)
119 return fn(*args, **kwargs)
120 else:
120 else:
121 now = datetime.datetime.now()
121 now = datetime.datetime.now()
122 time_since_last_call = now - self.time_of_last_call
122 time_since_last_call = now - self.time_of_last_call
123 time_left = self.throttle_period - time_since_last_call
123 time_left = self.throttle_period - time_since_last_call
124
124
125 if time_left > datetime.timedelta(seconds=0):
125 if time_left > datetime.timedelta(seconds=0):
126 return
126 return
127
127
128 self.time_of_last_call = datetime.datetime.now()
128 self.time_of_last_call = datetime.datetime.now()
129 return fn(*args, **kwargs)
129 return fn(*args, **kwargs)
130
130
131 return wrapper
131 return wrapper
132
132
133 def apply_throttle(value):
133 def apply_throttle(value):
134
134
135 @Throttle(seconds=value)
135 @Throttle(seconds=value)
136 def fnThrottled(fn):
136 def fnThrottled(fn):
137 fn()
137 fn()
138
138
139 return fnThrottled
139 return fnThrottled
140
140
141
141
142 @MPDecorator
142 @MPDecorator
143 class Plot(Operation):
143 class Plot(Operation):
144 '''
144 '''
145 Base class for Schain plotting operations
145 Base class for Schain plotting operations
146 '''
146 '''
147
147
148 CODE = 'Figure'
148 CODE = 'Figure'
149 colormap = 'jet'
149 colormap = 'jet'
150 bgcolor = 'white'
150 bgcolor = 'white'
151 __missing = 1E30
151 __missing = 1E30
152
152
153 __attrs__ = ['show', 'save', 'xmin', 'xmax', 'ymin', 'ymax', 'zmin', 'zmax',
153 __attrs__ = ['show', 'save', 'xmin', 'xmax', 'ymin', 'ymax', 'zmin', 'zmax',
154 'zlimits', 'xlabel', 'ylabel', 'xaxis', 'cb_label', 'title',
154 'zlimits', 'xlabel', 'ylabel', 'xaxis', 'cb_label', 'title',
155 'colorbar', 'bgcolor', 'width', 'height', 'localtime', 'oneFigure',
155 'colorbar', 'bgcolor', 'width', 'height', 'localtime', 'oneFigure',
156 'showprofile', 'decimation', 'pause']
156 'showprofile', 'decimation', 'pause']
157
157
158 def __init__(self):
158 def __init__(self):
159
159
160 Operation.__init__(self)
160 Operation.__init__(self)
161 self.isConfig = False
161 self.isConfig = False
162 self.isPlotConfig = False
162 self.isPlotConfig = False
163 self.save_counter = 1
163 self.save_counter = 1
164 self.sender_counter = 1
164 self.sender_counter = 1
165 self.data = None
165 self.data = None
166
166
167 def __fmtTime(self, x, pos):
167 def __fmtTime(self, x, pos):
168 '''
168 '''
169 '''
169 '''
170
170
171 return '{}'.format(self.getDateTime(x).strftime('%H:%M'))
171 return '{}'.format(self.getDateTime(x).strftime('%H:%M'))
172
172
173 def __setup(self, **kwargs):
173 def __setup(self, **kwargs):
174 '''
174 '''
175 Initialize variables
175 Initialize variables
176 '''
176 '''
177
177
178 self.figures = []
178 self.figures = []
179 self.axes = []
179 self.axes = []
180 self.cb_axes = []
180 self.cb_axes = []
181 self.localtime = kwargs.pop('localtime', True)
181 self.localtime = kwargs.pop('localtime', True)
182 self.show = kwargs.get('show', True)
182 self.show = kwargs.get('show', True)
183 self.save = kwargs.get('save', False)
183 self.save = kwargs.get('save', False)
184 self.save_period = kwargs.get('save_period', 2)
184 self.save_period = kwargs.get('save_period', 1)
185 self.ftp = kwargs.get('ftp', False)
185 self.ftp = kwargs.get('ftp', False)
186 self.colormap = kwargs.get('colormap', self.colormap)
186 self.colormap = kwargs.get('colormap', self.colormap)
187 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
187 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
188 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
188 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
189 self.colormaps = kwargs.get('colormaps', None)
189 self.colormaps = kwargs.get('colormaps', None)
190 self.bgcolor = kwargs.get('bgcolor', self.bgcolor)
190 self.bgcolor = kwargs.get('bgcolor', self.bgcolor)
191 self.showprofile = kwargs.get('showprofile', False)
191 self.showprofile = kwargs.get('showprofile', False)
192 self.title = kwargs.get('wintitle', self.CODE.upper())
192 self.title = kwargs.get('wintitle', self.CODE.upper())
193 self.cb_label = kwargs.get('cb_label', None)
193 self.cb_label = kwargs.get('cb_label', None)
194 self.cb_labels = kwargs.get('cb_labels', None)
194 self.cb_labels = kwargs.get('cb_labels', None)
195 self.labels = kwargs.get('labels', None)
195 self.labels = kwargs.get('labels', None)
196 self.xaxis = kwargs.get('xaxis', 'frequency')
196 self.xaxis = kwargs.get('xaxis', 'frequency')
197 self.zmin = kwargs.get('zmin', None)
197 self.zmin = kwargs.get('zmin', None)
198 self.zmax = kwargs.get('zmax', None)
198 self.zmax = kwargs.get('zmax', None)
199 self.zlimits = kwargs.get('zlimits', None)
199 self.zlimits = kwargs.get('zlimits', None)
200 self.xmin = kwargs.get('xmin', None)
200 self.xmin = kwargs.get('xmin', None)
201 self.xmax = kwargs.get('xmax', None)
201 self.xmax = kwargs.get('xmax', None)
202 self.xrange = kwargs.get('xrange', 24)
202 self.xrange = kwargs.get('xrange', 24)
203 self.xscale = kwargs.get('xscale', None)
203 self.xscale = kwargs.get('xscale', None)
204 self.ymin = kwargs.get('ymin', None)
204 self.ymin = kwargs.get('ymin', None)
205 self.ymax = kwargs.get('ymax', None)
205 self.ymax = kwargs.get('ymax', None)
206 self.yscale = kwargs.get('yscale', None)
206 self.yscale = kwargs.get('yscale', None)
207 self.xlabel = kwargs.get('xlabel', None)
207 self.xlabel = kwargs.get('xlabel', None)
208 self.decimation = kwargs.get('decimation', None)
208 self.decimation = kwargs.get('decimation', None)
209 self.showSNR = kwargs.get('showSNR', False)
209 self.showSNR = kwargs.get('showSNR', False)
210 self.oneFigure = kwargs.get('oneFigure', True)
210 self.oneFigure = kwargs.get('oneFigure', True)
211 self.width = kwargs.get('width', None)
211 self.width = kwargs.get('width', None)
212 self.height = kwargs.get('height', None)
212 self.height = kwargs.get('height', None)
213 self.colorbar = kwargs.get('colorbar', True)
213 self.colorbar = kwargs.get('colorbar', True)
214 self.factors = kwargs.get('factors', [1, 1, 1, 1, 1, 1, 1, 1])
214 self.factors = kwargs.get('factors', [1, 1, 1, 1, 1, 1, 1, 1])
215 self.channels = kwargs.get('channels', None)
215 self.channels = kwargs.get('channels', None)
216 self.titles = kwargs.get('titles', [])
216 self.titles = kwargs.get('titles', [])
217 self.polar = False
217 self.polar = False
218 self.type = kwargs.get('type', 'iq')
218 self.type = kwargs.get('type', 'iq')
219 self.grid = kwargs.get('grid', False)
219 self.grid = kwargs.get('grid', False)
220 self.pause = kwargs.get('pause', False)
220 self.pause = kwargs.get('pause', False)
221 self.save_labels = kwargs.get('save_labels', None)
221 self.save_labels = kwargs.get('save_labels', None)
222 self.realtime = kwargs.get('realtime', True)
222 self.realtime = kwargs.get('realtime', True)
223 self.buffering = kwargs.get('buffering', True)
223 self.buffering = kwargs.get('buffering', True)
224 self.throttle = kwargs.get('throttle', 2)
224 self.throttle = kwargs.get('throttle', 2)
225 self.exp_code = kwargs.get('exp_code', None)
225 self.exp_code = kwargs.get('exp_code', None)
226 self.plot_server = kwargs.get('plot_server', False)
226 self.plot_server = kwargs.get('plot_server', False)
227 self.sender_period = kwargs.get('sender_period', 1)
227 self.sender_period = kwargs.get('sender_period', 1)
228 self.__throttle_plot = apply_throttle(self.throttle)
228 self.__throttle_plot = apply_throttle(self.throttle)
229 self.data = PlotterData(
229 self.data = PlotterData(
230 self.CODE, self.throttle, self.exp_code, self.buffering, snr=self.showSNR)
230 self.CODE, self.throttle, self.exp_code, self.buffering, snr=self.showSNR)
231
231
232 if self.plot_server:
232 if self.plot_server:
233 if not self.plot_server.startswith('tcp://'):
233 if not self.plot_server.startswith('tcp://'):
234 self.plot_server = 'tcp://{}'.format(self.plot_server)
234 self.plot_server = 'tcp://{}'.format(self.plot_server)
235 log.success(
235 log.success(
236 'Sending to server: {}'.format(self.plot_server),
236 'Sending to server: {}'.format(self.plot_server),
237 self.name
237 self.name
238 )
238 )
239 if 'plot_name' in kwargs:
239 if 'plot_name' in kwargs:
240 self.plot_name = kwargs['plot_name']
240 self.plot_name = kwargs['plot_name']
241
241
242 def __setup_plot(self):
242 def __setup_plot(self):
243 '''
243 '''
244 Common setup for all figures, here figures and axes are created
244 Common setup for all figures, here figures and axes are created
245 '''
245 '''
246
246
247 self.setup()
247 self.setup()
248
248
249 self.time_label = 'LT' if self.localtime else 'UTC'
249 self.time_label = 'LT' if self.localtime else 'UTC'
250
250
251 if self.width is None:
251 if self.width is None:
252 self.width = 8
252 self.width = 8
253
253
254 self.figures = []
254 self.figures = []
255 self.axes = []
255 self.axes = []
256 self.cb_axes = []
256 self.cb_axes = []
257 self.pf_axes = []
257 self.pf_axes = []
258 self.cmaps = []
258 self.cmaps = []
259
259
260 size = '15%' if self.ncols == 1 else '30%'
260 size = '15%' if self.ncols == 1 else '30%'
261 pad = '4%' if self.ncols == 1 else '8%'
261 pad = '4%' if self.ncols == 1 else '8%'
262
262
263 if self.oneFigure:
263 if self.oneFigure:
264 if self.height is None:
264 if self.height is None:
265 self.height = 1.4 * self.nrows + 1
265 self.height = 1.4 * self.nrows + 1
266 fig = plt.figure(figsize=(self.width, self.height),
266 fig = plt.figure(figsize=(self.width, self.height),
267 edgecolor='k',
267 edgecolor='k',
268 facecolor='w')
268 facecolor='w')
269 self.figures.append(fig)
269 self.figures.append(fig)
270 for n in range(self.nplots):
270 for n in range(self.nplots):
271 ax = fig.add_subplot(self.nrows, self.ncols,
271 ax = fig.add_subplot(self.nrows, self.ncols,
272 n + 1, polar=self.polar)
272 n + 1, polar=self.polar)
273 ax.tick_params(labelsize=8)
273 ax.tick_params(labelsize=8)
274 ax.firsttime = True
274 ax.firsttime = True
275 ax.index = 0
275 ax.index = 0
276 ax.press = None
276 ax.press = None
277 self.axes.append(ax)
277 self.axes.append(ax)
278 if self.showprofile:
278 if self.showprofile:
279 cax = self.__add_axes(ax, size=size, pad=pad)
279 cax = self.__add_axes(ax, size=size, pad=pad)
280 cax.tick_params(labelsize=8)
280 cax.tick_params(labelsize=8)
281 self.pf_axes.append(cax)
281 self.pf_axes.append(cax)
282 else:
282 else:
283 if self.height is None:
283 if self.height is None:
284 self.height = 3
284 self.height = 3
285 for n in range(self.nplots):
285 for n in range(self.nplots):
286 fig = plt.figure(figsize=(self.width, self.height),
286 fig = plt.figure(figsize=(self.width, self.height),
287 edgecolor='k',
287 edgecolor='k',
288 facecolor='w')
288 facecolor='w')
289 ax = fig.add_subplot(1, 1, 1, polar=self.polar)
289 ax = fig.add_subplot(1, 1, 1, polar=self.polar)
290 ax.tick_params(labelsize=8)
290 ax.tick_params(labelsize=8)
291 ax.firsttime = True
291 ax.firsttime = True
292 ax.index = 0
292 ax.index = 0
293 ax.press = None
293 ax.press = None
294 self.figures.append(fig)
294 self.figures.append(fig)
295 self.axes.append(ax)
295 self.axes.append(ax)
296 if self.showprofile:
296 if self.showprofile:
297 cax = self.__add_axes(ax, size=size, pad=pad)
297 cax = self.__add_axes(ax, size=size, pad=pad)
298 cax.tick_params(labelsize=8)
298 cax.tick_params(labelsize=8)
299 self.pf_axes.append(cax)
299 self.pf_axes.append(cax)
300
300
301 for n in range(self.nrows):
301 for n in range(self.nrows):
302 if self.colormaps is not None:
302 if self.colormaps is not None:
303 cmap = plt.get_cmap(self.colormaps[n])
303 cmap = plt.get_cmap(self.colormaps[n])
304 else:
304 else:
305 cmap = plt.get_cmap(self.colormap)
305 cmap = plt.get_cmap(self.colormap)
306 cmap.set_bad(self.bgcolor, 1.)
306 cmap.set_bad(self.bgcolor, 1.)
307 self.cmaps.append(cmap)
307 self.cmaps.append(cmap)
308
308
309 for fig in self.figures:
309 for fig in self.figures:
310 fig.canvas.mpl_connect('key_press_event', self.OnKeyPress)
310 fig.canvas.mpl_connect('key_press_event', self.OnKeyPress)
311 fig.canvas.mpl_connect('scroll_event', self.OnBtnScroll)
311 fig.canvas.mpl_connect('scroll_event', self.OnBtnScroll)
312 fig.canvas.mpl_connect('button_press_event', self.onBtnPress)
312 fig.canvas.mpl_connect('button_press_event', self.onBtnPress)
313 fig.canvas.mpl_connect('motion_notify_event', self.onMotion)
313 fig.canvas.mpl_connect('motion_notify_event', self.onMotion)
314 fig.canvas.mpl_connect('button_release_event', self.onBtnRelease)
314 fig.canvas.mpl_connect('button_release_event', self.onBtnRelease)
315
315
316 def OnKeyPress(self, event):
316 def OnKeyPress(self, event):
317 '''
317 '''
318 Event for pressing keys (up, down) change colormap
318 Event for pressing keys (up, down) change colormap
319 '''
319 '''
320 ax = event.inaxes
320 ax = event.inaxes
321 if ax in self.axes:
321 if ax in self.axes:
322 if event.key == 'down':
322 if event.key == 'down':
323 ax.index += 1
323 ax.index += 1
324 elif event.key == 'up':
324 elif event.key == 'up':
325 ax.index -= 1
325 ax.index -= 1
326 if ax.index < 0:
326 if ax.index < 0:
327 ax.index = len(CMAPS) - 1
327 ax.index = len(CMAPS) - 1
328 elif ax.index == len(CMAPS):
328 elif ax.index == len(CMAPS):
329 ax.index = 0
329 ax.index = 0
330 cmap = CMAPS[ax.index]
330 cmap = CMAPS[ax.index]
331 ax.cbar.set_cmap(cmap)
331 ax.cbar.set_cmap(cmap)
332 ax.cbar.draw_all()
332 ax.cbar.draw_all()
333 ax.plt.set_cmap(cmap)
333 ax.plt.set_cmap(cmap)
334 ax.cbar.patch.figure.canvas.draw()
334 ax.cbar.patch.figure.canvas.draw()
335 self.colormap = cmap.name
335 self.colormap = cmap.name
336
336
337 def OnBtnScroll(self, event):
337 def OnBtnScroll(self, event):
338 '''
338 '''
339 Event for scrolling, scale figure
339 Event for scrolling, scale figure
340 '''
340 '''
341 cb_ax = event.inaxes
341 cb_ax = event.inaxes
342 if cb_ax in [ax.cbar.ax for ax in self.axes if ax.cbar]:
342 if cb_ax in [ax.cbar.ax for ax in self.axes if ax.cbar]:
343 ax = [ax for ax in self.axes if cb_ax == ax.cbar.ax][0]
343 ax = [ax for ax in self.axes if cb_ax == ax.cbar.ax][0]
344 pt = ax.cbar.ax.bbox.get_points()[:, 1]
344 pt = ax.cbar.ax.bbox.get_points()[:, 1]
345 nrm = ax.cbar.norm
345 nrm = ax.cbar.norm
346 vmin, vmax, p0, p1, pS = (
346 vmin, vmax, p0, p1, pS = (
347 nrm.vmin, nrm.vmax, pt[0], pt[1], event.y)
347 nrm.vmin, nrm.vmax, pt[0], pt[1], event.y)
348 scale = 2 if event.step == 1 else 0.5
348 scale = 2 if event.step == 1 else 0.5
349 point = vmin + (vmax - vmin) / (p1 - p0) * (pS - p0)
349 point = vmin + (vmax - vmin) / (p1 - p0) * (pS - p0)
350 ax.cbar.norm.vmin = point - scale * (point - vmin)
350 ax.cbar.norm.vmin = point - scale * (point - vmin)
351 ax.cbar.norm.vmax = point - scale * (point - vmax)
351 ax.cbar.norm.vmax = point - scale * (point - vmax)
352 ax.plt.set_norm(ax.cbar.norm)
352 ax.plt.set_norm(ax.cbar.norm)
353 ax.cbar.draw_all()
353 ax.cbar.draw_all()
354 ax.cbar.patch.figure.canvas.draw()
354 ax.cbar.patch.figure.canvas.draw()
355
355
356 def onBtnPress(self, event):
356 def onBtnPress(self, event):
357 '''
357 '''
358 Event for mouse button press
358 Event for mouse button press
359 '''
359 '''
360 cb_ax = event.inaxes
360 cb_ax = event.inaxes
361 if cb_ax is None:
361 if cb_ax is None:
362 return
362 return
363
363
364 if cb_ax in [ax.cbar.ax for ax in self.axes if ax.cbar]:
364 if cb_ax in [ax.cbar.ax for ax in self.axes if ax.cbar]:
365 cb_ax.press = event.x, event.y
365 cb_ax.press = event.x, event.y
366 else:
366 else:
367 cb_ax.press = None
367 cb_ax.press = None
368
368
369 def onMotion(self, event):
369 def onMotion(self, event):
370 '''
370 '''
371 Event for move inside colorbar
371 Event for move inside colorbar
372 '''
372 '''
373 cb_ax = event.inaxes
373 cb_ax = event.inaxes
374 if cb_ax is None:
374 if cb_ax is None:
375 return
375 return
376 if cb_ax not in [ax.cbar.ax for ax in self.axes if ax.cbar]:
376 if cb_ax not in [ax.cbar.ax for ax in self.axes if ax.cbar]:
377 return
377 return
378 if cb_ax.press is None:
378 if cb_ax.press is None:
379 return
379 return
380
380
381 ax = [ax for ax in self.axes if cb_ax == ax.cbar.ax][0]
381 ax = [ax for ax in self.axes if cb_ax == ax.cbar.ax][0]
382 xprev, yprev = cb_ax.press
382 xprev, yprev = cb_ax.press
383 dx = event.x - xprev
383 dx = event.x - xprev
384 dy = event.y - yprev
384 dy = event.y - yprev
385 cb_ax.press = event.x, event.y
385 cb_ax.press = event.x, event.y
386 scale = ax.cbar.norm.vmax - ax.cbar.norm.vmin
386 scale = ax.cbar.norm.vmax - ax.cbar.norm.vmin
387 perc = 0.03
387 perc = 0.03
388
388
389 if event.button == 1:
389 if event.button == 1:
390 ax.cbar.norm.vmin -= (perc * scale) * numpy.sign(dy)
390 ax.cbar.norm.vmin -= (perc * scale) * numpy.sign(dy)
391 ax.cbar.norm.vmax -= (perc * scale) * numpy.sign(dy)
391 ax.cbar.norm.vmax -= (perc * scale) * numpy.sign(dy)
392 elif event.button == 3:
392 elif event.button == 3:
393 ax.cbar.norm.vmin -= (perc * scale) * numpy.sign(dy)
393 ax.cbar.norm.vmin -= (perc * scale) * numpy.sign(dy)
394 ax.cbar.norm.vmax += (perc * scale) * numpy.sign(dy)
394 ax.cbar.norm.vmax += (perc * scale) * numpy.sign(dy)
395
395
396 ax.cbar.draw_all()
396 ax.cbar.draw_all()
397 ax.plt.set_norm(ax.cbar.norm)
397 ax.plt.set_norm(ax.cbar.norm)
398 ax.cbar.patch.figure.canvas.draw()
398 ax.cbar.patch.figure.canvas.draw()
399
399
400 def onBtnRelease(self, event):
400 def onBtnRelease(self, event):
401 '''
401 '''
402 Event for mouse button release
402 Event for mouse button release
403 '''
403 '''
404 cb_ax = event.inaxes
404 cb_ax = event.inaxes
405 if cb_ax is not None:
405 if cb_ax is not None:
406 cb_ax.press = None
406 cb_ax.press = None
407
407
408 def __add_axes(self, ax, size='30%', pad='8%'):
408 def __add_axes(self, ax, size='30%', pad='8%'):
409 '''
409 '''
410 Add new axes to the given figure
410 Add new axes to the given figure
411 '''
411 '''
412 divider = make_axes_locatable(ax)
412 divider = make_axes_locatable(ax)
413 nax = divider.new_horizontal(size=size, pad=pad)
413 nax = divider.new_horizontal(size=size, pad=pad)
414 ax.figure.add_axes(nax)
414 ax.figure.add_axes(nax)
415 return nax
415 return nax
416
416
417 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
417 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
418 '''
418 '''
419 Create a masked array for missing data
419 Create a masked array for missing data
420 '''
420 '''
421 if x_buffer.shape[0] < 2:
421 if x_buffer.shape[0] < 2:
422 return x_buffer, y_buffer, z_buffer
422 return x_buffer, y_buffer, z_buffer
423
423
424 deltas = x_buffer[1:] - x_buffer[0:-1]
424 deltas = x_buffer[1:] - x_buffer[0:-1]
425 x_median = numpy.median(deltas)
425 x_median = numpy.median(deltas)
426
426
427 index = numpy.where(deltas > 5 * x_median)
427 index = numpy.where(deltas > 5 * x_median)
428
428
429 if len(index[0]) != 0:
429 if len(index[0]) != 0:
430 z_buffer[::, index[0], ::] = self.__missing
430 z_buffer[::, index[0], ::] = self.__missing
431 z_buffer = numpy.ma.masked_inside(z_buffer,
431 z_buffer = numpy.ma.masked_inside(z_buffer,
432 0.99 * self.__missing,
432 0.99 * self.__missing,
433 1.01 * self.__missing)
433 1.01 * self.__missing)
434
434
435 return x_buffer, y_buffer, z_buffer
435 return x_buffer, y_buffer, z_buffer
436
436
437 def decimate(self):
437 def decimate(self):
438
438
439 # dx = int(len(self.x)/self.__MAXNUMX) + 1
439 # dx = int(len(self.x)/self.__MAXNUMX) + 1
440 dy = int(len(self.y) / self.decimation) + 1
440 dy = int(len(self.y) / self.decimation) + 1
441
441
442 # x = self.x[::dx]
442 # x = self.x[::dx]
443 x = self.x
443 x = self.x
444 y = self.y[::dy]
444 y = self.y[::dy]
445 z = self.z[::, ::, ::dy]
445 z = self.z[::, ::, ::dy]
446
446
447 return x, y, z
447 return x, y, z
448
448
449 def format(self):
449 def format(self):
450 '''
450 '''
451 Set min and max values, labels, ticks and titles
451 Set min and max values, labels, ticks and titles
452 '''
452 '''
453
453
454 if self.xmin is None:
454 if self.xmin is None:
455 xmin = self.data.min_time
455 xmin = self.data.min_time
456 else:
456 else:
457 if self.xaxis is 'time':
457 if self.xaxis is 'time':
458 dt = self.getDateTime(self.data.min_time)
458 dt = self.getDateTime(self.data.min_time)
459 xmin = (dt.replace(hour=int(self.xmin), minute=0, second=0) -
459 xmin = (dt.replace(hour=int(self.xmin), minute=0, second=0) -
460 datetime.datetime(1970, 1, 1)).total_seconds()
460 datetime.datetime(1970, 1, 1)).total_seconds()
461 if self.data.localtime:
461 if self.data.localtime:
462 xmin += time.timezone
462 xmin += time.timezone
463 else:
463 else:
464 xmin = self.xmin
464 xmin = self.xmin
465
465
466 if self.xmax is None:
466 if self.xmax is None:
467 xmax = xmin + self.xrange * 60 * 60
467 xmax = xmin + self.xrange * 60 * 60
468 else:
468 else:
469 if self.xaxis is 'time':
469 if self.xaxis is 'time':
470 dt = self.getDateTime(self.data.max_time)
470 dt = self.getDateTime(self.data.max_time)
471 xmax = (dt.replace(hour=int(self.xmax), minute=59, second=59) -
471 xmax = (dt.replace(hour=int(self.xmax), minute=59, second=59) -
472 datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=1)).total_seconds()
472 datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=1)).total_seconds()
473 if self.data.localtime:
473 if self.data.localtime:
474 xmax += time.timezone
474 xmax += time.timezone
475 else:
475 else:
476 xmax = self.xmax
476 xmax = self.xmax
477
477
478 ymin = self.ymin if self.ymin else numpy.nanmin(self.y)
478 ymin = self.ymin if self.ymin else numpy.nanmin(self.y)
479 ymax = self.ymax if self.ymax else numpy.nanmax(self.y)
479 ymax = self.ymax if self.ymax else numpy.nanmax(self.y)
480 #Y = numpy.array([1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000])
480 #Y = numpy.array([1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000])
481
481
482 #i = 1 if numpy.where(
482 #i = 1 if numpy.where(
483 # abs(ymax-ymin) <= Y)[0][0] < 0 else numpy.where(abs(ymax-ymin) <= Y)[0][0]
483 # abs(ymax-ymin) <= Y)[0][0] < 0 else numpy.where(abs(ymax-ymin) <= Y)[0][0]
484 #ystep = Y[i] / 10.
484 #ystep = Y[i] / 10.
485 dig = int(numpy.log10(ymax))
485 dig = int(numpy.log10(ymax))
486 if dig == 0:
486 if dig == 0:
487 digD = len(str(ymax)) - 2
487 digD = len(str(ymax)) - 2
488 ydec = ymax*(10**digD)
488 ydec = ymax*(10**digD)
489
489
490 dig = int(numpy.log10(ydec))
490 dig = int(numpy.log10(ydec))
491 ystep = ((ydec + (10**(dig)))//10**(dig))*(10**(dig))
491 ystep = ((ydec + (10**(dig)))//10**(dig))*(10**(dig))
492 ystep = ystep/5
492 ystep = ystep/5
493 ystep = ystep/(10**digD)
493 ystep = ystep/(10**digD)
494
494
495 else:
495 else:
496 ystep = ((ymax + (10**(dig)))//10**(dig))*(10**(dig))
496 ystep = ((ymax + (10**(dig)))//10**(dig))*(10**(dig))
497 ystep = ystep/5
497 ystep = ystep/5
498
498
499 if self.xaxis is not 'time':
499 if self.xaxis is not 'time':
500
500
501 dig = int(numpy.log10(xmax))
501 dig = int(numpy.log10(xmax))
502
502
503 if dig <= 0:
503 if dig <= 0:
504 digD = len(str(xmax)) - 2
504 digD = len(str(xmax)) - 2
505 xdec = xmax*(10**digD)
505 xdec = xmax*(10**digD)
506
506
507 dig = int(numpy.log10(xdec))
507 dig = int(numpy.log10(xdec))
508 xstep = ((xdec + (10**(dig)))//10**(dig))*(10**(dig))
508 xstep = ((xdec + (10**(dig)))//10**(dig))*(10**(dig))
509 xstep = xstep*0.5
509 xstep = xstep*0.5
510 xstep = xstep/(10**digD)
510 xstep = xstep/(10**digD)
511
511
512 else:
512 else:
513 xstep = ((xmax + (10**(dig)))//10**(dig))*(10**(dig))
513 xstep = ((xmax + (10**(dig)))//10**(dig))*(10**(dig))
514 xstep = xstep/5
514 xstep = xstep/5
515
515
516 for n, ax in enumerate(self.axes):
516 for n, ax in enumerate(self.axes):
517 if ax.firsttime:
517 if ax.firsttime:
518 ax.set_facecolor(self.bgcolor)
518 ax.set_facecolor(self.bgcolor)
519 ax.yaxis.set_major_locator(MultipleLocator(ystep))
519 ax.yaxis.set_major_locator(MultipleLocator(ystep))
520 if self.xscale:
520 if self.xscale:
521 ax.xaxis.set_major_formatter(FuncFormatter(
521 ax.xaxis.set_major_formatter(FuncFormatter(
522 lambda x, pos: '{0:g}'.format(x*self.xscale)))
522 lambda x, pos: '{0:g}'.format(x*self.xscale)))
523 if self.xscale:
523 if self.xscale:
524 ax.yaxis.set_major_formatter(FuncFormatter(
524 ax.yaxis.set_major_formatter(FuncFormatter(
525 lambda x, pos: '{0:g}'.format(x*self.yscale)))
525 lambda x, pos: '{0:g}'.format(x*self.yscale)))
526 if self.xaxis is 'time':
526 if self.xaxis is 'time':
527 ax.xaxis.set_major_formatter(FuncFormatter(self.__fmtTime))
527 ax.xaxis.set_major_formatter(FuncFormatter(self.__fmtTime))
528 ax.xaxis.set_major_locator(LinearLocator(9))
528 ax.xaxis.set_major_locator(LinearLocator(9))
529 else:
529 else:
530 ax.xaxis.set_major_locator(MultipleLocator(xstep))
530 ax.xaxis.set_major_locator(MultipleLocator(xstep))
531 if self.xlabel is not None:
531 if self.xlabel is not None:
532 ax.set_xlabel(self.xlabel)
532 ax.set_xlabel(self.xlabel)
533 ax.set_ylabel(self.ylabel)
533 ax.set_ylabel(self.ylabel)
534 ax.firsttime = False
534 ax.firsttime = False
535 if self.showprofile:
535 if self.showprofile:
536 self.pf_axes[n].set_ylim(ymin, ymax)
536 self.pf_axes[n].set_ylim(ymin, ymax)
537 self.pf_axes[n].set_xlim(self.zmin, self.zmax)
537 self.pf_axes[n].set_xlim(self.zmin, self.zmax)
538 self.pf_axes[n].set_xlabel('dB')
538 self.pf_axes[n].set_xlabel('dB')
539 self.pf_axes[n].grid(b=True, axis='x')
539 self.pf_axes[n].grid(b=True, axis='x')
540 [tick.set_visible(False)
540 [tick.set_visible(False)
541 for tick in self.pf_axes[n].get_yticklabels()]
541 for tick in self.pf_axes[n].get_yticklabels()]
542 if self.colorbar:
542 if self.colorbar:
543 ax.cbar = plt.colorbar(
543 ax.cbar = plt.colorbar(
544 ax.plt, ax=ax, fraction=0.05, pad=0.02, aspect=10)
544 ax.plt, ax=ax, fraction=0.05, pad=0.02, aspect=10)
545 ax.cbar.ax.tick_params(labelsize=8)
545 ax.cbar.ax.tick_params(labelsize=8)
546 ax.cbar.ax.press = None
546 ax.cbar.ax.press = None
547 if self.cb_label:
547 if self.cb_label:
548 ax.cbar.set_label(self.cb_label, size=8)
548 ax.cbar.set_label(self.cb_label, size=8)
549 elif self.cb_labels:
549 elif self.cb_labels:
550 ax.cbar.set_label(self.cb_labels[n], size=8)
550 ax.cbar.set_label(self.cb_labels[n], size=8)
551 else:
551 else:
552 ax.cbar = None
552 ax.cbar = None
553 if self.grid:
553 if self.grid:
554 ax.grid(True)
554 ax.grid(True)
555
555
556 if not self.polar:
556 if not self.polar:
557 ax.set_xlim(xmin, xmax)
557 ax.set_xlim(xmin, xmax)
558 ax.set_ylim(ymin, ymax)
558 ax.set_ylim(ymin, ymax)
559 ax.set_title('{} {} {}'.format(
559 ax.set_title('{} {} {}'.format(
560 self.titles[n],
560 self.titles[n],
561 self.getDateTime(self.data.max_time).strftime(
561 self.getDateTime(self.data.max_time).strftime(
562 '%Y-%m-%d %H:%M:%S'),
562 '%Y-%m-%d %H:%M:%S'),
563 self.time_label),
563 self.time_label),
564 size=8)
564 size=8)
565 else:
565 else:
566 ax.set_title('{}'.format(self.titles[n]), size=8)
566 ax.set_title('{}'.format(self.titles[n]), size=8)
567 ax.set_ylim(0, 90)
567 ax.set_ylim(0, 90)
568 ax.set_yticks(numpy.arange(0, 90, 20))
568 ax.set_yticks(numpy.arange(0, 90, 20))
569 ax.yaxis.labelpad = 40
569 ax.yaxis.labelpad = 40
570
570
571 def clear_figures(self):
571 def clear_figures(self):
572 '''
572 '''
573 Reset axes for redraw plots
573 Reset axes for redraw plots
574 '''
574 '''
575
575
576 for ax in self.axes:
576 for ax in self.axes:
577 ax.clear()
577 ax.clear()
578 ax.firsttime = True
578 ax.firsttime = True
579 if ax.cbar:
579 if ax.cbar:
580 ax.cbar.remove()
580 ax.cbar.remove()
581
581
582 def __plot(self):
582 def __plot(self):
583 '''
583 '''
584 Main function to plot, format and save figures
584 Main function to plot, format and save figures
585 '''
585 '''
586
586
587 try:
587 try:
588 self.plot()
588 self.plot()
589 self.format()
589 self.format()
590 except Exception as e:
590 except Exception as e:
591 log.warning('{} Plot could not be updated... check data'.format(
591 log.warning('{} Plot could not be updated... check data'.format(
592 self.CODE), self.name)
592 self.CODE), self.name)
593 log.error(str(e), '')
593 log.error(str(e), '')
594 return
594 return
595
595
596 for n, fig in enumerate(self.figures):
596 for n, fig in enumerate(self.figures):
597 if self.nrows == 0 or self.nplots == 0:
597 if self.nrows == 0 or self.nplots == 0:
598 log.warning('No data', self.name)
598 log.warning('No data', self.name)
599 fig.text(0.5, 0.5, 'No Data', fontsize='large', ha='center')
599 fig.text(0.5, 0.5, 'No Data', fontsize='large', ha='center')
600 fig.canvas.manager.set_window_title(self.CODE)
600 fig.canvas.manager.set_window_title(self.CODE)
601 continue
601 continue
602
602
603 fig.tight_layout()
603 fig.tight_layout()
604 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
604 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
605 self.getDateTime(self.data.max_time).strftime('%Y/%m/%d')))
605 self.getDateTime(self.data.max_time).strftime('%Y/%m/%d')))
606 fig.canvas.draw()
606 fig.canvas.draw()
607 if self.show:
607 if self.show:
608 fig.show()
608 fig.show()
609 figpause(0.1)
609 figpause(0.1)
610
610
611 if self.save:
611 if self.save:
612 self.save_figure(n)
612 self.save_figure(n)
613
613
614 if self.plot_server:
614 if self.plot_server:
615 self.send_to_server()
615 self.send_to_server()
616 # t = Thread(target=self.send_to_server)
616 # t = Thread(target=self.send_to_server)
617 # t.start()
617 # t.start()
618
618
619 def save_figure(self, n):
619 def save_figure(self, n):
620 '''
620 '''
621 '''
621 '''
622
622
623 if self.save_counter < self.save_period:
623 if self.save_counter < self.save_period:
624 self.save_counter += 1
624 self.save_counter += 1
625 return
625 return
626
626
627 self.save_counter = 1
627 self.save_counter = 1
628
628
629 fig = self.figures[n]
629 fig = self.figures[n]
630
630
631 if self.save_labels:
631 if self.save_labels:
632 labels = self.save_labels
632 labels = self.save_labels
633 else:
633 else:
634 labels = list(range(self.nrows))
634 labels = list(range(self.nrows))
635
635
636 if self.oneFigure:
636 if self.oneFigure:
637 label = ''
637 label = ''
638 else:
638 else:
639 label = '-{}'.format(labels[n])
639 label = '-{}'.format(labels[n])
640 figname = os.path.join(
640 figname = os.path.join(
641 self.save,
641 self.save,
642 self.CODE,
642 self.CODE,
643 '{}{}_{}.png'.format(
643 '{}{}_{}.png'.format(
644 self.CODE,
644 self.CODE,
645 label,
645 label,
646 self.getDateTime(self.data.max_time).strftime(
646 self.getDateTime(self.data.max_time).strftime(
647 '%Y%m%d_%H%M%S'
647 '%Y%m%d_%H%M%S'
648 ),
648 ),
649 )
649 )
650 )
650 )
651 log.log('Saving figure: {}'.format(figname), self.name)
651 log.log('Saving figure: {}'.format(figname), self.name)
652 if not os.path.isdir(os.path.dirname(figname)):
652 if not os.path.isdir(os.path.dirname(figname)):
653 os.makedirs(os.path.dirname(figname))
653 os.makedirs(os.path.dirname(figname))
654 fig.savefig(figname)
654 fig.savefig(figname)
655
655
656 if self.realtime:
656 if self.realtime:
657 figname = os.path.join(
657 figname = os.path.join(
658 self.save,
658 self.save,
659 '{}{}_{}.png'.format(
659 '{}{}_{}.png'.format(
660 self.CODE,
660 self.CODE,
661 label,
661 label,
662 self.getDateTime(self.data.min_time).strftime(
662 self.getDateTime(self.data.min_time).strftime(
663 '%Y%m%d'
663 '%Y%m%d'
664 ),
664 ),
665 )
665 )
666 )
666 )
667 fig.savefig(figname)
667 fig.savefig(figname)
668
668
669 def send_to_server(self):
669 def send_to_server(self):
670 '''
670 '''
671 '''
671 '''
672
672
673 if self.sender_counter < self.sender_period:
673 if self.sender_counter < self.sender_period:
674 self.sender_counter += 1
674 self.sender_counter += 1
675 return
675 return
676
676
677 self.sender_counter = 1
677 self.sender_counter = 1
678 self.data.meta['titles'] = self.titles
678 self.data.meta['titles'] = self.titles
679 retries = 2
679 retries = 2
680 while True:
680 while True:
681 self.socket.send_string(self.data.jsonify(self.plot_name, self.plot_type))
681 self.socket.send_string(self.data.jsonify(self.plot_name, self.plot_type))
682 socks = dict(self.poll.poll(5000))
682 socks = dict(self.poll.poll(5000))
683 if socks.get(self.socket) == zmq.POLLIN:
683 if socks.get(self.socket) == zmq.POLLIN:
684 reply = self.socket.recv_string()
684 reply = self.socket.recv_string()
685 if reply == 'ok':
685 if reply == 'ok':
686 log.log("Response from server ok", self.name)
686 log.log("Response from server ok", self.name)
687 break
687 break
688 else:
688 else:
689 log.warning(
689 log.warning(
690 "Malformed reply from server: {}".format(reply), self.name)
690 "Malformed reply from server: {}".format(reply), self.name)
691
691
692 else:
692 else:
693 log.warning(
693 log.warning(
694 "No response from server, retrying...", self.name)
694 "No response from server, retrying...", self.name)
695 self.socket.setsockopt(zmq.LINGER, 0)
695 self.socket.setsockopt(zmq.LINGER, 0)
696 self.socket.close()
696 self.socket.close()
697 self.poll.unregister(self.socket)
697 self.poll.unregister(self.socket)
698 retries -= 1
698 retries -= 1
699 if retries == 0:
699 if retries == 0:
700 log.error(
700 log.error(
701 "Server seems to be offline, abandoning", self.name)
701 "Server seems to be offline, abandoning", self.name)
702 self.socket = self.context.socket(zmq.REQ)
702 self.socket = self.context.socket(zmq.REQ)
703 self.socket.connect(self.plot_server)
703 self.socket.connect(self.plot_server)
704 self.poll.register(self.socket, zmq.POLLIN)
704 self.poll.register(self.socket, zmq.POLLIN)
705 time.sleep(1)
705 time.sleep(1)
706 break
706 break
707 self.socket = self.context.socket(zmq.REQ)
707 self.socket = self.context.socket(zmq.REQ)
708 self.socket.connect(self.plot_server)
708 self.socket.connect(self.plot_server)
709 self.poll.register(self.socket, zmq.POLLIN)
709 self.poll.register(self.socket, zmq.POLLIN)
710 time.sleep(0.5)
710 time.sleep(0.5)
711
711
712 def setup(self):
712 def setup(self):
713 '''
713 '''
714 This method should be implemented in the child class, the following
714 This method should be implemented in the child class, the following
715 attributes should be set:
715 attributes should be set:
716
716
717 self.nrows: number of rows
717 self.nrows: number of rows
718 self.ncols: number of cols
718 self.ncols: number of cols
719 self.nplots: number of plots (channels or pairs)
719 self.nplots: number of plots (channels or pairs)
720 self.ylabel: label for Y axes
720 self.ylabel: label for Y axes
721 self.titles: list of axes title
721 self.titles: list of axes title
722
722
723 '''
723 '''
724 raise NotImplementedError
724 raise NotImplementedError
725
725
726 def plot(self):
726 def plot(self):
727 '''
727 '''
728 Must be defined in the child class
728 Must be defined in the child class
729 '''
729 '''
730 raise NotImplementedError
730 raise NotImplementedError
731
731
732 def run(self, dataOut, **kwargs):
732 def run(self, dataOut, **kwargs):
733 '''
733 '''
734 Main plotting routine
734 Main plotting routine
735 '''
735 '''
736
736
737 if self.isConfig is False:
737 if self.isConfig is False:
738 self.__setup(**kwargs)
738 self.__setup(**kwargs)
739 if dataOut.type == 'Parameters':
739 if dataOut.type == 'Parameters':
740 t = dataOut.utctimeInit
740 t = dataOut.utctimeInit
741 else:
741 else:
742 t = dataOut.utctime
742 t = dataOut.utctime
743
743
744 if dataOut.useLocalTime:
744 if dataOut.useLocalTime:
745 self.getDateTime = datetime.datetime.fromtimestamp
745 self.getDateTime = datetime.datetime.fromtimestamp
746 if not self.localtime:
746 if not self.localtime:
747 t += time.timezone
747 t += time.timezone
748 else:
748 else:
749 self.getDateTime = datetime.datetime.utcfromtimestamp
749 self.getDateTime = datetime.datetime.utcfromtimestamp
750 if self.localtime:
750 if self.localtime:
751 t -= time.timezone
751 t -= time.timezone
752
752
753 if 'buffer' in self.plot_type:
753 if 'buffer' in self.plot_type:
754 if self.xmin is None:
754 if self.xmin is None:
755 self.tmin = t
755 self.tmin = t
756 else:
756 else:
757 self.tmin = (
757 self.tmin = (
758 self.getDateTime(t).replace(
758 self.getDateTime(t).replace(
759 hour=self.xmin,
759 hour=self.xmin,
760 minute=0,
760 minute=0,
761 second=0) - self.getDateTime(0)).total_seconds()
761 second=0) - self.getDateTime(0)).total_seconds()
762
762
763 self.data.setup()
763 self.data.setup()
764 self.isConfig = True
764 self.isConfig = True
765 if self.plot_server:
765 if self.plot_server:
766 self.context = zmq.Context()
766 self.context = zmq.Context()
767 self.socket = self.context.socket(zmq.REQ)
767 self.socket = self.context.socket(zmq.REQ)
768 self.socket.connect(self.plot_server)
768 self.socket.connect(self.plot_server)
769 self.poll = zmq.Poller()
769 self.poll = zmq.Poller()
770 self.poll.register(self.socket, zmq.POLLIN)
770 self.poll.register(self.socket, zmq.POLLIN)
771
771
772 if dataOut.type == 'Parameters':
772 if dataOut.type == 'Parameters':
773 tm = dataOut.utctimeInit
773 tm = dataOut.utctimeInit
774 else:
774 else:
775 tm = dataOut.utctime
775 tm = dataOut.utctime
776
776
777 if not dataOut.useLocalTime and self.localtime:
777 if not dataOut.useLocalTime and self.localtime:
778 tm -= time.timezone
778 tm -= time.timezone
779 if dataOut.useLocalTime and not self.localtime:
779 if dataOut.useLocalTime and not self.localtime:
780 tm += time.timezone
780 tm += time.timezone
781
781
782 if self.xaxis is 'time' and self.data and (tm - self.tmin) >= self.xrange*60*60:
782 if self.xaxis is 'time' and self.data and (tm - self.tmin) >= self.xrange*60*60:
783 self.save_counter = self.save_period
783 self.save_counter = self.save_period
784 self.__plot()
784 self.__plot()
785 self.xmin += self.xrange
785 self.xmin += self.xrange
786 if self.xmin >= 24:
786 if self.xmin >= 24:
787 self.xmin -= 24
787 self.xmin -= 24
788 self.tmin += self.xrange*60*60
788 self.tmin += self.xrange*60*60
789 self.data.setup()
789 self.data.setup()
790 self.clear_figures()
790 self.clear_figures()
791
791
792 self.data.update(dataOut, tm)
792 self.data.update(dataOut, tm)
793
793
794 if self.isPlotConfig is False:
794 if self.isPlotConfig is False:
795 self.__setup_plot()
795 self.__setup_plot()
796 self.isPlotConfig = True
796 self.isPlotConfig = True
797
797
798 if self.realtime:
798 if self.realtime:
799 self.__plot()
799 self.__plot()
800 else:
800 else:
801 self.__throttle_plot(self.__plot)#, coerce=coerce)
801 self.__throttle_plot(self.__plot)#, coerce=coerce)
802
802
803 def close(self):
803 def close(self):
804
804
805 if self.data:
805 if self.data:
806 self.save_counter = self.save_period
806 self.save_counter = self.save_period
807 self.__plot()
807 self.__plot()
808 if self.data and self.pause:
808 if self.data and self.pause:
809 figpause(10)
809 figpause(10)
810
810
This diff has been collapsed as it changes many lines, (970 lines changed) Show them Hide them
@@ -1,1831 +1,1565
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
16 import zmq
15 import zmq
17
16
18 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
17 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
19 from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width
18 from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width
20 from schainpy.utils import log
19 from schainpy.utils import log
21 import schainpy.admin
20 import schainpy.admin
22
21
23 LOCALTIME = True
22 LOCALTIME = True
23 DT_DIRECTIVES = {
24 '%Y': 4,
25 '%y': 2,
26 '%m': 2,
27 '%d': 2,
28 '%j': 3,
29 '%H': 2,
30 '%M': 2,
31 '%S': 2,
32 '%f': 6
33 }
24
34
25
35
26 def isNumber(cad):
36 def isNumber(cad):
27 """
37 """
28 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
38 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
29
39
30 Excepciones:
40 Excepciones:
31 Si un determinado string no puede ser convertido a numero
41 Si un determinado string no puede ser convertido a numero
32 Input:
42 Input:
33 str, string al cual se le analiza para determinar si convertible a un numero o no
43 str, string al cual se le analiza para determinar si convertible a un numero o no
34
44
35 Return:
45 Return:
36 True : si el string es uno numerico
46 True : si el string es uno numerico
37 False : no es un string numerico
47 False : no es un string numerico
38 """
48 """
39 try:
49 try:
40 float(cad)
50 float(cad)
41 return True
51 return True
42 except:
52 except:
43 return False
53 return False
44
54
45
55
46 def isFileInEpoch(filename, startUTSeconds, endUTSeconds):
56 def isFileInEpoch(filename, startUTSeconds, endUTSeconds):
47 """
57 """
48 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
58 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
49
59
50 Inputs:
60 Inputs:
51 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
61 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
52
62
53 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
63 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
54 segundos contados desde 01/01/1970.
64 segundos contados desde 01/01/1970.
55 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
65 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
56 segundos contados desde 01/01/1970.
66 segundos contados desde 01/01/1970.
57
67
58 Return:
68 Return:
59 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
69 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
60 fecha especificado, de lo contrario retorna False.
70 fecha especificado, de lo contrario retorna False.
61
71
62 Excepciones:
72 Excepciones:
63 Si el archivo no existe o no puede ser abierto
73 Si el archivo no existe o no puede ser abierto
64 Si la cabecera no puede ser leida.
74 Si la cabecera no puede ser leida.
65
75
66 """
76 """
67 basicHeaderObj = BasicHeader(LOCALTIME)
77 basicHeaderObj = BasicHeader(LOCALTIME)
68
78
69 try:
79 try:
70 fp = open(filename, 'rb')
80 fp = open(filename, 'rb')
71 except IOError:
81 except IOError:
72 print("The file %s can't be opened" % (filename))
82 print("The file %s can't be opened" % (filename))
73 return 0
83 return 0
74
84
75 sts = basicHeaderObj.read(fp)
85 sts = basicHeaderObj.read(fp)
76 fp.close()
86 fp.close()
77
87
78 if not(sts):
88 if not(sts):
79 print("Skipping the file %s because it has not a valid header" % (filename))
89 print("Skipping the file %s because it has not a valid header" % (filename))
80 return 0
90 return 0
81
91
82 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
92 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
83 return 0
93 return 0
84
94
85 return 1
95 return 1
86
96
87
97
88 def isTimeInRange(thisTime, startTime, endTime):
98 def isTimeInRange(thisTime, startTime, endTime):
89 if endTime >= startTime:
99 if endTime >= startTime:
90 if (thisTime < startTime) or (thisTime > endTime):
100 if (thisTime < startTime) or (thisTime > endTime):
91 return 0
101 return 0
92 return 1
102 return 1
93 else:
103 else:
94 if (thisTime < startTime) and (thisTime > endTime):
104 if (thisTime < startTime) and (thisTime > endTime):
95 return 0
105 return 0
96 return 1
106 return 1
97
107
98
108
99 def isFileInTimeRange(filename, startDate, endDate, startTime, endTime):
109 def isFileInTimeRange(filename, startDate, endDate, startTime, endTime):
100 """
110 """
101 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
111 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
102
112
103 Inputs:
113 Inputs:
104 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
114 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
105
115
106 startDate : fecha inicial del rango seleccionado en formato datetime.date
116 startDate : fecha inicial del rango seleccionado en formato datetime.date
107
117
108 endDate : fecha final del rango seleccionado en formato datetime.date
118 endDate : fecha final del rango seleccionado en formato datetime.date
109
119
110 startTime : tiempo inicial del rango seleccionado en formato datetime.time
120 startTime : tiempo inicial del rango seleccionado en formato datetime.time
111
121
112 endTime : tiempo final del rango seleccionado en formato datetime.time
122 endTime : tiempo final del rango seleccionado en formato datetime.time
113
123
114 Return:
124 Return:
115 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
125 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
116 fecha especificado, de lo contrario retorna False.
126 fecha especificado, de lo contrario retorna False.
117
127
118 Excepciones:
128 Excepciones:
119 Si el archivo no existe o no puede ser abierto
129 Si el archivo no existe o no puede ser abierto
120 Si la cabecera no puede ser leida.
130 Si la cabecera no puede ser leida.
121
131
122 """
132 """
123
133
124 try:
134 try:
125 fp = open(filename, 'rb')
135 fp = open(filename, 'rb')
126 except IOError:
136 except IOError:
127 print("The file %s can't be opened" % (filename))
137 print("The file %s can't be opened" % (filename))
128 return None
138 return None
129
139
130 firstBasicHeaderObj = BasicHeader(LOCALTIME)
140 firstBasicHeaderObj = BasicHeader(LOCALTIME)
131 systemHeaderObj = SystemHeader()
141 systemHeaderObj = SystemHeader()
132 radarControllerHeaderObj = RadarControllerHeader()
142 radarControllerHeaderObj = RadarControllerHeader()
133 processingHeaderObj = ProcessingHeader()
143 processingHeaderObj = ProcessingHeader()
134
144
135 lastBasicHeaderObj = BasicHeader(LOCALTIME)
145 lastBasicHeaderObj = BasicHeader(LOCALTIME)
136
146
137 sts = firstBasicHeaderObj.read(fp)
147 sts = firstBasicHeaderObj.read(fp)
138
148
139 if not(sts):
149 if not(sts):
140 print("[Reading] Skipping the file %s because it has not a valid header" % (filename))
150 print("[Reading] Skipping the file %s because it has not a valid header" % (filename))
141 return None
151 return None
142
152
143 if not systemHeaderObj.read(fp):
153 if not systemHeaderObj.read(fp):
144 return None
154 return None
145
155
146 if not radarControllerHeaderObj.read(fp):
156 if not radarControllerHeaderObj.read(fp):
147 return None
157 return None
148
158
149 if not processingHeaderObj.read(fp):
159 if not processingHeaderObj.read(fp):
150 return None
160 return None
151
161
152 filesize = os.path.getsize(filename)
162 filesize = os.path.getsize(filename)
153
163
154 offset = processingHeaderObj.blockSize + 24 # header size
164 offset = processingHeaderObj.blockSize + 24 # header size
155
165
156 if filesize <= offset:
166 if filesize <= offset:
157 print("[Reading] %s: This file has not enough data" % filename)
167 print("[Reading] %s: This file has not enough data" % filename)
158 return None
168 return None
159
169
160 fp.seek(-offset, 2)
170 fp.seek(-offset, 2)
161
171
162 sts = lastBasicHeaderObj.read(fp)
172 sts = lastBasicHeaderObj.read(fp)
163
173
164 fp.close()
174 fp.close()
165
175
166 thisDatetime = lastBasicHeaderObj.datatime
176 thisDatetime = lastBasicHeaderObj.datatime
167 thisTime_last_block = thisDatetime.time()
177 thisTime_last_block = thisDatetime.time()
168
178
169 thisDatetime = firstBasicHeaderObj.datatime
179 thisDatetime = firstBasicHeaderObj.datatime
170 thisDate = thisDatetime.date()
180 thisDate = thisDatetime.date()
171 thisTime_first_block = thisDatetime.time()
181 thisTime_first_block = thisDatetime.time()
172
182
173 # General case
183 # General case
174 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
184 # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o
175 #-----------o----------------------------o-----------
185 #-----------o----------------------------o-----------
176 # startTime endTime
186 # startTime endTime
177
187
178 if endTime >= startTime:
188 if endTime >= startTime:
179 if (thisTime_last_block < startTime) or (thisTime_first_block > endTime):
189 if (thisTime_last_block < startTime) or (thisTime_first_block > endTime):
180 return None
190 return None
181
191
182 return thisDatetime
192 return thisDatetime
183
193
184 # If endTime < startTime then endTime belongs to the next day
194 # If endTime < startTime then endTime belongs to the next day
185
195
186 #<<<<<<<<<<<o o>>>>>>>>>>>
196 #<<<<<<<<<<<o o>>>>>>>>>>>
187 #-----------o----------------------------o-----------
197 #-----------o----------------------------o-----------
188 # endTime startTime
198 # endTime startTime
189
199
190 if (thisDate == startDate) and (thisTime_last_block < startTime):
200 if (thisDate == startDate) and (thisTime_last_block < startTime):
191 return None
201 return None
192
202
193 if (thisDate == endDate) and (thisTime_first_block > endTime):
203 if (thisDate == endDate) and (thisTime_first_block > endTime):
194 return None
204 return None
195
205
196 if (thisTime_last_block < startTime) and (thisTime_first_block > endTime):
206 if (thisTime_last_block < startTime) and (thisTime_first_block > endTime):
197 return None
207 return None
198
208
199 return thisDatetime
209 return thisDatetime
200
210
201
211
202 def isFolderInDateRange(folder, startDate=None, endDate=None):
212 def isFolderInDateRange(folder, startDate=None, endDate=None):
203 """
213 """
204 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
214 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
205
215
206 Inputs:
216 Inputs:
207 folder : nombre completo del directorio.
217 folder : nombre completo del directorio.
208 Su formato deberia ser "/path_root/?YYYYDDD"
218 Su formato deberia ser "/path_root/?YYYYDDD"
209
219
210 siendo:
220 siendo:
211 YYYY : Anio (ejemplo 2015)
221 YYYY : Anio (ejemplo 2015)
212 DDD : Dia del anio (ejemplo 305)
222 DDD : Dia del anio (ejemplo 305)
213
223
214 startDate : fecha inicial del rango seleccionado en formato datetime.date
224 startDate : fecha inicial del rango seleccionado en formato datetime.date
215
225
216 endDate : fecha final del rango seleccionado en formato datetime.date
226 endDate : fecha final del rango seleccionado en formato datetime.date
217
227
218 Return:
228 Return:
219 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
229 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
220 fecha especificado, de lo contrario retorna False.
230 fecha especificado, de lo contrario retorna False.
221 Excepciones:
231 Excepciones:
222 Si el directorio no tiene el formato adecuado
232 Si el directorio no tiene el formato adecuado
223 """
233 """
224
234
225 basename = os.path.basename(folder)
235 basename = os.path.basename(folder)
226
236
227 if not isRadarFolder(basename):
237 if not isRadarFolder(basename):
228 print("The folder %s has not the rigth format" % folder)
238 print("The folder %s has not the rigth format" % folder)
229 return 0
239 return 0
230
240
231 if startDate and endDate:
241 if startDate and endDate:
232 thisDate = getDateFromRadarFolder(basename)
242 thisDate = getDateFromRadarFolder(basename)
233
243
234 if thisDate < startDate:
244 if thisDate < startDate:
235 return 0
245 return 0
236
246
237 if thisDate > endDate:
247 if thisDate > endDate:
238 return 0
248 return 0
239
249
240 return 1
250 return 1
241
251
242
252
243 def isFileInDateRange(filename, startDate=None, endDate=None):
253 def isFileInDateRange(filename, startDate=None, endDate=None):
244 """
254 """
245 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
255 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
246
256
247 Inputs:
257 Inputs:
248 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
258 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
249
259
250 Su formato deberia ser "?YYYYDDDsss"
260 Su formato deberia ser "?YYYYDDDsss"
251
261
252 siendo:
262 siendo:
253 YYYY : Anio (ejemplo 2015)
263 YYYY : Anio (ejemplo 2015)
254 DDD : Dia del anio (ejemplo 305)
264 DDD : Dia del anio (ejemplo 305)
255 sss : set
265 sss : set
256
266
257 startDate : fecha inicial del rango seleccionado en formato datetime.date
267 startDate : fecha inicial del rango seleccionado en formato datetime.date
258
268
259 endDate : fecha final del rango seleccionado en formato datetime.date
269 endDate : fecha final del rango seleccionado en formato datetime.date
260
270
261 Return:
271 Return:
262 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
272 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
263 fecha especificado, de lo contrario retorna False.
273 fecha especificado, de lo contrario retorna False.
264 Excepciones:
274 Excepciones:
265 Si el archivo no tiene el formato adecuado
275 Si el archivo no tiene el formato adecuado
266 """
276 """
267
277
268 basename = os.path.basename(filename)
278 basename = os.path.basename(filename)
269
279
270 if not isRadarFile(basename):
280 if not isRadarFile(basename):
271 print("The filename %s has not the rigth format" % filename)
281 print("The filename %s has not the rigth format" % filename)
272 return 0
282 return 0
273
283
274 if startDate and endDate:
284 if startDate and endDate:
275 thisDate = getDateFromRadarFile(basename)
285 thisDate = getDateFromRadarFile(basename)
276
286
277 if thisDate < startDate:
287 if thisDate < startDate:
278 return 0
288 return 0
279
289
280 if thisDate > endDate:
290 if thisDate > endDate:
281 return 0
291 return 0
282
292
283 return 1
293 return 1
284
294
285
295
286 def getFileFromSet(path, ext, set):
296 def getFileFromSet(path, ext, set):
287 validFilelist = []
297 validFilelist = []
288 fileList = os.listdir(path)
298 fileList = os.listdir(path)
289
299
290 # 0 1234 567 89A BCDE
300 # 0 1234 567 89A BCDE
291 # H YYYY DDD SSS .ext
301 # H YYYY DDD SSS .ext
292
302
293 for thisFile in fileList:
303 for thisFile in fileList:
294 try:
304 try:
295 year = int(thisFile[1:5])
305 year = int(thisFile[1:5])
296 doy = int(thisFile[5:8])
306 doy = int(thisFile[5:8])
297 except:
307 except:
298 continue
308 continue
299
309
300 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
310 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
301 continue
311 continue
302
312
303 validFilelist.append(thisFile)
313 validFilelist.append(thisFile)
304
314
305 myfile = fnmatch.filter(
315 myfile = fnmatch.filter(
306 validFilelist, '*%4.4d%3.3d%3.3d*' % (year, doy, set))
316 validFilelist, '*%4.4d%3.3d%3.3d*' % (year, doy, set))
307
317
308 if len(myfile) != 0:
318 if len(myfile) != 0:
309 return myfile[0]
319 return myfile[0]
310 else:
320 else:
311 filename = '*%4.4d%3.3d%3.3d%s' % (year, doy, set, ext.lower())
321 filename = '*%4.4d%3.3d%3.3d%s' % (year, doy, set, ext.lower())
312 print('the filename %s does not exist' % filename)
322 print('the filename %s does not exist' % filename)
313 print('...going to the last file: ')
323 print('...going to the last file: ')
314
324
315 if validFilelist:
325 if validFilelist:
316 validFilelist = sorted(validFilelist, key=str.lower)
326 validFilelist = sorted(validFilelist, key=str.lower)
317 return validFilelist[-1]
327 return validFilelist[-1]
318
328
319 return None
329 return None
320
330
321
331
322 def getlastFileFromPath(path, ext):
332 def getlastFileFromPath(path, ext):
323 """
333 """
324 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
334 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
325 al final de la depuracion devuelve el ultimo file de la lista que quedo.
335 al final de la depuracion devuelve el ultimo file de la lista que quedo.
326
336
327 Input:
337 Input:
328 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
338 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
329 ext : extension de los files contenidos en una carpeta
339 ext : extension de los files contenidos en una carpeta
330
340
331 Return:
341 Return:
332 El ultimo file de una determinada carpeta, no se considera el path.
342 El ultimo file de una determinada carpeta, no se considera el path.
333 """
343 """
334 validFilelist = []
344 validFilelist = []
335 fileList = os.listdir(path)
345 fileList = os.listdir(path)
336
346
337 # 0 1234 567 89A BCDE
347 # 0 1234 567 89A BCDE
338 # H YYYY DDD SSS .ext
348 # H YYYY DDD SSS .ext
339
349
340 for thisFile in fileList:
350 for thisFile in fileList:
341
351
342 year = thisFile[1:5]
352 year = thisFile[1:5]
343 if not isNumber(year):
353 if not isNumber(year):
344 continue
354 continue
345
355
346 doy = thisFile[5:8]
356 doy = thisFile[5:8]
347 if not isNumber(doy):
357 if not isNumber(doy):
348 continue
358 continue
349
359
350 year = int(year)
360 year = int(year)
351 doy = int(doy)
361 doy = int(doy)
352
362
353 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
363 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
354 continue
364 continue
355
365
356 validFilelist.append(thisFile)
366 validFilelist.append(thisFile)
357
367
358 if validFilelist:
368 if validFilelist:
359 validFilelist = sorted(validFilelist, key=str.lower)
369 validFilelist = sorted(validFilelist, key=str.lower)
360 return validFilelist[-1]
370 return validFilelist[-1]
361
371
362 return None
372 return None
363
373
364
374
365 def checkForRealPath(path, foldercounter, year, doy, set, ext):
366 """
367 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
368 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
369 el path exacto de un determinado file.
370
371 Example :
372 nombre correcto del file es .../.../D2009307/P2009307367.ext
373
374 Entonces la funcion prueba con las siguientes combinaciones
375 .../.../y2009307367.ext
376 .../.../Y2009307367.ext
377 .../.../x2009307/y2009307367.ext
378 .../.../x2009307/Y2009307367.ext
379 .../.../X2009307/y2009307367.ext
380 .../.../X2009307/Y2009307367.ext
381 siendo para este caso, la ultima combinacion de letras, identica al file buscado
382
383 Return:
384 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
385 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
386 para el filename
387 """
388 fullfilename = None
389 find_flag = False
390 filename = None
391
392 prefixDirList = [None, 'd', 'D']
393 if ext.lower() == ".r": # voltage
394 prefixFileList = ['d', 'D']
395 elif ext.lower() == ".pdata": # spectra
396 prefixFileList = ['p', 'P']
397 else:
398 return None, filename
399
400 # barrido por las combinaciones posibles
401 for prefixDir in prefixDirList:
402 thispath = path
403 if prefixDir != None:
404 # formo el nombre del directorio xYYYYDDD (x=d o x=D)
405 if foldercounter == 0:
406 thispath = os.path.join(path, "%s%04d%03d" %
407 (prefixDir, year, doy))
408 else:
409 thispath = os.path.join(path, "%s%04d%03d_%02d" % (
410 prefixDir, year, doy, foldercounter))
411 for prefixFile in prefixFileList: # barrido por las dos combinaciones posibles de "D"
412 # formo el nombre del file xYYYYDDDSSS.ext
413 filename = "%s%04d%03d%03d%s" % (prefixFile, year, doy, set, ext)
414 fullfilename = os.path.join(
415 thispath, filename) # formo el path completo
416
417 if os.path.exists(fullfilename): # verifico que exista
418 find_flag = True
419 break
420 if find_flag:
421 break
422
423 if not(find_flag):
424 return None, filename
425
426 return fullfilename, filename
427
428
429 def isRadarFolder(folder):
375 def isRadarFolder(folder):
430 try:
376 try:
431 year = int(folder[1:5])
377 year = int(folder[1:5])
432 doy = int(folder[5:8])
378 doy = int(folder[5:8])
433 except:
379 except:
434 return 0
380 return 0
435
381
436 return 1
382 return 1
437
383
438
384
439 def isRadarFile(file):
385 def isRadarFile(file):
440 try:
386 try:
441 year = int(file[1:5])
387 year = int(file[1:5])
442 doy = int(file[5:8])
388 doy = int(file[5:8])
443 set = int(file[8:11])
389 set = int(file[8:11])
444 except:
390 except:
445 return 0
391 return 0
446
392
447 return 1
393 return 1
448
394
449
395
450 def getDateFromRadarFile(file):
396 def getDateFromRadarFile(file):
451 try:
397 try:
452 year = int(file[1:5])
398 year = int(file[1:5])
453 doy = int(file[5:8])
399 doy = int(file[5:8])
454 set = int(file[8:11])
400 set = int(file[8:11])
455 except:
401 except:
456 return None
402 return None
457
403
458 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
404 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
459 return thisDate
405 return thisDate
460
406
461
407
462 def getDateFromRadarFolder(folder):
408 def getDateFromRadarFolder(folder):
463 try:
409 try:
464 year = int(folder[1:5])
410 year = int(folder[1:5])
465 doy = int(folder[5:8])
411 doy = int(folder[5:8])
466 except:
412 except:
467 return None
413 return None
468
414
469 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
415 thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy - 1)
470 return thisDate
416 return thisDate
471
417
418 def parse_format(s, fmt):
472
419
473 class JRODataIO:
420 for i in range(fmt.count('%')):
421 x = fmt.index('%')
422 d = DT_DIRECTIVES[fmt[x:x+2]]
423 fmt = fmt.replace(fmt[x:x+2], s[x:x+d])
424 return fmt
474
425
475 c = 3E8
426 class Reader(object):
476
427
428 c = 3E8
477 isConfig = False
429 isConfig = False
478
479 basicHeaderObj = None
480
481 systemHeaderObj = None
482
483 radarControllerHeaderObj = None
484
485 processingHeaderObj = None
486
487 dtype = None
430 dtype = None
488
489 pathList = []
431 pathList = []
490
491 filenameList = []
432 filenameList = []
492
433 datetimeList = []
493 filename = None
434 filename = None
494
495 ext = None
435 ext = None
496
497 flagIsNewFile = 1
436 flagIsNewFile = 1
498
499 flagDiscontinuousBlock = 0
437 flagDiscontinuousBlock = 0
500
501 flagIsNewBlock = 0
438 flagIsNewBlock = 0
502
439 flagNoMoreFiles = 0
503 fp = None
440 fp = None
504
505 firstHeaderSize = 0
441 firstHeaderSize = 0
506
507 basicHeaderSize = 24
442 basicHeaderSize = 24
508
509 versionFile = 1103
443 versionFile = 1103
510
511 fileSize = None
444 fileSize = None
512
513 # ippSeconds = None
514
515 fileSizeByHeader = None
445 fileSizeByHeader = None
516
446 fileIndex = -1
517 fileIndex = None
518
519 profileIndex = None
447 profileIndex = None
520
448 blockIndex = 0
521 blockIndex = None
449 nTotalBlocks = 0
522
523 nTotalBlocks = None
524
525 maxTimeStep = 30
450 maxTimeStep = 30
526
527 lastUTTime = None
451 lastUTTime = None
528
529 datablock = None
452 datablock = None
530
531 dataOut = None
453 dataOut = None
532
533 blocksize = None
534
535 getByBlock = False
454 getByBlock = False
536
455 path = None
537 def __init__(self):
456 startDate = None
538
457 endDate = None
539 raise NotImplementedError
458 startTime = datetime.time(0, 0, 0)
459 endTime = datetime.time(23, 59, 59)
460 set = None
461 expLabel = ""
462 online = False
463 delay = 60
464 nTries = 3 # quantity tries
465 nFiles = 3 # number of files for searching
466 walk = True
467 getblock = False
468 nTxs = 1
469 realtime = False
470 blocksize = 0
471 blocktime = None
472 warnings = True
473 verbose = True
474 server = None
475 format = None
476 oneDDict = None
477 twoDDict = None
478 independentParam = None
479 filefmt = None
480 folderfmt = None
540
481
541 def run(self):
482 def run(self):
542
483
543 raise NotImplementedError
484 raise NotImplementedError
544
485
545 def getDtypeWidth(self):
546
547 dtype_index = get_dtype_index(self.dtype)
548 dtype_width = get_dtype_width(dtype_index)
549
550 return dtype_width
551
552 def getAllowedArgs(self):
486 def getAllowedArgs(self):
553 if hasattr(self, '__attrs__'):
487 if hasattr(self, '__attrs__'):
554 return self.__attrs__
488 return self.__attrs__
555 else:
489 else:
556 return inspect.getargspec(self.run).args
490 return inspect.getargspec(self.run).args
557
491
492 def set_kwargs(self, **kwargs):
558
493
559 class JRODataReader(JRODataIO):
494 for key, value in kwargs.items():
495 setattr(self, key, value)
560
496
561 online = 0
497 def find_folders(self, path, startDate, endDate, folderfmt, last=False):
562
498
563 realtime = 0
499 folders = [x for f in path.split(',')
500 for x in os.listdir(f) if os.path.isdir(os.path.join(f, x))]
501 folders.sort()
564
502
565 nReadBlocks = 0
503 if last:
566
504 folders = [folders[-1]]
567 delay = 10 # number of seconds waiting a new file
568
569 nTries = 3 # quantity tries
570
571 nFiles = 3 # number of files for searching
572
505
573 path = None
506 for folder in folders:
574
507 try:
575 foldercounter = 0
508 dt = datetime.datetime.strptime(parse_format(folder, folderfmt), folderfmt).date()
576
509 if dt >= startDate and dt <= endDate:
577 flagNoMoreFiles = 0
510 yield os.path.join(path, folder)
578
511 else:
579 datetimeList = []
512 log.log('Skiping folder {}'.format(folder), self.name)
580
513 except Exception as e:
581 __isFirstTimeOnline = 1
514 log.log('Skiping folder {}'.format(folder), self.name)
582
515 continue
583 __printInfo = True
516 return
584
585 profileIndex = None
586
587 nTxs = 1
588
589 txIndex = None
590
591 # Added--------------------
592
593 selBlocksize = None
594
595 selBlocktime = None
596
517
597 def __init__(self):
518 def find_files(self, folders, ext, filefmt, startDate=None, endDate=None,
598 """
519 expLabel='', last=False):
599 This class is used to find data files
600
520
601 Example:
521 for path in folders:
602 reader = JRODataReader()
522 files = glob.glob1(path, '*{}'.format(ext))
603 fileList = reader.findDataFiles()
523 files.sort()
604
524 if last:
605 """
525 if files:
526 fo = files[-1]
527 try:
528 dt = datetime.datetime.strptime(parse_format(fo, filefmt), filefmt).date()
529 yield os.path.join(path, expLabel, fo)
530 except Exception as e:
606 pass
531 pass
607
532 return None
608 def createObjByDefault(self):
609 """
610
611 """
612 raise NotImplementedError
613
614 def getBlockDimension(self):
615
616 raise NotImplementedError
617
618 def searchFilesOffLine(self,
619 path,
620 startDate=None,
621 endDate=None,
622 startTime=datetime.time(0, 0, 0),
623 endTime=datetime.time(23, 59, 59),
624 set=None,
625 expLabel='',
626 ext='.r',
627 cursor=None,
628 skip=None,
629 walk=True):
630
631 self.filenameList = []
632 self.datetimeList = []
633
634 pathList = []
635
636 dateList, pathList = self.findDatafiles(
637 path, startDate, endDate, expLabel, ext, walk, include_path=True)
638
639 if dateList == []:
640 return [], []
641
642 if len(dateList) > 1:
643 print("[Reading] Data found for date range [%s - %s]: total days = %d" % (startDate, endDate, len(dateList)))
644 else:
533 else:
645 print("[Reading] Data found for date range [%s - %s]: date = %s" % (startDate, endDate, dateList[0]))
534 return None
646
647 filenameList = []
648 datetimeList = []
649
650 for thisPath in pathList:
651
652 fileList = glob.glob1(thisPath, "*%s" % ext)
653 fileList.sort()
654
655 for file in fileList:
656
657 filename = os.path.join(thisPath, file)
658
659 if not isFileInDateRange(filename, startDate, endDate):
660 continue
661
662 thisDatetime = isFileInTimeRange(
663 filename, startDate, endDate, startTime, endTime)
664
535
665 if not(thisDatetime):
536 for fo in files:
537 try:
538 dt = datetime.datetime.strptime(parse_format(fo, filefmt), filefmt).date()
539 if dt >= startDate and dt <= endDate:
540 yield os.path.join(path, expLabel, fo)
541 else:
542 log.log('Skiping file {}'.format(fo), self.name)
543 except Exception as e:
544 log.log('Skiping file {}'.format(fo), self.name)
666 continue
545 continue
667
546
668 filenameList.append(filename)
547 def searchFilesOffLine(self, path, startDate, endDate,
669 datetimeList.append(thisDatetime)
548 expLabel, ext, walk,
670
549 filefmt, folderfmt):
671 if cursor is not None and skip is not None:
550 """Search files in offline mode for the given arguments
672 filenameList = filenameList[cursor * skip:cursor * skip + skip]
673 datetimeList = datetimeList[cursor * skip:cursor * skip + skip]
674
551
675 if not(filenameList):
552 Return:
676 print("[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" % (startTime, endTime, ext, path))
553 Generator of files
677 return [], []
554 """
678
679 print("[Reading] %d file(s) was(were) found in time range: %s - %s" % (len(filenameList), startTime, endTime))
680
681 # for i in range(len(filenameList)):
682 # print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
683
555
684 self.filenameList = filenameList
556 if walk:
685 self.datetimeList = datetimeList
557 folders = self.find_folders(
558 path, startDate, endDate, folderfmt)
559 else:
560 folders = path.split(',')
686
561
687 return pathList, filenameList
562 return self.find_files(
563 folders, ext, filefmt, startDate, endDate, expLabel)
688
564
689 def __searchFilesOnLine(self, path, expLabel="", ext=None, walk=True, set=None):
565 def searchFilesOnLine(self, path, startDate, endDate,
690 """
566 expLabel, ext, walk,
691 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
567 filefmt, folderfmt):
692 devuelve el archivo encontrado ademas de otros datos.
568 """Search for the last file of the last folder
693
569
694 Input:
570 Arguments:
695 path : carpeta donde estan contenidos los files que contiene data
571 path : carpeta donde estan contenidos los files que contiene data
696
697 expLabel : Nombre del subexperimento (subfolder)
572 expLabel : Nombre del subexperimento (subfolder)
698
699 ext : extension de los files
573 ext : extension de los files
700
701 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
574 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
702
575
703 Return:
576 Return:
704 directory : eL directorio donde esta el file encontrado
577 generator with the full path of last filename
705 filename : el ultimo file de una determinada carpeta
706 year : el anho
707 doy : el numero de dia del anho
708 set : el set del archivo
709
710
711 """
578 """
712 if not os.path.isdir(path):
713 return None, None, None, None, None, None
714
715 dirList = []
716
579
717 if not walk:
580 if walk:
718 fullpath = path
581 folders = self.find_folders(
719 foldercounter = 0
582 path, startDate, endDate, folderfmt, last=True)
720 else:
583 else:
721 # Filtra solo los directorios
584 folders = path.split(',')
722 for thisPath in os.listdir(path):
723 if not os.path.isdir(os.path.join(path, thisPath)):
724 continue
725 if not isRadarFolder(thisPath):
726 continue
727
585
728 dirList.append(thisPath)
586 return self.find_files(
729
587 folders, ext, filefmt, startDate, endDate, expLabel, last=True)
730 if not(dirList):
731 return None, None, None, None, None, None
732
733 dirList = sorted(dirList, key=str.lower)
734
588
735 doypath = dirList[-1]
589 def setNextFile(self):
736 foldercounter = int(doypath.split('_')[1]) if len(
590 """Set the next file to be readed open it and parse de file header"""
737 doypath.split('_')) > 1 else 0
738 fullpath = os.path.join(path, doypath, expLabel)
739
591
740 print("[Reading] %s folder was found: " % (fullpath))
592 if self.fp != None:
593 self.fp.close()
741
594
742 if set == None:
595 if self.online:
743 filename = getlastFileFromPath(fullpath, ext)
596 newFile = self.setNextFileOnline()
744 else:
597 else:
745 filename = getFileFromSet(fullpath, ext, set)
598 newFile = self.setNextFileOffline()
746
747 if not(filename):
748 return None, None, None, None, None, None
749
599
750 print("[Reading] %s file was found" % (filename))
600 if not(newFile):
601 if self.online:
602 raise schainpy.admin.SchainError('Time to wait for new files reach')
603 else:
604 if self.fileIndex == -1:
605 raise schainpy.admin.SchainWarning('No files found in the given path')
606 else:
607 raise schainpy.admin.SchainWarning('No more files to read')
751
608
752 if not(self.__verifyFile(os.path.join(fullpath, filename))):
609 if not(self.verifyFile(self.filename)):
753 return None, None, None, None, None, None
610 self.setNextFile()
754
611
755 year = int(filename[1:5])
612 log.log('Opening file: %s' % self.filename, self.name)
756 doy = int(filename[5:8])
757 set = int(filename[8:11])
758
613
759 return fullpath, foldercounter, filename, year, doy, set
614 self.readFirstHeader()
615 self.nReadBlocks = 0
760
616
761 def __setNextFileOffline(self):
617 def setNextFileOnline(self):
618 """Check for the next file to be readed in online mode.
762
619
763 idFile = self.fileIndex
620 Set:
621 self.filename
622 self.fp
623 self.filesize
764
624
765 while (True):
625 Return:
766 idFile += 1
626 boolean
767 if not(idFile < len(self.filenameList)):
768 self.flagNoMoreFiles = 1
769 return 0
770
627
771 filename = self.filenameList[idFile]
628 """
629 nextFile = True
630 nextDay = False
772
631
773 if not(self.__verifyFile(filename)):
632 for nFiles in range(self.nFiles+1):
633 for nTries in range(self.nTries):
634 fullfilename, filename = self.checkForRealPath(nextFile, nextDay)
635 if fullfilename is not None:
636 break
637 log.warning(
638 "Waiting %0.2f sec for the next file: \"%s\" , try %02d ..." % (self.delay, filename, nTries + 1),
639 self.name)
640 time.sleep(self.delay)
641 nextFile = False
774 continue
642 continue
775
643
776 fileSize = os.path.getsize(filename)
644 if fullfilename:
777 fp = open(filename, 'rb')
778 break
645 break
779
646
647 self.nTries = 1
648 nextFile = True
649
650 if nFiles == (self.nFiles - 1):
651 log.log('Trying with next day...', self.name)
652 nextDay = True
653
654 if fullfilename:
655 self.fileSize = os.path.getsize(fullfilename)
656 self.filename = fullfilename
780 self.flagIsNewFile = 1
657 self.flagIsNewFile = 1
781 self.fileIndex = idFile
658 if self.fp != None:
782 self.filename = filename
659 self.fp.close()
783 self.fileSize = fileSize
660 self.fp = open(fullfilename, 'rb')
784 self.fp = fp
661 self.flagNoMoreFiles = 0
662 self.fileIndex += 1
663 return 1
664 else:
665 return 0
666
667 def setNextFileOffline(self):
668 """Open the next file to be readed in offline mode"""
669
670 try:
671 filename = next(self.filenameList)
672 self.fileIndex +=1
673 except StopIteration:
674 self.flagNoMoreFiles = 1
675 return 0
785
676
786 # print "[Reading] Setting the file: %s"%self.filename
677 self.filename = filename
678 self.fileSize = os.path.getsize(filename)
679 self.fp = open(filename, 'rb')
680 self.flagIsNewFile = 1
787
681
788 return 1
682 return 1
789
683
790 def __setNextFileOnline(self):
684 def verifyFile(self, filename):
791 """
685 """Check for a valid file
792 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
793 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
794 siguientes.
795
686
796 Affected:
687 Arguments:
797 self.flagIsNewFile
688 filename -- full path filename
798 self.filename
799 self.fileSize
800 self.fp
801 self.set
802 self.flagNoMoreFiles
803
689
804 Return:
690 Return:
805 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
691 boolean
806 1 : si el file fue abierto con exito y esta listo a ser leido
807
808 Excepciones:
809 Si un determinado file no puede ser abierto
810 """
692 """
811 nFiles = 0
812 fileOk_flag = False
813 firstTime_flag = True
814
693
815 self.set += 1
694 return True
816
695
817 if self.set > 999:
696 def checkForRealPath(self, nextFile, nextDay):
818 self.set = 0
697 """Check if the next file to be readed exists"""
819 self.foldercounter += 1
820
698
821 # busca el 1er file disponible
699 raise NotImplementedError
822 fullfilename, filename = checkForRealPath(
823 self.path, self.foldercounter, self.year, self.doy, self.set, self.ext)
824 if fullfilename:
825 if self.__verifyFile(fullfilename, False):
826 fileOk_flag = True
827
700
828 # si no encuentra un file entonces espera y vuelve a buscar
701 def readFirstHeader(self):
829 if not(fileOk_flag):
702 """Parse the file header"""
830 # busco en los siguientes self.nFiles+1 files posibles
831 for nFiles in range(self.nFiles + 1):
832
703
833 if firstTime_flag: # si es la 1era vez entonces hace el for self.nTries veces
704 pass
834 tries = self.nTries
835 else:
836 tries = 1 # si no es la 1era vez entonces solo lo hace una vez
837
705
838 for nTries in range(tries):
706 class JRODataReader(Reader):
839 if firstTime_flag:
840 log.warning(
841 "Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % (self.delay, filename, nTries + 1),
842 self.name)
843 time.sleep(self.delay)
844 else:
845 log.warning(
846 "Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext),
847 self.name)
848
707
849 fullfilename, filename = checkForRealPath(
708 utc = 0
850 self.path, self.foldercounter, self.year, self.doy, self.set, self.ext)
709 nReadBlocks = 0
851 if fullfilename:
710 foldercounter = 0
852 if self.__verifyFile(fullfilename):
711 firstHeaderSize = 0
853 fileOk_flag = True
712 basicHeaderSize = 24
854 break
713 __isFirstTimeOnline = 1
714 __printInfo = True
715 filefmt = "*%Y%j***"
716 folderfmt = "*%Y%j"
855
717
856 if fileOk_flag:
718 def getDtypeWidth(self):
857 break
858
719
859 firstTime_flag = False
720 dtype_index = get_dtype_index(self.dtype)
721 dtype_width = get_dtype_width(dtype_index)
860
722
861 log.warning(
723 return dtype_width
862 'Skipping the file {} due to this file doesn\'t exist'.format(filename),
863 self.name)
864 self.set += 1
865
724
866 # si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
725 def checkForRealPath(self, nextFile, nextDay):
867 if nFiles == (self.nFiles - 1):
726 """Check if the next file to be readed exists.
868 self.set = 0
869 self.doy += 1
870 self.foldercounter = 0
871
727
872 if fileOk_flag:
728 Example :
873 self.fileSize = os.path.getsize(fullfilename)
729 nombre correcto del file es .../.../D2009307/P2009307367.ext
874 self.filename = fullfilename
875 self.flagIsNewFile = 1
876 if self.fp != None:
877 self.fp.close()
878 self.fp = open(fullfilename, 'rb')
879 self.flagNoMoreFiles = 0
880 else:
881 raise schainpy.admin.SchainError('Time for waiting new files reach')
882 self.fileSize = 0
883 self.filename = None
884 self.flagIsNewFile = 0
885 self.fp = None
886 self.flagNoMoreFiles = 1
887
730
888 return fileOk_flag
731 Entonces la funcion prueba con las siguientes combinaciones
732 .../.../y2009307367.ext
733 .../.../Y2009307367.ext
734 .../.../x2009307/y2009307367.ext
735 .../.../x2009307/Y2009307367.ext
736 .../.../X2009307/y2009307367.ext
737 .../.../X2009307/Y2009307367.ext
738 siendo para este caso, la ultima combinacion de letras, identica al file buscado
889
739
890 def setNextFile(self):
740 Return:
891 if self.fp != None:
741 str -- fullpath of the file
892 self.fp.close()
742 """
893
743
894 if self.online:
895 newFile = self.__setNextFileOnline()
896 else:
897 newFile = self.__setNextFileOffline()
898
744
899 if not(newFile):
745 if nextFile:
900 raise schainpy.admin.SchainWarning('No more files to read')
746 self.set += 1
747 if nextDay:
748 self.set = 0
749 self.doy += 1
750 foldercounter = 0
751 prefixDirList = [None, 'd', 'D']
752 if self.ext.lower() == ".r": # voltage
753 prefixFileList = ['d', 'D']
754 elif self.ext.lower() == ".pdata": # spectra
755 prefixFileList = ['p', 'P']
901
756
757 # barrido por las combinaciones posibles
758 for prefixDir in prefixDirList:
759 thispath = self.path
760 if prefixDir != None:
761 # formo el nombre del directorio xYYYYDDD (x=d o x=D)
762 if foldercounter == 0:
763 thispath = os.path.join(self.path, "%s%04d%03d" %
764 (prefixDir, self.year, self.doy))
765 else:
766 thispath = os.path.join(self.path, "%s%04d%03d_%02d" % (
767 prefixDir, self.year, self.doy, foldercounter))
768 for prefixFile in prefixFileList: # barrido por las dos combinaciones posibles de "D"
769 # formo el nombre del file xYYYYDDDSSS.ext
770 filename = "%s%04d%03d%03d%s" % (prefixFile, self.year, self.doy, self.set, self.ext)
771 fullfilename = os.path.join(
772 thispath, filename)
902
773
903 if self.verbose:
774 if os.path.exists(fullfilename):
904 print('[Reading] Setting the file: %s' % self.filename)
775 return fullfilename, filename
905
776
906 self.__readFirstHeader()
777 return None, filename
907 self.nReadBlocks = 0
908 return 1
909
778
910 def __waitNewBlock(self):
779 def __waitNewBlock(self):
911 """
780 """
912 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
781 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
913
782
914 Si el modo de lectura es OffLine siempre retorn 0
783 Si el modo de lectura es OffLine siempre retorn 0
915 """
784 """
916 if not self.online:
785 if not self.online:
917 return 0
786 return 0
918
787
919 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
788 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
920 return 0
789 return 0
921
790
922 currentPointer = self.fp.tell()
791 currentPointer = self.fp.tell()
923
792
924 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
793 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
925
794
926 for nTries in range(self.nTries):
795 for nTries in range(self.nTries):
927
796
928 self.fp.close()
797 self.fp.close()
929 self.fp = open(self.filename, 'rb')
798 self.fp = open(self.filename, 'rb')
930 self.fp.seek(currentPointer)
799 self.fp.seek(currentPointer)
931
800
932 self.fileSize = os.path.getsize(self.filename)
801 self.fileSize = os.path.getsize(self.filename)
933 currentSize = self.fileSize - currentPointer
802 currentSize = self.fileSize - currentPointer
934
803
935 if (currentSize >= neededSize):
804 if (currentSize >= neededSize):
936 self.basicHeaderObj.read(self.fp)
805 self.basicHeaderObj.read(self.fp)
937 return 1
806 return 1
938
807
939 if self.fileSize == self.fileSizeByHeader:
808 if self.fileSize == self.fileSizeByHeader:
940 # self.flagEoF = True
809 # self.flagEoF = True
941 return 0
810 return 0
942
811
943 print("[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1))
812 print("[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1))
944 time.sleep(self.delay)
813 time.sleep(self.delay)
945
814
946 return 0
815 return 0
947
816
948 def waitDataBlock(self, pointer_location, blocksize=None):
817 def waitDataBlock(self, pointer_location, blocksize=None):
949
818
950 currentPointer = pointer_location
819 currentPointer = pointer_location
951 if blocksize is None:
820 if blocksize is None:
952 neededSize = self.processingHeaderObj.blockSize # + self.basicHeaderSize
821 neededSize = self.processingHeaderObj.blockSize # + self.basicHeaderSize
953 else:
822 else:
954 neededSize = blocksize
823 neededSize = blocksize
955
824
956 for nTries in range(self.nTries):
825 for nTries in range(self.nTries):
957 self.fp.close()
826 self.fp.close()
958 self.fp = open(self.filename, 'rb')
827 self.fp = open(self.filename, 'rb')
959 self.fp.seek(currentPointer)
828 self.fp.seek(currentPointer)
960
829
961 self.fileSize = os.path.getsize(self.filename)
830 self.fileSize = os.path.getsize(self.filename)
962 currentSize = self.fileSize - currentPointer
831 currentSize = self.fileSize - currentPointer
963
832
964 if (currentSize >= neededSize):
833 if (currentSize >= neededSize):
965 return 1
834 return 1
966
835
967 log.warning(
836 log.warning(
968 "Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1),
837 "Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries + 1),
969 self.name
838 self.name
970 )
839 )
971 time.sleep(self.delay)
840 time.sleep(self.delay)
972
841
973 return 0
842 return 0
974
843
975 def __jumpToLastBlock(self):
976
977 if not(self.__isFirstTimeOnline):
978 return
979
980 csize = self.fileSize - self.fp.tell()
981 blocksize = self.processingHeaderObj.blockSize
982
983 # salta el primer bloque de datos
984 if csize > self.processingHeaderObj.blockSize:
985 self.fp.seek(self.fp.tell() + blocksize)
986 else:
987 return
988
989 csize = self.fileSize - self.fp.tell()
990 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
991 while True:
992
993 if self.fp.tell() < self.fileSize:
994 self.fp.seek(self.fp.tell() + neededsize)
995 else:
996 self.fp.seek(self.fp.tell() - neededsize)
997 break
998
999 # csize = self.fileSize - self.fp.tell()
1000 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
1001 # factor = int(csize/neededsize)
1002 # if factor > 0:
1003 # self.fp.seek(self.fp.tell() + factor*neededsize)
1004
1005 self.flagIsNewFile = 0
1006 self.__isFirstTimeOnline = 0
1007
1008 def __setNewBlock(self):
844 def __setNewBlock(self):
1009 # if self.server is None:
845
1010 if self.fp == None:
846 if self.fp == None:
1011 return 0
847 return 0
1012
848
1013 # if self.online:
1014 # self.__jumpToLastBlock()
1015
1016 if self.flagIsNewFile:
849 if self.flagIsNewFile:
1017 self.lastUTTime = self.basicHeaderObj.utc
850 self.lastUTTime = self.basicHeaderObj.utc
1018 return 1
851 return 1
1019
852
1020 if self.realtime:
853 if self.realtime:
1021 self.flagDiscontinuousBlock = 1
854 self.flagDiscontinuousBlock = 1
1022 if not(self.setNextFile()):
855 if not(self.setNextFile()):
1023 return 0
856 return 0
1024 else:
857 else:
1025 return 1
858 return 1
1026 # if self.server is None:
859
1027 currentSize = self.fileSize - self.fp.tell()
860 currentSize = self.fileSize - self.fp.tell()
1028 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
861 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
862
1029 if (currentSize >= neededSize):
863 if (currentSize >= neededSize):
1030 self.basicHeaderObj.read(self.fp)
864 self.basicHeaderObj.read(self.fp)
1031 self.lastUTTime = self.basicHeaderObj.utc
865 self.lastUTTime = self.basicHeaderObj.utc
1032 return 1
866 return 1
1033 # else:
867
1034 # self.basicHeaderObj.read(self.zHeader)
1035 # self.lastUTTime = self.basicHeaderObj.utc
1036 # return 1
1037 if self.__waitNewBlock():
868 if self.__waitNewBlock():
1038 self.lastUTTime = self.basicHeaderObj.utc
869 self.lastUTTime = self.basicHeaderObj.utc
1039 return 1
870 return 1
1040 # if self.server is None:
871
1041 if not(self.setNextFile()):
872 if not(self.setNextFile()):
1042 return 0
873 return 0
1043
874
1044 deltaTime = self.basicHeaderObj.utc - self.lastUTTime
875 deltaTime = self.basicHeaderObj.utc - self.lastUTTime
1045 self.lastUTTime = self.basicHeaderObj.utc
876 self.lastUTTime = self.basicHeaderObj.utc
1046
877
1047 self.flagDiscontinuousBlock = 0
878 self.flagDiscontinuousBlock = 0
1048
879
1049 if deltaTime > self.maxTimeStep:
880 if deltaTime > self.maxTimeStep:
1050 self.flagDiscontinuousBlock = 1
881 self.flagDiscontinuousBlock = 1
1051
882
1052 return 1
883 return 1
1053
884
1054 def readNextBlock(self):
885 def readNextBlock(self):
1055
886
1056 # Skip block out of startTime and endTime
1057 while True:
887 while True:
1058 if not(self.__setNewBlock()):
888 self.__setNewBlock()
1059 raise schainpy.admin.SchainWarning('No more files to read')
1060
889
1061 if not(self.readBlock()):
890 if not(self.readBlock()):
1062 return 0
891 return 0
1063
892
1064 self.getBasicHeader()
893 self.getBasicHeader()
1065 if (self.dataOut.datatime < datetime.datetime.combine(self.startDate, self.startTime)) or (self.dataOut.datatime > datetime.datetime.combine(self.endDate, self.endTime)):
894 if (self.dataOut.datatime < datetime.datetime.combine(self.startDate, self.startTime)) or (self.dataOut.datatime > datetime.datetime.combine(self.endDate, self.endTime)):
1066 print("[Reading] Block No. %d/%d -> %s [Skipping]" % (self.nReadBlocks,
895 print("[Reading] Block No. %d/%d -> %s [Skipping]" % (self.nReadBlocks,
1067 self.processingHeaderObj.dataBlocksPerFile,
896 self.processingHeaderObj.dataBlocksPerFile,
1068 self.dataOut.datatime.ctime()))
897 self.dataOut.datatime.ctime()))
1069 continue
898 continue
1070
899
1071 break
900 break
1072
901
1073 if self.verbose:
902 if self.verbose:
1074 print("[Reading] Block No. %d/%d -> %s" % (self.nReadBlocks,
903 print("[Reading] Block No. %d/%d -> %s" % (self.nReadBlocks,
1075 self.processingHeaderObj.dataBlocksPerFile,
904 self.processingHeaderObj.dataBlocksPerFile,
1076 self.dataOut.datatime.ctime()))
905 self.dataOut.datatime.ctime()))
1077 return 1
906 return 1
1078
907
1079 def __readFirstHeader(self):
908 def readFirstHeader(self):
1080
909
1081 self.basicHeaderObj.read(self.fp)
910 self.basicHeaderObj.read(self.fp)
1082 self.systemHeaderObj.read(self.fp)
911 self.systemHeaderObj.read(self.fp)
1083 self.radarControllerHeaderObj.read(self.fp)
912 self.radarControllerHeaderObj.read(self.fp)
1084 self.processingHeaderObj.read(self.fp)
913 self.processingHeaderObj.read(self.fp)
1085
1086 self.firstHeaderSize = self.basicHeaderObj.size
914 self.firstHeaderSize = self.basicHeaderObj.size
1087
915
1088 datatype = int(numpy.log2((self.processingHeaderObj.processFlags &
916 datatype = int(numpy.log2((self.processingHeaderObj.processFlags &
1089 PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR))
917 PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR))
1090 if datatype == 0:
918 if datatype == 0:
1091 datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
919 datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
1092 elif datatype == 1:
920 elif datatype == 1:
1093 datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
921 datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
1094 elif datatype == 2:
922 elif datatype == 2:
1095 datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
923 datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
1096 elif datatype == 3:
924 elif datatype == 3:
1097 datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
925 datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
1098 elif datatype == 4:
926 elif datatype == 4:
1099 datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
927 datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
1100 elif datatype == 5:
928 elif datatype == 5:
1101 datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
929 datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
1102 else:
930 else:
1103 raise ValueError('Data type was not defined')
931 raise ValueError('Data type was not defined')
1104
932
1105 self.dtype = datatype_str
933 self.dtype = datatype_str
1106 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
934 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
1107 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \
935 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \
1108 self.firstHeaderSize + self.basicHeaderSize * \
936 self.firstHeaderSize + self.basicHeaderSize * \
1109 (self.processingHeaderObj.dataBlocksPerFile - 1)
937 (self.processingHeaderObj.dataBlocksPerFile - 1)
1110 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
938 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
1111 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
939 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
1112 self.getBlockDimension()
940 self.getBlockDimension()
1113
941
1114 def __verifyFile(self, filename, msgFlag=True):
942 def verifyFile(self, filename, msgFlag=True):
1115
943
1116 msg = None
944 msg = None
1117
945
1118 try:
946 try:
1119 fp = open(filename, 'rb')
947 fp = open(filename, 'rb')
1120 except IOError:
948 except IOError:
1121
949
1122 if msgFlag:
950 if msgFlag:
1123 print("[Reading] File %s can't be opened" % (filename))
951 print("[Reading] File %s can't be opened" % (filename))
1124
952
1125 return False
953 return False
1126
954
1127 currentPosition = fp.tell()
955 currentPosition = fp.tell()
1128 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
956 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
1129
957
1130 if neededSize == 0:
958 if neededSize == 0:
1131 basicHeaderObj = BasicHeader(LOCALTIME)
959 basicHeaderObj = BasicHeader(LOCALTIME)
1132 systemHeaderObj = SystemHeader()
960 systemHeaderObj = SystemHeader()
1133 radarControllerHeaderObj = RadarControllerHeader()
961 radarControllerHeaderObj = RadarControllerHeader()
1134 processingHeaderObj = ProcessingHeader()
962 processingHeaderObj = ProcessingHeader()
1135
963
1136 if not(basicHeaderObj.read(fp)):
964 if not(basicHeaderObj.read(fp)):
1137 fp.close()
965 fp.close()
1138 return False
966 return False
1139
967
1140 if not(systemHeaderObj.read(fp)):
968 if not(systemHeaderObj.read(fp)):
1141 fp.close()
969 fp.close()
1142 return False
970 return False
1143
971
1144 if not(radarControllerHeaderObj.read(fp)):
972 if not(radarControllerHeaderObj.read(fp)):
1145 fp.close()
973 fp.close()
1146 return False
974 return False
1147
975
1148 if not(processingHeaderObj.read(fp)):
976 if not(processingHeaderObj.read(fp)):
1149 fp.close()
977 fp.close()
1150 return False
978 return False
1151
979
1152 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
980 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
1153 else:
981 else:
1154 msg = "[Reading] Skipping the file %s due to it hasn't enough data" % filename
982 msg = "[Reading] Skipping the file %s due to it hasn't enough data" % filename
1155
983
1156 fp.close()
984 fp.close()
1157
985
1158 fileSize = os.path.getsize(filename)
986 fileSize = os.path.getsize(filename)
1159 currentSize = fileSize - currentPosition
987 currentSize = fileSize - currentPosition
1160
988
1161 if currentSize < neededSize:
989 if currentSize < neededSize:
1162 if msgFlag and (msg != None):
990 if msgFlag and (msg != None):
1163 print(msg)
991 print(msg)
1164 return False
992 return False
1165
993
1166 return True
994 return True
1167
995
1168 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
996 def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False):
1169
997
1170 path_empty = True
998 path_empty = True
1171
999
1172 dateList = []
1000 dateList = []
1173 pathList = []
1001 pathList = []
1174
1002
1175 multi_path = path.split(',')
1003 multi_path = path.split(',')
1176
1004
1177 if not walk:
1005 if not walk:
1178
1006
1179 for single_path in multi_path:
1007 for single_path in multi_path:
1180
1008
1181 if not os.path.isdir(single_path):
1009 if not os.path.isdir(single_path):
1182 continue
1010 continue
1183
1011
1184 fileList = glob.glob1(single_path, "*" + ext)
1012 fileList = glob.glob1(single_path, "*" + ext)
1185
1013
1186 if not fileList:
1014 if not fileList:
1187 continue
1015 continue
1188
1016
1189 path_empty = False
1017 path_empty = False
1190
1018
1191 fileList.sort()
1019 fileList.sort()
1192
1020
1193 for thisFile in fileList:
1021 for thisFile in fileList:
1194
1022
1195 if not os.path.isfile(os.path.join(single_path, thisFile)):
1023 if not os.path.isfile(os.path.join(single_path, thisFile)):
1196 continue
1024 continue
1197
1025
1198 if not isRadarFile(thisFile):
1026 if not isRadarFile(thisFile):
1199 continue
1027 continue
1200
1028
1201 if not isFileInDateRange(thisFile, startDate, endDate):
1029 if not isFileInDateRange(thisFile, startDate, endDate):
1202 continue
1030 continue
1203
1031
1204 thisDate = getDateFromRadarFile(thisFile)
1032 thisDate = getDateFromRadarFile(thisFile)
1205
1033
1206 if thisDate in dateList or single_path in pathList:
1034 if thisDate in dateList or single_path in pathList:
1207 continue
1035 continue
1208
1036
1209 dateList.append(thisDate)
1037 dateList.append(thisDate)
1210 pathList.append(single_path)
1038 pathList.append(single_path)
1211
1039
1212 else:
1040 else:
1213 for single_path in multi_path:
1041 for single_path in multi_path:
1214
1042
1215 if not os.path.isdir(single_path):
1043 if not os.path.isdir(single_path):
1216 continue
1044 continue
1217
1045
1218 dirList = []
1046 dirList = []
1219
1047
1220 for thisPath in os.listdir(single_path):
1048 for thisPath in os.listdir(single_path):
1221
1049
1222 if not os.path.isdir(os.path.join(single_path, thisPath)):
1050 if not os.path.isdir(os.path.join(single_path, thisPath)):
1223 continue
1051 continue
1224
1052
1225 if not isRadarFolder(thisPath):
1053 if not isRadarFolder(thisPath):
1226 continue
1054 continue
1227
1055
1228 if not isFolderInDateRange(thisPath, startDate, endDate):
1056 if not isFolderInDateRange(thisPath, startDate, endDate):
1229 continue
1057 continue
1230
1058
1231 dirList.append(thisPath)
1059 dirList.append(thisPath)
1232
1060
1233 if not dirList:
1061 if not dirList:
1234 continue
1062 continue
1235
1063
1236 dirList.sort()
1064 dirList.sort()
1237
1065
1238 for thisDir in dirList:
1066 for thisDir in dirList:
1239
1067
1240 datapath = os.path.join(single_path, thisDir, expLabel)
1068 datapath = os.path.join(single_path, thisDir, expLabel)
1241 fileList = glob.glob1(datapath, "*" + ext)
1069 fileList = glob.glob1(datapath, "*" + ext)
1242
1070
1243 if not fileList:
1071 if not fileList:
1244 continue
1072 continue
1245
1073
1246 path_empty = False
1074 path_empty = False
1247
1075
1248 thisDate = getDateFromRadarFolder(thisDir)
1076 thisDate = getDateFromRadarFolder(thisDir)
1249
1077
1250 pathList.append(datapath)
1078 pathList.append(datapath)
1251 dateList.append(thisDate)
1079 dateList.append(thisDate)
1252
1080
1253 dateList.sort()
1081 dateList.sort()
1254
1082
1255 if walk:
1083 if walk:
1256 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1084 pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel)
1257 else:
1085 else:
1258 pattern_path = multi_path[0]
1086 pattern_path = multi_path[0]
1259
1087
1260 if path_empty:
1088 if path_empty:
1261 raise schainpy.admin.SchainError("[Reading] No *%s files in %s for %s to %s" % (ext, pattern_path, startDate, endDate))
1089 raise schainpy.admin.SchainError("[Reading] No *%s files in %s for %s to %s" % (ext, pattern_path, startDate, endDate))
1262 else:
1090 else:
1263 if not dateList:
1091 if not dateList:
1264 raise schainpy.admin.SchainError("[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" % (startDate, endDate, ext, path))
1092 raise schainpy.admin.SchainError("[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" % (startDate, endDate, ext, path))
1265
1093
1266 if include_path:
1094 if include_path:
1267 return dateList, pathList
1095 return dateList, pathList
1268
1096
1269 return dateList
1097 return dateList
1270
1098
1271 def setup(self,
1099 def setup(self, **kwargs):
1272 path=None,
1100
1273 startDate=None,
1101 self.set_kwargs(**kwargs)
1274 endDate=None,
1102 if not self.ext.startswith('.'):
1275 startTime=datetime.time(0, 0, 0),
1103 self.ext = '.{}'.format(self.ext)
1276 endTime=datetime.time(23, 59, 59),
1104
1277 set=None,
1105 if self.server is not None:
1278 expLabel="",
1106 if 'tcp://' in self.server:
1279 ext=None,
1280 online=False,
1281 delay=60,
1282 walk=True,
1283 getblock=False,
1284 nTxs=1,
1285 realtime=False,
1286 blocksize=None,
1287 blocktime=None,
1288 skip=None,
1289 cursor=None,
1290 warnings=True,
1291 verbose=True,
1292 server=None,
1293 format=None,
1294 oneDDict=None,
1295 twoDDict=None,
1296 independentParam=None):
1297
1298 self.online = online
1299 self.realtime = realtime
1300 self.delay = delay
1301 self.getByBlock = getblock
1302 self.nTxs = nTxs
1303 self.startTime = startTime
1304 self.endTime = endTime
1305 self.endDate = endDate
1306 self.startDate = startDate
1307
1308 if server is not None:
1309 if 'tcp://' in server:
1310 address = server
1107 address = server
1311 else:
1108 else:
1312 address = 'ipc:///tmp/%s' % server
1109 address = 'ipc:///tmp/%s' % self.server
1313 self.server = address
1110 self.server = address
1314 self.context = zmq.Context()
1111 self.context = zmq.Context()
1315 self.receiver = self.context.socket(zmq.PULL)
1112 self.receiver = self.context.socket(zmq.PULL)
1316 self.receiver.connect(self.server)
1113 self.receiver.connect(self.server)
1317 time.sleep(0.5)
1114 time.sleep(0.5)
1318 print('[Starting] ReceiverData from {}'.format(self.server))
1115 print('[Starting] ReceiverData from {}'.format(self.server))
1319 else:
1116 else:
1320 self.server = None
1117 self.server = None
1321 if path == None:
1118 if self.path == None:
1322 raise ValueError("[Reading] The path is not valid")
1119 raise ValueError("[Reading] The path is not valid")
1323
1120
1324 if ext == None:
1121 if self.online:
1325 ext = self.ext
1122 log.log("[Reading] Searching files in online mode...", self.name)
1326
1327 if online:
1328 print("[Reading] Searching files in online mode...")
1329
1123
1330 for nTries in range(self.nTries):
1124 for nTries in range(self.nTries):
1331 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(
1125 fullpath = self.searchFilesOnLine(self.path, self.startDate,
1332 path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
1126 self.endDate, self.expLabel, self.ext, self.walk,
1127 self.filefmt, self.folderfmt)
1128
1129 try:
1130 fullpath = next(fullpath)
1131 except:
1132 fullpath = None
1333
1133
1334 if fullpath:
1134 if fullpath:
1335 break
1135 break
1336
1136
1337 print('[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries + 1))
1137 log.warning(
1138 'Waiting {} sec for a valid file in {}: try {} ...'.format(
1139 self.delay, self.path, nTries + 1),
1140 self.name)
1338 time.sleep(self.delay)
1141 time.sleep(self.delay)
1339
1142
1340 if not(fullpath):
1143 if not(fullpath):
1341 raise schainpy.admin.SchainError('There isn\'t any valid file in {}'.format(path))
1144 raise schainpy.admin.SchainError(
1342 return
1145 'There isn\'t any valid file in {}'.format(self.path))
1343
1146
1344 self.year = year
1147 pathname, filename = os.path.split(fullpath)
1345 self.doy = doy
1148 self.year = int(filename[1:5])
1346 self.set = set - 1
1149 self.doy = int(filename[5:8])
1347 self.path = path
1150 self.set = int(filename[8:11]) - 1
1348 self.foldercounter = foldercounter
1349 last_set = None
1350 else:
1351 print("[Reading] Searching files in offline mode ...")
1352 pathList, filenameList = self.searchFilesOffLine(path, startDate=startDate, endDate=endDate,
1353 startTime=startTime, endTime=endTime,
1354 set=set, expLabel=expLabel, ext=ext,
1355 walk=walk, cursor=cursor,
1356 skip=skip)
1357
1358 if not(pathList):
1359 self.fileIndex = -1
1360 self.pathList = []
1361 self.filenameList = []
1362 return
1363
1364 self.fileIndex = -1
1365 self.pathList = pathList
1366 self.filenameList = filenameList
1367 file_name = os.path.basename(filenameList[-1])
1368 basename, ext = os.path.splitext(file_name)
1369 last_set = int(basename[-3:])
1370
1371
1372 ext = ext.lower()
1373 self.ext = ext
1374
1375 # Added-----------------
1376 self.selBlocksize = blocksize
1377 self.selBlocktime = blocktime
1378
1379 # Verbose-----------
1380 self.verbose = verbose
1381 self.warnings = warnings
1382
1383 if not(self.setNextFile()):
1384 if (startDate != None) and (endDate != None):
1385 print("[Reading] No files in range: %s - %s" % (datetime.datetime.combine(startDate, startTime).ctime(), datetime.datetime.combine(endDate, endTime).ctime()))
1386 elif startDate != None:
1387 print("[Reading] No files in range: %s" % (datetime.datetime.combine(startDate, startTime).ctime()))
1388 else:
1151 else:
1389 print("[Reading] No files")
1152 log.log("Searching files in {}".format(self.path), self.name)
1153 self.filenameList = self.searchFilesOffLine(self.path, self.startDate,
1154 self.endDate, self.expLabel, self.ext, self.walk, self.filefmt, self.folderfmt)
1390
1155
1391 self.fileIndex = -1
1156 self.setNextFile()
1392 self.pathList = []
1393 self.filenameList = []
1394 return
1395
1157
1396 if last_set != None:
1397 self.dataOut.last_block = last_set * \
1398 self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1399 return
1158 return
1400
1159
1401 def getBasicHeader(self):
1160 def getBasicHeader(self):
1402
1161
1403 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond / \
1162 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond / \
1404 1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1163 1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1405
1164
1406 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1165 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1407
1166
1408 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1167 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1409
1168
1410 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1169 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1411
1170
1412 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1171 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1413
1172
1414 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1173 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1415
1174
1416 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
1175 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
1417
1176
1418 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1177 # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1419
1178
1420 def getFirstHeader(self):
1179 def getFirstHeader(self):
1421
1180
1422 raise NotImplementedError
1181 raise NotImplementedError
1423
1182
1424 def getData(self):
1183 def getData(self):
1425
1184
1426 raise NotImplementedError
1185 raise NotImplementedError
1427
1186
1428 def hasNotDataInBuffer(self):
1187 def hasNotDataInBuffer(self):
1429
1188
1430 raise NotImplementedError
1189 raise NotImplementedError
1431
1190
1432 def readBlock(self):
1191 def readBlock(self):
1433
1192
1434 raise NotImplementedError
1193 raise NotImplementedError
1435
1194
1436 def isEndProcess(self):
1195 def isEndProcess(self):
1437
1196
1438 return self.flagNoMoreFiles
1197 return self.flagNoMoreFiles
1439
1198
1440 def printReadBlocks(self):
1199 def printReadBlocks(self):
1441
1200
1442 print("[Reading] Number of read blocks per file %04d" % self.nReadBlocks)
1201 print("[Reading] Number of read blocks per file %04d" % self.nReadBlocks)
1443
1202
1444 def printTotalBlocks(self):
1203 def printTotalBlocks(self):
1445
1204
1446 print("[Reading] Number of read blocks %04d" % self.nTotalBlocks)
1205 print("[Reading] Number of read blocks %04d" % self.nTotalBlocks)
1447
1206
1448 def printNumberOfBlock(self):
1207 def printNumberOfBlock(self):
1449 'SPAM!'
1208 'SPAM!'
1450
1209
1451 # if self.flagIsNewBlock:
1210 # if self.flagIsNewBlock:
1452 # print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1211 # print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks,
1453 # self.processingHeaderObj.dataBlocksPerFile,
1212 # self.processingHeaderObj.dataBlocksPerFile,
1454 # self.dataOut.datatime.ctime())
1213 # self.dataOut.datatime.ctime())
1455
1214
1456 def printInfo(self):
1215 def printInfo(self):
1457
1216
1458 if self.__printInfo == False:
1217 if self.__printInfo == False:
1459 return
1218 return
1460
1219
1461 self.basicHeaderObj.printInfo()
1220 self.basicHeaderObj.printInfo()
1462 self.systemHeaderObj.printInfo()
1221 self.systemHeaderObj.printInfo()
1463 self.radarControllerHeaderObj.printInfo()
1222 self.radarControllerHeaderObj.printInfo()
1464 self.processingHeaderObj.printInfo()
1223 self.processingHeaderObj.printInfo()
1465
1224
1466 self.__printInfo = False
1225 self.__printInfo = False
1467
1226
1468 def run(self,
1227 def run(self, **kwargs):
1469 path=None,
1228 """
1470 startDate=None,
1229
1471 endDate=None,
1230 Arguments:
1472 startTime=datetime.time(0, 0, 0),
1231 path :
1473 endTime=datetime.time(23, 59, 59),
1232 startDate :
1474 set=None,
1233 endDate :
1475 expLabel="",
1234 startTime :
1476 ext=None,
1235 endTime :
1477 online=False,
1236 set :
1478 delay=60,
1237 expLabel :
1479 walk=True,
1238 ext :
1480 getblock=False,
1239 online :
1481 nTxs=1,
1240 delay :
1482 realtime=False,
1241 walk :
1483 blocksize=None,
1242 getblock :
1484 blocktime=None,
1243 nTxs :
1485 skip=None,
1244 realtime :
1486 cursor=None,
1245 blocksize :
1487 warnings=True,
1246 blocktime :
1488 server=None,
1247 skip :
1489 verbose=True,
1248 cursor :
1490 format=None,
1249 warnings :
1491 oneDDict=None,
1250 server :
1492 twoDDict=None,
1251 verbose :
1493 independentParam=None, **kwargs):
1252 format :
1253 oneDDict :
1254 twoDDict :
1255 independentParam :
1256 """
1494
1257
1495 if not(self.isConfig):
1258 if not(self.isConfig):
1496 self.setup(path=path,
1259 self.setup(**kwargs)
1497 startDate=startDate,
1498 endDate=endDate,
1499 startTime=startTime,
1500 endTime=endTime,
1501 set=set,
1502 expLabel=expLabel,
1503 ext=ext,
1504 online=online,
1505 delay=delay,
1506 walk=walk,
1507 getblock=getblock,
1508 nTxs=nTxs,
1509 realtime=realtime,
1510 blocksize=blocksize,
1511 blocktime=blocktime,
1512 skip=skip,
1513 cursor=cursor,
1514 warnings=warnings,
1515 server=server,
1516 verbose=verbose,
1517 format=format,
1518 oneDDict=oneDDict,
1519 twoDDict=twoDDict,
1520 independentParam=independentParam)
1521 self.isConfig = True
1260 self.isConfig = True
1522 if server is None:
1261 if self.server is None:
1523 self.getData()
1262 self.getData()
1524 else:
1263 else:
1525 self.getFromServer()
1264 self.getFromServer()
1526
1265
1527
1266
1528 class JRODataWriter(JRODataIO):
1267 class JRODataWriter(Reader):
1529
1268
1530 """
1269 """
1531 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1270 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1532 de los datos siempre se realiza por bloques.
1271 de los datos siempre se realiza por bloques.
1533 """
1272 """
1534
1273
1535 blockIndex = 0
1536
1537 path = None
1538
1539 setFile = None
1274 setFile = None
1540
1541 profilesPerBlock = None
1275 profilesPerBlock = None
1542
1543 blocksPerFile = None
1276 blocksPerFile = None
1544
1545 nWriteBlocks = 0
1277 nWriteBlocks = 0
1546
1547 fileDate = None
1278 fileDate = None
1548
1279
1549 def __init__(self, dataOut=None):
1280 def __init__(self, dataOut=None):
1550 raise NotImplementedError
1281 raise NotImplementedError
1551
1282
1552 def hasAllDataInBuffer(self):
1283 def hasAllDataInBuffer(self):
1553 raise NotImplementedError
1284 raise NotImplementedError
1554
1285
1555 def setBlockDimension(self):
1286 def setBlockDimension(self):
1556 raise NotImplementedError
1287 raise NotImplementedError
1557
1288
1558 def writeBlock(self):
1289 def writeBlock(self):
1559 raise NotImplementedError
1290 raise NotImplementedError
1560
1291
1561 def putData(self):
1292 def putData(self):
1562 raise NotImplementedError
1293 raise NotImplementedError
1563
1294
1295 def getDtypeWidth(self):
1296
1297 dtype_index = get_dtype_index(self.dtype)
1298 dtype_width = get_dtype_width(dtype_index)
1299
1300 return dtype_width
1301
1564 def getProcessFlags(self):
1302 def getProcessFlags(self):
1565
1303
1566 processFlags = 0
1304 processFlags = 0
1567
1305
1568 dtype_index = get_dtype_index(self.dtype)
1306 dtype_index = get_dtype_index(self.dtype)
1569 procflag_dtype = get_procflag_dtype(dtype_index)
1307 procflag_dtype = get_procflag_dtype(dtype_index)
1570
1308
1571 processFlags += procflag_dtype
1309 processFlags += procflag_dtype
1572
1310
1573 if self.dataOut.flagDecodeData:
1311 if self.dataOut.flagDecodeData:
1574 processFlags += PROCFLAG.DECODE_DATA
1312 processFlags += PROCFLAG.DECODE_DATA
1575
1313
1576 if self.dataOut.flagDeflipData:
1314 if self.dataOut.flagDeflipData:
1577 processFlags += PROCFLAG.DEFLIP_DATA
1315 processFlags += PROCFLAG.DEFLIP_DATA
1578
1316
1579 if self.dataOut.code is not None:
1317 if self.dataOut.code is not None:
1580 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1318 processFlags += PROCFLAG.DEFINE_PROCESS_CODE
1581
1319
1582 if self.dataOut.nCohInt > 1:
1320 if self.dataOut.nCohInt > 1:
1583 processFlags += PROCFLAG.COHERENT_INTEGRATION
1321 processFlags += PROCFLAG.COHERENT_INTEGRATION
1584
1322
1585 if self.dataOut.type == "Spectra":
1323 if self.dataOut.type == "Spectra":
1586 if self.dataOut.nIncohInt > 1:
1324 if self.dataOut.nIncohInt > 1:
1587 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1325 processFlags += PROCFLAG.INCOHERENT_INTEGRATION
1588
1326
1589 if self.dataOut.data_dc is not None:
1327 if self.dataOut.data_dc is not None:
1590 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1328 processFlags += PROCFLAG.SAVE_CHANNELS_DC
1591
1329
1592 if self.dataOut.flagShiftFFT:
1330 if self.dataOut.flagShiftFFT:
1593 processFlags += PROCFLAG.SHIFT_FFT_DATA
1331 processFlags += PROCFLAG.SHIFT_FFT_DATA
1594
1332
1595 return processFlags
1333 return processFlags
1596
1334
1597 def setBasicHeader(self):
1335 def setBasicHeader(self):
1598
1336
1599 self.basicHeaderObj.size = self.basicHeaderSize # bytes
1337 self.basicHeaderObj.size = self.basicHeaderSize # bytes
1600 self.basicHeaderObj.version = self.versionFile
1338 self.basicHeaderObj.version = self.versionFile
1601 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1339 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1602 utc = numpy.floor(self.dataOut.utctime)
1340 utc = numpy.floor(self.dataOut.utctime)
1603 milisecond = (self.dataOut.utctime - utc) * 1000.0
1341 milisecond = (self.dataOut.utctime - utc) * 1000.0
1604 self.basicHeaderObj.utc = utc
1342 self.basicHeaderObj.utc = utc
1605 self.basicHeaderObj.miliSecond = milisecond
1343 self.basicHeaderObj.miliSecond = milisecond
1606 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1344 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1607 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1345 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1608 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1346 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1609
1347
1610 def setFirstHeader(self):
1348 def setFirstHeader(self):
1611 """
1349 """
1612 Obtiene una copia del First Header
1350 Obtiene una copia del First Header
1613
1351
1614 Affected:
1352 Affected:
1615
1353
1616 self.basicHeaderObj
1354 self.basicHeaderObj
1617 self.systemHeaderObj
1355 self.systemHeaderObj
1618 self.radarControllerHeaderObj
1356 self.radarControllerHeaderObj
1619 self.processingHeaderObj self.
1357 self.processingHeaderObj self.
1620
1358
1621 Return:
1359 Return:
1622 None
1360 None
1623 """
1361 """
1624
1362
1625 raise NotImplementedError
1363 raise NotImplementedError
1626
1364
1627 def __writeFirstHeader(self):
1365 def __writeFirstHeader(self):
1628 """
1366 """
1629 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1367 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1630
1368
1631 Affected:
1369 Affected:
1632 __dataType
1370 __dataType
1633
1371
1634 Return:
1372 Return:
1635 None
1373 None
1636 """
1374 """
1637
1375
1638 # CALCULAR PARAMETROS
1376 # CALCULAR PARAMETROS
1639
1377
1640 sizeLongHeader = self.systemHeaderObj.size + \
1378 sizeLongHeader = self.systemHeaderObj.size + \
1641 self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1379 self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1642 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1380 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1643
1381
1644 self.basicHeaderObj.write(self.fp)
1382 self.basicHeaderObj.write(self.fp)
1645 self.systemHeaderObj.write(self.fp)
1383 self.systemHeaderObj.write(self.fp)
1646 self.radarControllerHeaderObj.write(self.fp)
1384 self.radarControllerHeaderObj.write(self.fp)
1647 self.processingHeaderObj.write(self.fp)
1385 self.processingHeaderObj.write(self.fp)
1648
1386
1649 def __setNewBlock(self):
1387 def __setNewBlock(self):
1650 """
1388 """
1651 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1389 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1652
1390
1653 Return:
1391 Return:
1654 0 : si no pudo escribir nada
1392 0 : si no pudo escribir nada
1655 1 : Si escribio el Basic el First Header
1393 1 : Si escribio el Basic el First Header
1656 """
1394 """
1657 if self.fp == None:
1395 if self.fp == None:
1658 self.setNextFile()
1396 self.setNextFile()
1659
1397
1660 if self.flagIsNewFile:
1398 if self.flagIsNewFile:
1661 return 1
1399 return 1
1662
1400
1663 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1401 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1664 self.basicHeaderObj.write(self.fp)
1402 self.basicHeaderObj.write(self.fp)
1665 return 1
1403 return 1
1666
1404
1667 if not(self.setNextFile()):
1405 if not(self.setNextFile()):
1668 return 0
1406 return 0
1669
1407
1670 return 1
1408 return 1
1671
1409
1672 def writeNextBlock(self):
1410 def writeNextBlock(self):
1673 """
1411 """
1674 Selecciona el bloque siguiente de datos y los escribe en un file
1412 Selecciona el bloque siguiente de datos y los escribe en un file
1675
1413
1676 Return:
1414 Return:
1677 0 : Si no hizo pudo escribir el bloque de datos
1415 0 : Si no hizo pudo escribir el bloque de datos
1678 1 : Si no pudo escribir el bloque de datos
1416 1 : Si no pudo escribir el bloque de datos
1679 """
1417 """
1680 if not(self.__setNewBlock()):
1418 if not(self.__setNewBlock()):
1681 return 0
1419 return 0
1682
1420
1683 self.writeBlock()
1421 self.writeBlock()
1684
1422
1685 print("[Writing] Block No. %d/%d" % (self.blockIndex,
1423 print("[Writing] Block No. %d/%d" % (self.blockIndex,
1686 self.processingHeaderObj.dataBlocksPerFile))
1424 self.processingHeaderObj.dataBlocksPerFile))
1687
1425
1688 return 1
1426 return 1
1689
1427
1690 def setNextFile(self):
1428 def setNextFile(self):
1691 """
1429 """Determina el siguiente file que sera escrito
1692 Determina el siguiente file que sera escrito
1693
1430
1694 Affected:
1431 Affected:
1695 self.filename
1432 self.filename
1696 self.subfolder
1433 self.subfolder
1697 self.fp
1434 self.fp
1698 self.setFile
1435 self.setFile
1699 self.flagIsNewFile
1436 self.flagIsNewFile
1700
1437
1701 Return:
1438 Return:
1702 0 : Si el archivo no puede ser escrito
1439 0 : Si el archivo no puede ser escrito
1703 1 : Si el archivo esta listo para ser escrito
1440 1 : Si el archivo esta listo para ser escrito
1704 """
1441 """
1705 ext = self.ext
1442 ext = self.ext
1706 path = self.path
1443 path = self.path
1707
1444
1708 if self.fp != None:
1445 if self.fp != None:
1709 self.fp.close()
1446 self.fp.close()
1710
1447
1448 if not os.path.exists(path):
1449 os.mkdir(path)
1450
1711 timeTuple = time.localtime(self.dataOut.utctime)
1451 timeTuple = time.localtime(self.dataOut.utctime)
1712 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year, timeTuple.tm_yday)
1452 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year, timeTuple.tm_yday)
1713
1453
1714 fullpath = os.path.join(path, subfolder)
1454 fullpath = os.path.join(path, subfolder)
1715 setFile = self.setFile
1455 setFile = self.setFile
1716
1456
1717 if not(os.path.exists(fullpath)):
1457 if not(os.path.exists(fullpath)):
1718 os.mkdir(fullpath)
1458 os.mkdir(fullpath)
1719 setFile = -1 # inicializo mi contador de seteo
1459 setFile = -1 # inicializo mi contador de seteo
1720 else:
1460 else:
1721 filesList = os.listdir(fullpath)
1461 filesList = os.listdir(fullpath)
1722 if len(filesList) > 0:
1462 if len(filesList) > 0:
1723 filesList = sorted(filesList, key=str.lower)
1463 filesList = sorted(filesList, key=str.lower)
1724 filen = filesList[-1]
1464 filen = filesList[-1]
1725 # el filename debera tener el siguiente formato
1465 # el filename debera tener el siguiente formato
1726 # 0 1234 567 89A BCDE (hex)
1466 # 0 1234 567 89A BCDE (hex)
1727 # x YYYY DDD SSS .ext
1467 # x YYYY DDD SSS .ext
1728 if isNumber(filen[8:11]):
1468 if isNumber(filen[8:11]):
1729 # inicializo mi contador de seteo al seteo del ultimo file
1469 # inicializo mi contador de seteo al seteo del ultimo file
1730 setFile = int(filen[8:11])
1470 setFile = int(filen[8:11])
1731 else:
1471 else:
1732 setFile = -1
1472 setFile = -1
1733 else:
1473 else:
1734 setFile = -1 # inicializo mi contador de seteo
1474 setFile = -1 # inicializo mi contador de seteo
1735
1475
1736 setFile += 1
1476 setFile += 1
1737
1477
1738 # If this is a new day it resets some values
1478 # If this is a new day it resets some values
1739 if self.dataOut.datatime.date() > self.fileDate:
1479 if self.dataOut.datatime.date() > self.fileDate:
1740 setFile = 0
1480 setFile = 0
1741 self.nTotalBlocks = 0
1481 self.nTotalBlocks = 0
1742
1482
1743 filen = '{}{:04d}{:03d}{:03d}{}'.format(
1483 filen = '{}{:04d}{:03d}{:03d}{}'.format(
1744 self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext)
1484 self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext)
1745
1485
1746 filename = os.path.join(path, subfolder, filen)
1486 filename = os.path.join(path, subfolder, filen)
1747
1487
1748 fp = open(filename, 'wb')
1488 fp = open(filename, 'wb')
1749
1489
1750 self.blockIndex = 0
1490 self.blockIndex = 0
1751
1752 # guardando atributos
1753 self.filename = filename
1491 self.filename = filename
1754 self.subfolder = subfolder
1492 self.subfolder = subfolder
1755 self.fp = fp
1493 self.fp = fp
1756 self.setFile = setFile
1494 self.setFile = setFile
1757 self.flagIsNewFile = 1
1495 self.flagIsNewFile = 1
1758 self.fileDate = self.dataOut.datatime.date()
1496 self.fileDate = self.dataOut.datatime.date()
1759
1760 self.setFirstHeader()
1497 self.setFirstHeader()
1761
1498
1762 print('[Writing] Opening file: %s' % self.filename)
1499 print('[Writing] Opening file: %s' % self.filename)
1763
1500
1764 self.__writeFirstHeader()
1501 self.__writeFirstHeader()
1765
1502
1766 return 1
1503 return 1
1767
1504
1768 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1505 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4):
1769 """
1506 """
1770 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1507 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1771
1508
1772 Inputs:
1509 Inputs:
1773 path : directory where data will be saved
1510 path : directory where data will be saved
1774 profilesPerBlock : number of profiles per block
1511 profilesPerBlock : number of profiles per block
1775 set : initial file set
1512 set : initial file set
1776 datatype : An integer number that defines data type:
1513 datatype : An integer number that defines data type:
1777 0 : int8 (1 byte)
1514 0 : int8 (1 byte)
1778 1 : int16 (2 bytes)
1515 1 : int16 (2 bytes)
1779 2 : int32 (4 bytes)
1516 2 : int32 (4 bytes)
1780 3 : int64 (8 bytes)
1517 3 : int64 (8 bytes)
1781 4 : float32 (4 bytes)
1518 4 : float32 (4 bytes)
1782 5 : double64 (8 bytes)
1519 5 : double64 (8 bytes)
1783
1520
1784 Return:
1521 Return:
1785 0 : Si no realizo un buen seteo
1522 0 : Si no realizo un buen seteo
1786 1 : Si realizo un buen seteo
1523 1 : Si realizo un buen seteo
1787 """
1524 """
1788
1525
1789 if ext == None:
1526 if ext == None:
1790 ext = self.ext
1527 ext = self.ext
1791
1528
1792 self.ext = ext.lower()
1529 self.ext = ext.lower()
1793
1530
1794 self.path = path
1531 self.path = path
1795
1532
1796 if set is None:
1533 if set is None:
1797 self.setFile = -1
1534 self.setFile = -1
1798 else:
1535 else:
1799 self.setFile = set - 1
1536 self.setFile = set - 1
1800
1537
1801 self.blocksPerFile = blocksPerFile
1538 self.blocksPerFile = blocksPerFile
1802
1803 self.profilesPerBlock = profilesPerBlock
1539 self.profilesPerBlock = profilesPerBlock
1804
1805 self.dataOut = dataOut
1540 self.dataOut = dataOut
1806 self.fileDate = self.dataOut.datatime.date()
1541 self.fileDate = self.dataOut.datatime.date()
1807 # By default
1808 self.dtype = self.dataOut.dtype
1542 self.dtype = self.dataOut.dtype
1809
1543
1810 if datatype is not None:
1544 if datatype is not None:
1811 self.dtype = get_numpy_dtype(datatype)
1545 self.dtype = get_numpy_dtype(datatype)
1812
1546
1813 if not(self.setNextFile()):
1547 if not(self.setNextFile()):
1814 print("[Writing] There isn't a next file")
1548 print("[Writing] There isn't a next file")
1815 return 0
1549 return 0
1816
1550
1817 self.setBlockDimension()
1551 self.setBlockDimension()
1818
1552
1819 return 1
1553 return 1
1820
1554
1821 def run(self, dataOut, path, blocksPerFile=100, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1555 def run(self, dataOut, path, blocksPerFile=100, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs):
1822
1556
1823 if not(self.isConfig):
1557 if not(self.isConfig):
1824
1558
1825 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock,
1559 self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock,
1826 set=set, ext=ext, datatype=datatype, **kwargs)
1560 set=set, ext=ext, datatype=datatype, **kwargs)
1827 self.isConfig = True
1561 self.isConfig = True
1828
1562
1829 self.dataOut = dataOut
1563 self.dataOut = dataOut
1830 self.putData()
1564 self.putData()
1831 return self.dataOut
1565 return self.dataOut
@@ -1,675 +1,527
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 numpy
6 import numpy
7
7
8 from schainpy.model.io.jroIO_base import LOCALTIME, JRODataReader, JRODataWriter
8 from schainpy.model.io.jroIO_base import LOCALTIME, JRODataReader, JRODataWriter
9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
9 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
10 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
10 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
11 from schainpy.model.data.jrodata import Spectra
11 from schainpy.model.data.jrodata import Spectra
12 from schainpy.utils import log
12 from schainpy.utils import log
13
13
14 @MPDecorator
14 @MPDecorator
15 class SpectraReader(JRODataReader, ProcessingUnit):
15 class SpectraReader(JRODataReader, ProcessingUnit):
16 """
16 """
17 Esta clase permite leer datos de espectros desde archivos procesados (.pdata). La lectura
17 Esta clase permite leer datos de espectros desde archivos procesados (.pdata). La lectura
18 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones)
18 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones)
19 son almacenados en tres buffer's para el Self Spectra, el Cross Spectra y el DC Channel.
19 son almacenados en tres buffer's para el Self Spectra, el Cross Spectra y el DC Channel.
20
20
21 paresCanalesIguales * alturas * perfiles (Self Spectra)
21 paresCanalesIguales * alturas * perfiles (Self Spectra)
22 paresCanalesDiferentes * alturas * perfiles (Cross Spectra)
22 paresCanalesDiferentes * alturas * perfiles (Cross Spectra)
23 canales * alturas (DC Channels)
23 canales * alturas (DC Channels)
24
24
25 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
25 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
26 RadarControllerHeader y Spectra. Los tres primeros se usan para almacenar informacion de la
26 RadarControllerHeader y Spectra. Los tres primeros se usan para almacenar informacion de la
27 cabecera de datos (metadata), y el cuarto (Spectra) para obtener y almacenar un bloque de
27 cabecera de datos (metadata), y el cuarto (Spectra) para obtener y almacenar un bloque de
28 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
28 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
29
29
30 Example:
30 Example:
31 dpath = "/home/myuser/data"
31 dpath = "/home/myuser/data"
32
32
33 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
33 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
34
34
35 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
35 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
36
36
37 readerObj = SpectraReader()
37 readerObj = SpectraReader()
38
38
39 readerObj.setup(dpath, startTime, endTime)
39 readerObj.setup(dpath, startTime, endTime)
40
40
41 while(True):
41 while(True):
42
42
43 readerObj.getData()
43 readerObj.getData()
44
44
45 print readerObj.data_spc
45 print readerObj.data_spc
46
46
47 print readerObj.data_cspc
47 print readerObj.data_cspc
48
48
49 print readerObj.data_dc
49 print readerObj.data_dc
50
50
51 if readerObj.flagNoMoreFiles:
51 if readerObj.flagNoMoreFiles:
52 break
52 break
53
53
54 """
54 """
55
55
56 pts2read_SelfSpectra = 0
57
58 pts2read_CrossSpectra = 0
59
60 pts2read_DCchannels = 0
61
62 ext = ".pdata"
63
64 optchar = "P"
65
66 dataOut = None
67
68 nRdChannels = None
69
70 nRdPairs = None
71
72 rdPairList = []
73
74 def __init__(self):#, **kwargs):
56 def __init__(self):#, **kwargs):
75 """
57 """
76 Inicializador de la clase SpectraReader para la lectura de datos de espectros.
58 Inicializador de la clase SpectraReader para la lectura de datos de espectros.
77
59
78 Inputs:
60 Inputs:
79 dataOut : Objeto de la clase Spectra. Este objeto sera utilizado para
61 dataOut : Objeto de la clase Spectra. Este objeto sera utilizado para
80 almacenar un perfil de datos cada vez que se haga un requerimiento
62 almacenar un perfil de datos cada vez que se haga un requerimiento
81 (getData). El perfil sera obtenido a partir del buffer de datos,
63 (getData). El perfil sera obtenido a partir del buffer de datos,
82 si el buffer esta vacio se hara un nuevo proceso de lectura de un
64 si el buffer esta vacio se hara un nuevo proceso de lectura de un
83 bloque de datos.
65 bloque de datos.
84 Si este parametro no es pasado se creara uno internamente.
66 Si este parametro no es pasado se creara uno internamente.
85
67
86 Affected:
68 Affected:
87 self.dataOut
69 self.dataOut
88
70
89 Return : None
71 Return : None
90 """
72 """
91
73
92 #Eliminar de la base la herencia
74 ProcessingUnit.__init__(self)
93 ProcessingUnit.__init__(self)#, **kwargs)
94
95
75
96 self.pts2read_SelfSpectra = 0
76 self.pts2read_SelfSpectra = 0
97
98 self.pts2read_CrossSpectra = 0
77 self.pts2read_CrossSpectra = 0
99
100 self.pts2read_DCchannels = 0
78 self.pts2read_DCchannels = 0
101
102 self.datablock = None
103
104 self.utc = None
105
106 self.ext = ".pdata"
79 self.ext = ".pdata"
107
108 self.optchar = "P"
80 self.optchar = "P"
109
110 self.basicHeaderObj = BasicHeader(LOCALTIME)
81 self.basicHeaderObj = BasicHeader(LOCALTIME)
111
112 self.systemHeaderObj = SystemHeader()
82 self.systemHeaderObj = SystemHeader()
113
114 self.radarControllerHeaderObj = RadarControllerHeader()
83 self.radarControllerHeaderObj = RadarControllerHeader()
115
116 self.processingHeaderObj = ProcessingHeader()
84 self.processingHeaderObj = ProcessingHeader()
117
118 self.online = 0
119
120 self.fp = None
121
122 self.idFile = None
123
124 self.dtype = None
125
126 self.fileSizeByHeader = None
127
128 self.filenameList = []
129
130 self.filename = None
131
132 self.fileSize = None
133
134 self.firstHeaderSize = 0
135
136 self.basicHeaderSize = 24
137
138 self.pathList = []
139
140 self.lastUTTime = 0
85 self.lastUTTime = 0
141
142 self.maxTimeStep = 30
86 self.maxTimeStep = 30
143
87 self.dataOut = Spectra()
144 self.flagNoMoreFiles = 0
88 self.profileIndex = 1
145
89 self.nRdChannels = None
146 self.set = 0
90 self.nRdPairs = None
147
91 self.rdPairList = []
148 self.path = None
149
150 self.delay = 60 #seconds
151
152 self.nTries = 3 #quantity tries
153
154 self.nFiles = 3 #number of files for searching
155
156 self.nReadBlocks = 0
157
158 self.flagIsNewFile = 1
159
160 self.__isFirstTimeOnline = 1
161
162
163 self.flagDiscontinuousBlock = 0
164
165 self.flagIsNewBlock = 0
166
167 self.nTotalBlocks = 0
168
169 self.blocksize = 0
170
171 self.dataOut = self.createObjByDefault()
172
173 self.profileIndex = 1 #Always
174
175
92
176 def createObjByDefault(self):
93 def createObjByDefault(self):
177
94
178 dataObj = Spectra()
95 dataObj = Spectra()
179
96
180 return dataObj
97 return dataObj
181
98
182 def __hasNotDataInBuffer(self):
99 def __hasNotDataInBuffer(self):
183 return 1
100 return 1
184
101
185
102
186 def getBlockDimension(self):
103 def getBlockDimension(self):
187 """
104 """
188 Obtiene la cantidad de puntos a leer por cada bloque de datos
105 Obtiene la cantidad de puntos a leer por cada bloque de datos
189
106
190 Affected:
107 Affected:
191 self.nRdChannels
108 self.nRdChannels
192 self.nRdPairs
109 self.nRdPairs
193 self.pts2read_SelfSpectra
110 self.pts2read_SelfSpectra
194 self.pts2read_CrossSpectra
111 self.pts2read_CrossSpectra
195 self.pts2read_DCchannels
112 self.pts2read_DCchannels
196 self.blocksize
113 self.blocksize
197 self.dataOut.nChannels
114 self.dataOut.nChannels
198 self.dataOut.nPairs
115 self.dataOut.nPairs
199
116
200 Return:
117 Return:
201 None
118 None
202 """
119 """
203 self.nRdChannels = 0
120 self.nRdChannels = 0
204 self.nRdPairs = 0
121 self.nRdPairs = 0
205 self.rdPairList = []
122 self.rdPairList = []
206
123
207 for i in range(0, self.processingHeaderObj.totalSpectra*2, 2):
124 for i in range(0, self.processingHeaderObj.totalSpectra*2, 2):
208 if self.processingHeaderObj.spectraComb[i] == self.processingHeaderObj.spectraComb[i+1]:
125 if self.processingHeaderObj.spectraComb[i] == self.processingHeaderObj.spectraComb[i+1]:
209 self.nRdChannels = self.nRdChannels + 1 #par de canales iguales
126 self.nRdChannels = self.nRdChannels + 1 #par de canales iguales
210 else:
127 else:
211 self.nRdPairs = self.nRdPairs + 1 #par de canales diferentes
128 self.nRdPairs = self.nRdPairs + 1 #par de canales diferentes
212 self.rdPairList.append((self.processingHeaderObj.spectraComb[i], self.processingHeaderObj.spectraComb[i+1]))
129 self.rdPairList.append((self.processingHeaderObj.spectraComb[i], self.processingHeaderObj.spectraComb[i+1]))
213
130
214 pts2read = self.processingHeaderObj.nHeights * self.processingHeaderObj.profilesPerBlock
131 pts2read = self.processingHeaderObj.nHeights * self.processingHeaderObj.profilesPerBlock
215
132
216 self.pts2read_SelfSpectra = int(self.nRdChannels * pts2read)
133 self.pts2read_SelfSpectra = int(self.nRdChannels * pts2read)
217 self.blocksize = self.pts2read_SelfSpectra
134 self.blocksize = self.pts2read_SelfSpectra
218
135
219 if self.processingHeaderObj.flag_cspc:
136 if self.processingHeaderObj.flag_cspc:
220 self.pts2read_CrossSpectra = int(self.nRdPairs * pts2read)
137 self.pts2read_CrossSpectra = int(self.nRdPairs * pts2read)
221 self.blocksize += self.pts2read_CrossSpectra
138 self.blocksize += self.pts2read_CrossSpectra
222
139
223 if self.processingHeaderObj.flag_dc:
140 if self.processingHeaderObj.flag_dc:
224 self.pts2read_DCchannels = int(self.systemHeaderObj.nChannels * self.processingHeaderObj.nHeights)
141 self.pts2read_DCchannels = int(self.systemHeaderObj.nChannels * self.processingHeaderObj.nHeights)
225 self.blocksize += self.pts2read_DCchannels
142 self.blocksize += self.pts2read_DCchannels
226
143
227 # self.blocksize = self.pts2read_SelfSpectra + self.pts2read_CrossSpectra + self.pts2read_DCchannels
228
229
230 def readBlock(self):
144 def readBlock(self):
231 """
145 """
232 Lee el bloque de datos desde la posicion actual del puntero del archivo
146 Lee el bloque de datos desde la posicion actual del puntero del archivo
233 (self.fp) y actualiza todos los parametros relacionados al bloque de datos
147 (self.fp) y actualiza todos los parametros relacionados al bloque de datos
234 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
148 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
235 es seteado a 0
149 es seteado a 0
236
150
237 Return: None
151 Return: None
238
152
239 Variables afectadas:
153 Variables afectadas:
240
154
241 self.flagIsNewFile
155 self.flagIsNewFile
242 self.flagIsNewBlock
156 self.flagIsNewBlock
243 self.nTotalBlocks
157 self.nTotalBlocks
244 self.data_spc
158 self.data_spc
245 self.data_cspc
159 self.data_cspc
246 self.data_dc
160 self.data_dc
247
161
248 Exceptions:
162 Exceptions:
249 Si un bloque leido no es un bloque valido
163 Si un bloque leido no es un bloque valido
250 """
164 """
251 blockOk_flag = False
165
252 fpointer = self.fp.tell()
166 fpointer = self.fp.tell()
253
167
254 spc = numpy.fromfile( self.fp, self.dtype[0], self.pts2read_SelfSpectra )
168 spc = numpy.fromfile( self.fp, self.dtype[0], self.pts2read_SelfSpectra )
255 spc = spc.reshape( (self.nRdChannels, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
169 spc = spc.reshape( (self.nRdChannels, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
256
170
257 if self.processingHeaderObj.flag_cspc:
171 if self.processingHeaderObj.flag_cspc:
258 cspc = numpy.fromfile( self.fp, self.dtype, self.pts2read_CrossSpectra )
172 cspc = numpy.fromfile( self.fp, self.dtype, self.pts2read_CrossSpectra )
259 cspc = cspc.reshape( (self.nRdPairs, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
173 cspc = cspc.reshape( (self.nRdPairs, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D
260
174
261 if self.processingHeaderObj.flag_dc:
175 if self.processingHeaderObj.flag_dc:
262 dc = numpy.fromfile( self.fp, self.dtype, self.pts2read_DCchannels ) #int(self.processingHeaderObj.nHeights*self.systemHeaderObj.nChannels) )
176 dc = numpy.fromfile( self.fp, self.dtype, self.pts2read_DCchannels ) #int(self.processingHeaderObj.nHeights*self.systemHeaderObj.nChannels) )
263 dc = dc.reshape( (self.systemHeaderObj.nChannels, self.processingHeaderObj.nHeights) ) #transforma a un arreglo 2D
177 dc = dc.reshape( (self.systemHeaderObj.nChannels, self.processingHeaderObj.nHeights) ) #transforma a un arreglo 2D
264
178
265
266 if not self.processingHeaderObj.shif_fft:
179 if not self.processingHeaderObj.shif_fft:
267 #desplaza a la derecha en el eje 2 determinadas posiciones
180 #desplaza a la derecha en el eje 2 determinadas posiciones
268 shift = int(self.processingHeaderObj.profilesPerBlock/2)
181 shift = int(self.processingHeaderObj.profilesPerBlock/2)
269 spc = numpy.roll( spc, shift , axis=2 )
182 spc = numpy.roll( spc, shift , axis=2 )
270
183
271 if self.processingHeaderObj.flag_cspc:
184 if self.processingHeaderObj.flag_cspc:
272 #desplaza a la derecha en el eje 2 determinadas posiciones
185 #desplaza a la derecha en el eje 2 determinadas posiciones
273 cspc = numpy.roll( cspc, shift, axis=2 )
186 cspc = numpy.roll( cspc, shift, axis=2 )
274
187
275 #Dimensions : nChannels, nProfiles, nSamples
188 #Dimensions : nChannels, nProfiles, nSamples
276 spc = numpy.transpose( spc, (0,2,1) )
189 spc = numpy.transpose( spc, (0,2,1) )
277 self.data_spc = spc
190 self.data_spc = spc
278
191
279 if self.processingHeaderObj.flag_cspc:
192 if self.processingHeaderObj.flag_cspc:
280 cspc = numpy.transpose( cspc, (0,2,1) )
193 cspc = numpy.transpose( cspc, (0,2,1) )
281 self.data_cspc = cspc['real'] + cspc['imag']*1j
194 self.data_cspc = cspc['real'] + cspc['imag']*1j
282 else:
195 else:
283 self.data_cspc = None
196 self.data_cspc = None
284
197
285 if self.processingHeaderObj.flag_dc:
198 if self.processingHeaderObj.flag_dc:
286 self.data_dc = dc['real'] + dc['imag']*1j
199 self.data_dc = dc['real'] + dc['imag']*1j
287 else:
200 else:
288 self.data_dc = None
201 self.data_dc = None
289
202
290 self.flagIsNewFile = 0
203 self.flagIsNewFile = 0
291 self.flagIsNewBlock = 1
204 self.flagIsNewBlock = 1
292
205
293 self.nTotalBlocks += 1
206 self.nTotalBlocks += 1
294 self.nReadBlocks += 1
207 self.nReadBlocks += 1
295
208
296 return 1
209 return 1
297
210
298 def getFirstHeader(self):
211 def getFirstHeader(self):
299
212
300 self.getBasicHeader()
213 self.getBasicHeader()
301
302 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
214 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
303
304 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
215 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
305
306 # self.dataOut.ippSeconds = self.ippSeconds
307
308 # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt * self.processingHeaderObj.nIncohInt * self.processingHeaderObj.profilesPerBlock
309
310 self.dataOut.dtype = self.dtype
216 self.dataOut.dtype = self.dtype
311
312 # self.dataOut.nPairs = self.nPairs
313
314 self.dataOut.pairsList = self.rdPairList
217 self.dataOut.pairsList = self.rdPairList
315
316 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
218 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
317
318 self.dataOut.nFFTPoints = self.processingHeaderObj.profilesPerBlock
219 self.dataOut.nFFTPoints = self.processingHeaderObj.profilesPerBlock
319
320 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
220 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
321
322 self.dataOut.nIncohInt = self.processingHeaderObj.nIncohInt
221 self.dataOut.nIncohInt = self.processingHeaderObj.nIncohInt
323
324 xf = self.processingHeaderObj.firstHeight + self.processingHeaderObj.nHeights*self.processingHeaderObj.deltaHeight
222 xf = self.processingHeaderObj.firstHeight + self.processingHeaderObj.nHeights*self.processingHeaderObj.deltaHeight
325
326 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.firstHeight, xf, self.processingHeaderObj.deltaHeight)
223 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.firstHeight, xf, self.processingHeaderObj.deltaHeight)
327
328 self.dataOut.channelList = list(range(self.systemHeaderObj.nChannels))
224 self.dataOut.channelList = list(range(self.systemHeaderObj.nChannels))
329
330 self.dataOut.flagShiftFFT = True #Data is always shifted
225 self.dataOut.flagShiftFFT = True #Data is always shifted
331
332 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode #asumo q la data no esta decodificada
226 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode #asumo q la data no esta decodificada
333
334 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip #asumo q la data esta sin flip
227 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip #asumo q la data esta sin flip
335
228
336 def getData(self):
229 def getData(self):
337 """
230 """
338 First method to execute before "RUN" is called.
231 First method to execute before "RUN" is called.
339
232
340 Copia el buffer de lectura a la clase "Spectra",
233 Copia el buffer de lectura a la clase "Spectra",
341 con todos los parametros asociados a este (metadata). cuando no hay datos en el buffer de
234 con todos los parametros asociados a este (metadata). cuando no hay datos en el buffer de
342 lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock"
235 lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock"
343
236
344 Return:
237 Return:
345 0 : Si no hay mas archivos disponibles
238 0 : Si no hay mas archivos disponibles
346 1 : Si hizo una buena copia del buffer
239 1 : Si hizo una buena copia del buffer
347
240
348 Affected:
241 Affected:
349 self.dataOut
242 self.dataOut
350
351 self.flagDiscontinuousBlock
243 self.flagDiscontinuousBlock
352 self.flagIsNewBlock
244 self.flagIsNewBlock
353 """
245 """
354
246
355 if self.flagNoMoreFiles:
247 if self.flagNoMoreFiles:
356 self.dataOut.flagNoData = True
248 self.dataOut.flagNoData = True
357 return 0
249 return 0
358
250
359 self.flagDiscontinuousBlock = 0
251 self.flagDiscontinuousBlock = 0
360 self.flagIsNewBlock = 0
252 self.flagIsNewBlock = 0
361
253
362 if self.__hasNotDataInBuffer():
254 if self.__hasNotDataInBuffer():
363
255
364 if not( self.readNextBlock() ):
256 if not( self.readNextBlock() ):
365 self.dataOut.flagNoData = True
257 self.dataOut.flagNoData = True
366 return 0
258 return 0
367
259
368 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
260 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
369
261
370 if self.data_spc is None:
262 if self.data_spc is None:
371 self.dataOut.flagNoData = True
263 self.dataOut.flagNoData = True
372 return 0
264 return 0
373
265
374 self.getBasicHeader()
266 self.getBasicHeader()
375
376 self.getFirstHeader()
267 self.getFirstHeader()
377
378 self.dataOut.data_spc = self.data_spc
268 self.dataOut.data_spc = self.data_spc
379
380 self.dataOut.data_cspc = self.data_cspc
269 self.dataOut.data_cspc = self.data_cspc
381
382 self.dataOut.data_dc = self.data_dc
270 self.dataOut.data_dc = self.data_dc
383
384 self.dataOut.flagNoData = False
271 self.dataOut.flagNoData = False
385
386 self.dataOut.realtime = self.online
272 self.dataOut.realtime = self.online
387
273
388 return self.dataOut.data_spc
274 return self.dataOut.data_spc
275
276
389 @MPDecorator
277 @MPDecorator
390 class SpectraWriter(JRODataWriter, Operation):
278 class SpectraWriter(JRODataWriter, Operation):
391
279
392 """
280 """
393 Esta clase permite escribir datos de espectros a archivos procesados (.pdata). La escritura
281 Esta clase permite escribir datos de espectros a archivos procesados (.pdata). La escritura
394 de los datos siempre se realiza por bloques.
282 de los datos siempre se realiza por bloques.
395 """
283 """
396
284
397 ext = ".pdata"
398
399 optchar = "P"
400
401 shape_spc_Buffer = None
402
403 shape_cspc_Buffer = None
404
405 shape_dc_Buffer = None
406
407 data_spc = None
408
409 data_cspc = None
410
411 data_dc = None
412
413 def __init__(self):
285 def __init__(self):
414 """
286 """
415 Inicializador de la clase SpectraWriter para la escritura de datos de espectros.
287 Inicializador de la clase SpectraWriter para la escritura de datos de espectros.
416
288
417 Affected:
289 Affected:
418 self.dataOut
290 self.dataOut
419 self.basicHeaderObj
291 self.basicHeaderObj
420 self.systemHeaderObj
292 self.systemHeaderObj
421 self.radarControllerHeaderObj
293 self.radarControllerHeaderObj
422 self.processingHeaderObj
294 self.processingHeaderObj
423
295
424 Return: None
296 Return: None
425 """
297 """
426
298
427 Operation.__init__(self)
299 Operation.__init__(self)
428
300
429 self.nTotalBlocks = 0
301 self.ext = ".pdata"
430
302 self.optchar = "P"
303 self.shape_spc_Buffer = None
304 self.shape_cspc_Buffer = None
305 self.shape_dc_Buffer = None
431 self.data_spc = None
306 self.data_spc = None
432
433 self.data_cspc = None
307 self.data_cspc = None
434
435 self.data_dc = None
308 self.data_dc = None
436
437 self.fp = None
438
439 self.flagIsNewFile = 1
440
441 self.nTotalBlocks = 0
442
443 self.flagIsNewBlock = 0
444
445 self.setFile = None
309 self.setFile = None
446
447 self.dtype = None
448
449 self.path = None
450
451 self.noMoreFiles = 0
310 self.noMoreFiles = 0
452
453 self.filename = None
454
455 self.basicHeaderObj = BasicHeader(LOCALTIME)
311 self.basicHeaderObj = BasicHeader(LOCALTIME)
456
457 self.systemHeaderObj = SystemHeader()
312 self.systemHeaderObj = SystemHeader()
458
459 self.radarControllerHeaderObj = RadarControllerHeader()
313 self.radarControllerHeaderObj = RadarControllerHeader()
460
461 self.processingHeaderObj = ProcessingHeader()
314 self.processingHeaderObj = ProcessingHeader()
462
315
463
464 def hasAllDataInBuffer(self):
316 def hasAllDataInBuffer(self):
465 return 1
317 return 1
466
318
467
319
468 def setBlockDimension(self):
320 def setBlockDimension(self):
469 """
321 """
470 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
322 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
471
323
472 Affected:
324 Affected:
473 self.shape_spc_Buffer
325 self.shape_spc_Buffer
474 self.shape_cspc_Buffer
326 self.shape_cspc_Buffer
475 self.shape_dc_Buffer
327 self.shape_dc_Buffer
476
328
477 Return: None
329 Return: None
478 """
330 """
479 self.shape_spc_Buffer = (self.dataOut.nChannels,
331 self.shape_spc_Buffer = (self.dataOut.nChannels,
480 self.processingHeaderObj.nHeights,
332 self.processingHeaderObj.nHeights,
481 self.processingHeaderObj.profilesPerBlock)
333 self.processingHeaderObj.profilesPerBlock)
482
334
483 self.shape_cspc_Buffer = (self.dataOut.nPairs,
335 self.shape_cspc_Buffer = (self.dataOut.nPairs,
484 self.processingHeaderObj.nHeights,
336 self.processingHeaderObj.nHeights,
485 self.processingHeaderObj.profilesPerBlock)
337 self.processingHeaderObj.profilesPerBlock)
486
338
487 self.shape_dc_Buffer = (self.dataOut.nChannels,
339 self.shape_dc_Buffer = (self.dataOut.nChannels,
488 self.processingHeaderObj.nHeights)
340 self.processingHeaderObj.nHeights)
489
341
490
342
491 def writeBlock(self):
343 def writeBlock(self):
492 """processingHeaderObj
344 """processingHeaderObj
493 Escribe el buffer en el file designado
345 Escribe el buffer en el file designado
494
346
495 Affected:
347 Affected:
496 self.data_spc
348 self.data_spc
497 self.data_cspc
349 self.data_cspc
498 self.data_dc
350 self.data_dc
499 self.flagIsNewFile
351 self.flagIsNewFile
500 self.flagIsNewBlock
352 self.flagIsNewBlock
501 self.nTotalBlocks
353 self.nTotalBlocks
502 self.nWriteBlocks
354 self.nWriteBlocks
503
355
504 Return: None
356 Return: None
505 """
357 """
506
358
507 spc = numpy.transpose( self.data_spc, (0,2,1) )
359 spc = numpy.transpose( self.data_spc, (0,2,1) )
508 if not self.processingHeaderObj.shif_fft:
360 if not self.processingHeaderObj.shif_fft:
509 spc = numpy.roll( spc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
361 spc = numpy.roll( spc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
510 data = spc.reshape((-1))
362 data = spc.reshape((-1))
511 data = data.astype(self.dtype[0])
363 data = data.astype(self.dtype[0])
512 data.tofile(self.fp)
364 data.tofile(self.fp)
513
365
514 if self.data_cspc is not None:
366 if self.data_cspc is not None:
515
367
516 cspc = numpy.transpose( self.data_cspc, (0,2,1) )
368 cspc = numpy.transpose( self.data_cspc, (0,2,1) )
517 data = numpy.zeros( numpy.shape(cspc), self.dtype )
369 data = numpy.zeros( numpy.shape(cspc), self.dtype )
518 #print 'data.shape', self.shape_cspc_Buffer
370 #print 'data.shape', self.shape_cspc_Buffer
519 if not self.processingHeaderObj.shif_fft:
371 if not self.processingHeaderObj.shif_fft:
520 cspc = numpy.roll( cspc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
372 cspc = numpy.roll( cspc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones
521 data['real'] = cspc.real
373 data['real'] = cspc.real
522 data['imag'] = cspc.imag
374 data['imag'] = cspc.imag
523 data = data.reshape((-1))
375 data = data.reshape((-1))
524 data.tofile(self.fp)
376 data.tofile(self.fp)
525
377
526 if self.data_dc is not None:
378 if self.data_dc is not None:
527
379
528 dc = self.data_dc
380 dc = self.data_dc
529 data = numpy.zeros( numpy.shape(dc), self.dtype )
381 data = numpy.zeros( numpy.shape(dc), self.dtype )
530 data['real'] = dc.real
382 data['real'] = dc.real
531 data['imag'] = dc.imag
383 data['imag'] = dc.imag
532 data = data.reshape((-1))
384 data = data.reshape((-1))
533 data.tofile(self.fp)
385 data.tofile(self.fp)
534
386
535 # self.data_spc.fill(0)
387 # self.data_spc.fill(0)
536 #
388 #
537 # if self.data_dc is not None:
389 # if self.data_dc is not None:
538 # self.data_dc.fill(0)
390 # self.data_dc.fill(0)
539 #
391 #
540 # if self.data_cspc is not None:
392 # if self.data_cspc is not None:
541 # self.data_cspc.fill(0)
393 # self.data_cspc.fill(0)
542
394
543 self.flagIsNewFile = 0
395 self.flagIsNewFile = 0
544 self.flagIsNewBlock = 1
396 self.flagIsNewBlock = 1
545 self.nTotalBlocks += 1
397 self.nTotalBlocks += 1
546 self.nWriteBlocks += 1
398 self.nWriteBlocks += 1
547 self.blockIndex += 1
399 self.blockIndex += 1
548
400
549 # print "[Writing] Block = %d04" %self.blockIndex
401 # print "[Writing] Block = %d04" %self.blockIndex
550
402
551 def putData(self):
403 def putData(self):
552 """
404 """
553 Setea un bloque de datos y luego los escribe en un file
405 Setea un bloque de datos y luego los escribe en un file
554
406
555 Affected:
407 Affected:
556 self.data_spc
408 self.data_spc
557 self.data_cspc
409 self.data_cspc
558 self.data_dc
410 self.data_dc
559
411
560 Return:
412 Return:
561 0 : Si no hay data o no hay mas files que puedan escribirse
413 0 : Si no hay data o no hay mas files que puedan escribirse
562 1 : Si se escribio la data de un bloque en un file
414 1 : Si se escribio la data de un bloque en un file
563 """
415 """
564
416
565 if self.dataOut.flagNoData:
417 if self.dataOut.flagNoData:
566 return 0
418 return 0
567
419
568 self.flagIsNewBlock = 0
420 self.flagIsNewBlock = 0
569
421
570 if self.dataOut.flagDiscontinuousBlock:
422 if self.dataOut.flagDiscontinuousBlock:
571 self.data_spc.fill(0)
423 self.data_spc.fill(0)
572 if self.dataOut.data_cspc is not None:
424 if self.dataOut.data_cspc is not None:
573 self.data_cspc.fill(0)
425 self.data_cspc.fill(0)
574 if self.dataOut.data_dc is not None:
426 if self.dataOut.data_dc is not None:
575 self.data_dc.fill(0)
427 self.data_dc.fill(0)
576 self.setNextFile()
428 self.setNextFile()
577
429
578 if self.flagIsNewFile == 0:
430 if self.flagIsNewFile == 0:
579 self.setBasicHeader()
431 self.setBasicHeader()
580
432
581 self.data_spc = self.dataOut.data_spc.copy()
433 self.data_spc = self.dataOut.data_spc.copy()
582
434
583 if self.dataOut.data_cspc is not None:
435 if self.dataOut.data_cspc is not None:
584 self.data_cspc = self.dataOut.data_cspc.copy()
436 self.data_cspc = self.dataOut.data_cspc.copy()
585
437
586 if self.dataOut.data_dc is not None:
438 if self.dataOut.data_dc is not None:
587 self.data_dc = self.dataOut.data_dc.copy()
439 self.data_dc = self.dataOut.data_dc.copy()
588
440
589 # #self.processingHeaderObj.dataBlocksPerFile)
441 # #self.processingHeaderObj.dataBlocksPerFile)
590 if self.hasAllDataInBuffer():
442 if self.hasAllDataInBuffer():
591 # self.setFirstHeader()
443 # self.setFirstHeader()
592 self.writeNextBlock()
444 self.writeNextBlock()
593
445
594 def __getBlockSize(self):
446 def __getBlockSize(self):
595 '''
447 '''
596 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Spectra
448 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Spectra
597 '''
449 '''
598
450
599 dtype_width = self.getDtypeWidth()
451 dtype_width = self.getDtypeWidth()
600
452
601 pts2write = self.dataOut.nHeights * self.dataOut.nFFTPoints
453 pts2write = self.dataOut.nHeights * self.dataOut.nFFTPoints
602
454
603 pts2write_SelfSpectra = int(self.dataOut.nChannels * pts2write)
455 pts2write_SelfSpectra = int(self.dataOut.nChannels * pts2write)
604 blocksize = (pts2write_SelfSpectra*dtype_width)
456 blocksize = (pts2write_SelfSpectra*dtype_width)
605
457
606 if self.dataOut.data_cspc is not None:
458 if self.dataOut.data_cspc is not None:
607 pts2write_CrossSpectra = int(self.dataOut.nPairs * pts2write)
459 pts2write_CrossSpectra = int(self.dataOut.nPairs * pts2write)
608 blocksize += (pts2write_CrossSpectra*dtype_width*2)
460 blocksize += (pts2write_CrossSpectra*dtype_width*2)
609
461
610 if self.dataOut.data_dc is not None:
462 if self.dataOut.data_dc is not None:
611 pts2write_DCchannels = int(self.dataOut.nChannels * self.dataOut.nHeights)
463 pts2write_DCchannels = int(self.dataOut.nChannels * self.dataOut.nHeights)
612 blocksize += (pts2write_DCchannels*dtype_width*2)
464 blocksize += (pts2write_DCchannels*dtype_width*2)
613
465
614 # blocksize = blocksize #* datatypeValue * 2 #CORREGIR ESTO
466 # blocksize = blocksize #* datatypeValue * 2 #CORREGIR ESTO
615
467
616 return blocksize
468 return blocksize
617
469
618 def setFirstHeader(self):
470 def setFirstHeader(self):
619
471
620 """
472 """
621 Obtiene una copia del First Header
473 Obtiene una copia del First Header
622
474
623 Affected:
475 Affected:
624 self.systemHeaderObj
476 self.systemHeaderObj
625 self.radarControllerHeaderObj
477 self.radarControllerHeaderObj
626 self.dtype
478 self.dtype
627
479
628 Return:
480 Return:
629 None
481 None
630 """
482 """
631
483
632 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
484 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
633 self.systemHeaderObj.nChannels = self.dataOut.nChannels
485 self.systemHeaderObj.nChannels = self.dataOut.nChannels
634 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
486 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
635
487
636 self.processingHeaderObj.dtype = 1 # Spectra
488 self.processingHeaderObj.dtype = 1 # Spectra
637 self.processingHeaderObj.blockSize = self.__getBlockSize()
489 self.processingHeaderObj.blockSize = self.__getBlockSize()
638 self.processingHeaderObj.profilesPerBlock = self.dataOut.nFFTPoints
490 self.processingHeaderObj.profilesPerBlock = self.dataOut.nFFTPoints
639 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
491 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
640 self.processingHeaderObj.nWindows = 1 #podria ser 1 o self.dataOut.processingHeaderObj.nWindows
492 self.processingHeaderObj.nWindows = 1 #podria ser 1 o self.dataOut.processingHeaderObj.nWindows
641 self.processingHeaderObj.nCohInt = self.dataOut.nCohInt# Se requiere para determinar el valor de timeInterval
493 self.processingHeaderObj.nCohInt = self.dataOut.nCohInt# Se requiere para determinar el valor de timeInterval
642 self.processingHeaderObj.nIncohInt = self.dataOut.nIncohInt
494 self.processingHeaderObj.nIncohInt = self.dataOut.nIncohInt
643 self.processingHeaderObj.totalSpectra = self.dataOut.nPairs + self.dataOut.nChannels
495 self.processingHeaderObj.totalSpectra = self.dataOut.nPairs + self.dataOut.nChannels
644 self.processingHeaderObj.shif_fft = self.dataOut.flagShiftFFT
496 self.processingHeaderObj.shif_fft = self.dataOut.flagShiftFFT
645
497
646 if self.processingHeaderObj.totalSpectra > 0:
498 if self.processingHeaderObj.totalSpectra > 0:
647 channelList = []
499 channelList = []
648 for channel in range(self.dataOut.nChannels):
500 for channel in range(self.dataOut.nChannels):
649 channelList.append(channel)
501 channelList.append(channel)
650 channelList.append(channel)
502 channelList.append(channel)
651
503
652 pairsList = []
504 pairsList = []
653 if self.dataOut.nPairs > 0:
505 if self.dataOut.nPairs > 0:
654 for pair in self.dataOut.pairsList:
506 for pair in self.dataOut.pairsList:
655 pairsList.append(pair[0])
507 pairsList.append(pair[0])
656 pairsList.append(pair[1])
508 pairsList.append(pair[1])
657
509
658 spectraComb = channelList + pairsList
510 spectraComb = channelList + pairsList
659 spectraComb = numpy.array(spectraComb, dtype="u1")
511 spectraComb = numpy.array(spectraComb, dtype="u1")
660 self.processingHeaderObj.spectraComb = spectraComb
512 self.processingHeaderObj.spectraComb = spectraComb
661
513
662 if self.dataOut.code is not None:
514 if self.dataOut.code is not None:
663 self.processingHeaderObj.code = self.dataOut.code
515 self.processingHeaderObj.code = self.dataOut.code
664 self.processingHeaderObj.nCode = self.dataOut.nCode
516 self.processingHeaderObj.nCode = self.dataOut.nCode
665 self.processingHeaderObj.nBaud = self.dataOut.nBaud
517 self.processingHeaderObj.nBaud = self.dataOut.nBaud
666
518
667 if self.processingHeaderObj.nWindows != 0:
519 if self.processingHeaderObj.nWindows != 0:
668 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
520 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
669 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
521 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
670 self.processingHeaderObj.nHeights = self.dataOut.nHeights
522 self.processingHeaderObj.nHeights = self.dataOut.nHeights
671 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
523 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
672
524
673 self.processingHeaderObj.processFlags = self.getProcessFlags()
525 self.processingHeaderObj.processFlags = self.getProcessFlags()
674
526
675 self.setBasicHeader() No newline at end of file
527 self.setBasicHeader()
@@ -1,754 +1,680
1 '''
1 '''
2 Created on Jul 2, 2014
2 Created on Jul 2, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6
6
7 import numpy
7 import numpy
8
8
9 from .jroIO_base import LOCALTIME, JRODataReader, JRODataWriter
9 from .jroIO_base import LOCALTIME, JRODataReader, JRODataWriter
10 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
10 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
11 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
11 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
12 from schainpy.model.data.jrodata import Voltage
12 from schainpy.model.data.jrodata import Voltage
13 import zmq
13 import zmq
14 import tempfile
14 import tempfile
15 from io import StringIO
15 from io import StringIO
16 # from _sha import blocksize
16 # from _sha import blocksize
17
17
18 @MPDecorator
18 @MPDecorator
19 class VoltageReader(JRODataReader, ProcessingUnit):
19 class VoltageReader(JRODataReader, ProcessingUnit):
20 """
20 """
21 Esta clase permite leer datos de voltage desde archivos en formato rawdata (.r). La lectura
21 Esta clase permite leer datos de voltage desde archivos en formato rawdata (.r). La lectura
22 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones:
22 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones:
23 perfiles*alturas*canales) son almacenados en la variable "buffer".
23 perfiles*alturas*canales) son almacenados en la variable "buffer".
24
24
25 perfiles * alturas * canales
25 perfiles * alturas * canales
26
26
27 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
27 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
28 RadarControllerHeader y Voltage. Los tres primeros se usan para almacenar informacion de la
28 RadarControllerHeader y Voltage. Los tres primeros se usan para almacenar informacion de la
29 cabecera de datos (metadata), y el cuarto (Voltage) para obtener y almacenar un perfil de
29 cabecera de datos (metadata), y el cuarto (Voltage) para obtener y almacenar un perfil de
30 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
30 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
31
31
32 Example:
32 Example:
33
33
34 dpath = "/home/myuser/data"
34 dpath = "/home/myuser/data"
35
35
36 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
36 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
37
37
38 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
38 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
39
39
40 readerObj = VoltageReader()
40 readerObj = VoltageReader()
41
41
42 readerObj.setup(dpath, startTime, endTime)
42 readerObj.setup(dpath, startTime, endTime)
43
43
44 while(True):
44 while(True):
45
45
46 #to get one profile
46 #to get one profile
47 profile = readerObj.getData()
47 profile = readerObj.getData()
48
48
49 #print the profile
49 #print the profile
50 print profile
50 print profile
51
51
52 #If you want to see all datablock
52 #If you want to see all datablock
53 print readerObj.datablock
53 print readerObj.datablock
54
54
55 if readerObj.flagNoMoreFiles:
55 if readerObj.flagNoMoreFiles:
56 break
56 break
57
57
58 """
58 """
59
59
60 ext = ".r"
60 def __init__(self):
61
62 optchar = "D"
63 dataOut = None
64
65 def __init__(self):#, **kwargs):
66 """
61 """
67 Inicializador de la clase VoltageReader para la lectura de datos de voltage.
62 Inicializador de la clase VoltageReader para la lectura de datos de voltage.
68
63
69 Input:
64 Input:
70 dataOut : Objeto de la clase Voltage. Este objeto sera utilizado para
65 dataOut : Objeto de la clase Voltage. Este objeto sera utilizado para
71 almacenar un perfil de datos cada vez que se haga un requerimiento
66 almacenar un perfil de datos cada vez que se haga un requerimiento
72 (getData). El perfil sera obtenido a partir del buffer de datos,
67 (getData). El perfil sera obtenido a partir del buffer de datos,
73 si el buffer esta vacio se hara un nuevo proceso de lectura de un
68 si el buffer esta vacio se hara un nuevo proceso de lectura de un
74 bloque de datos.
69 bloque de datos.
75 Si este parametro no es pasado se creara uno internamente.
70 Si este parametro no es pasado se creara uno internamente.
76
71
77 Variables afectadas:
72 Variables afectadas:
78 self.dataOut
73 self.dataOut
79
74
80 Return:
75 Return:
81 None
76 None
82 """
77 """
83
78
84 ProcessingUnit.__init__(self)#, **kwargs)
79 ProcessingUnit.__init__(self)
85
86 self.isConfig = False
87
88 self.datablock = None
89
90 self.utc = 0
91
80
92 self.ext = ".r"
81 self.ext = ".r"
93
94 self.optchar = "D"
82 self.optchar = "D"
95
96 self.basicHeaderObj = BasicHeader(LOCALTIME)
83 self.basicHeaderObj = BasicHeader(LOCALTIME)
97
98 self.systemHeaderObj = SystemHeader()
84 self.systemHeaderObj = SystemHeader()
99
100 self.radarControllerHeaderObj = RadarControllerHeader()
85 self.radarControllerHeaderObj = RadarControllerHeader()
101
102 self.processingHeaderObj = ProcessingHeader()
86 self.processingHeaderObj = ProcessingHeader()
103
104 self.online = 0
105
106 self.fp = None
107
108 self.idFile = None
109
110 self.dtype = None
111
112 self.fileSizeByHeader = None
113
114 self.filenameList = []
115
116 self.filename = None
117
118 self.fileSize = None
119
120 self.firstHeaderSize = 0
121
122 self.basicHeaderSize = 24
123
124 self.pathList = []
125
126 self.filenameList = []
127
128 self.lastUTTime = 0
87 self.lastUTTime = 0
129
130 self.maxTimeStep = 30
131
132 self.flagNoMoreFiles = 0
133
134 self.set = 0
135
136 self.path = None
137
138 self.profileIndex = 2**32 - 1
88 self.profileIndex = 2**32 - 1
139
89 self.dataOut = Voltage()
140 self.delay = 3 # seconds
90 self.selBlocksize = None
141
91 self.selBlocktime = None
142 self.nTries = 3 # quantity tries
143
144 self.nFiles = 3 # number of files for searching
145
146 self.nReadBlocks = 0
147
148 self.flagIsNewFile = 1
149
150 self.__isFirstTimeOnline = 1
151
152 # self.ippSeconds = 0
153
154 self.flagDiscontinuousBlock = 0
155
156 self.flagIsNewBlock = 0
157
158 self.nTotalBlocks = 0
159
160 self.blocksize = 0
161
162 self.dataOut = self.createObjByDefault()
163
164 self.nTxs = 1
165
166 self.txIndex = 0
167
92
168 def createObjByDefault(self):
93 def createObjByDefault(self):
169
94
170 dataObj = Voltage()
95 dataObj = Voltage()
171
96
172 return dataObj
97 return dataObj
173
98
174 def __hasNotDataInBuffer(self):
99 def __hasNotDataInBuffer(self):
175
100
176 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock * self.nTxs:
101 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock * self.nTxs:
177 return 1
102 return 1
178
103
179 return 0
104 return 0
180
105
181 def getBlockDimension(self):
106 def getBlockDimension(self):
182 """
107 """
183 Obtiene la cantidad de puntos a leer por cada bloque de datos
108 Obtiene la cantidad de puntos a leer por cada bloque de datos
184
109
185 Affected:
110 Affected:
186 self.blocksize
111 self.blocksize
187
112
188 Return:
113 Return:
189 None
114 None
190 """
115 """
191 pts2read = self.processingHeaderObj.profilesPerBlock * \
116 pts2read = self.processingHeaderObj.profilesPerBlock * \
192 self.processingHeaderObj.nHeights * self.systemHeaderObj.nChannels
117 self.processingHeaderObj.nHeights * self.systemHeaderObj.nChannels
193 self.blocksize = pts2read
118 self.blocksize = pts2read
194
119
195 def readBlock(self):
120 def readBlock(self):
196 """
121 """
197 readBlock lee el bloque de datos desde la posicion actual del puntero del archivo
122 readBlock lee el bloque de datos desde la posicion actual del puntero del archivo
198 (self.fp) y actualiza todos los parametros relacionados al bloque de datos
123 (self.fp) y actualiza todos los parametros relacionados al bloque de datos
199 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
124 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
200 es seteado a 0
125 es seteado a 0
201
126
202 Inputs:
127 Inputs:
203 None
128 None
204
129
205 Return:
130 Return:
206 None
131 None
207
132
208 Affected:
133 Affected:
209 self.profileIndex
134 self.profileIndex
210 self.datablock
135 self.datablock
211 self.flagIsNewFile
136 self.flagIsNewFile
212 self.flagIsNewBlock
137 self.flagIsNewBlock
213 self.nTotalBlocks
138 self.nTotalBlocks
214
139
215 Exceptions:
140 Exceptions:
216 Si un bloque leido no es un bloque valido
141 Si un bloque leido no es un bloque valido
217 """
142 """
218
143
219 # if self.server is not None:
144 # if self.server is not None:
220 # self.zBlock = self.receiver.recv()
145 # self.zBlock = self.receiver.recv()
221 # self.zHeader = self.zBlock[:24]
146 # self.zHeader = self.zBlock[:24]
222 # self.zDataBlock = self.zBlock[24:]
147 # self.zDataBlock = self.zBlock[24:]
223 # junk = numpy.fromstring(self.zDataBlock, numpy.dtype([('real','<i4'),('imag','<i4')]))
148 # junk = numpy.fromstring(self.zDataBlock, numpy.dtype([('real','<i4'),('imag','<i4')]))
224 # self.processingHeaderObj.profilesPerBlock = 240
149 # self.processingHeaderObj.profilesPerBlock = 240
225 # self.processingHeaderObj.nHeights = 248
150 # self.processingHeaderObj.nHeights = 248
226 # self.systemHeaderObj.nChannels
151 # self.systemHeaderObj.nChannels
227 # else:
152 # else:
228 current_pointer_location = self.fp.tell()
153 current_pointer_location = self.fp.tell()
229 junk = numpy.fromfile(self.fp, self.dtype, self.blocksize)
154 junk = numpy.fromfile(self.fp, self.dtype, self.blocksize)
230
155
231 try:
156 try:
232 junk = junk.reshape((self.processingHeaderObj.profilesPerBlock,
157 junk = junk.reshape((self.processingHeaderObj.profilesPerBlock,
233 self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels))
158 self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels))
234 except:
159 except:
235 # print "The read block (%3d) has not enough data" %self.nReadBlocks
160 # print "The read block (%3d) has not enough data" %self.nReadBlocks
236
161
237 if self.waitDataBlock(pointer_location=current_pointer_location):
162 if self.waitDataBlock(pointer_location=current_pointer_location):
238 junk = numpy.fromfile(self.fp, self.dtype, self.blocksize)
163 junk = numpy.fromfile(self.fp, self.dtype, self.blocksize)
239 junk = junk.reshape((self.processingHeaderObj.profilesPerBlock,
164 junk = junk.reshape((self.processingHeaderObj.profilesPerBlock,
240 self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels))
165 self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels))
241 # return 0
166 # return 0
242
167
243 # Dimensions : nChannels, nProfiles, nSamples
168 # Dimensions : nChannels, nProfiles, nSamples
244
169
245 junk = numpy.transpose(junk, (2, 0, 1))
170 junk = numpy.transpose(junk, (2, 0, 1))
246 self.datablock = junk['real'] + junk['imag'] * 1j
171 self.datablock = junk['real'] + junk['imag'] * 1j
247
172
248 self.profileIndex = 0
173 self.profileIndex = 0
249
174
250 self.flagIsNewFile = 0
175 self.flagIsNewFile = 0
251 self.flagIsNewBlock = 1
176 self.flagIsNewBlock = 1
252
177
253 self.nTotalBlocks += 1
178 self.nTotalBlocks += 1
254 self.nReadBlocks += 1
179 self.nReadBlocks += 1
255
180
256 return 1
181 return 1
257
182
258 def getFirstHeader(self):
183 def getFirstHeader(self):
259
184
260 self.getBasicHeader()
185 self.getBasicHeader()
261
186
262 self.dataOut.processingHeaderObj = self.processingHeaderObj.copy()
187 self.dataOut.processingHeaderObj = self.processingHeaderObj.copy()
263
188
264 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
189 self.dataOut.systemHeaderObj = self.systemHeaderObj.copy()
265
190
266 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
191 self.dataOut.radarControllerHeaderObj = self.radarControllerHeaderObj.copy()
267
192
268 if self.nTxs > 1:
193 if self.nTxs > 1:
269 self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
194 self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
270 # Time interval and code are propierties of dataOut. Its value depends of radarControllerHeaderObj.
195 # Time interval and code are propierties of dataOut. Its value depends of radarControllerHeaderObj.
271
196
272 # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt
197 # self.dataOut.timeInterval = self.radarControllerHeaderObj.ippSeconds * self.processingHeaderObj.nCohInt
273 #
198 #
274 # if self.radarControllerHeaderObj.code is not None:
199 # if self.radarControllerHeaderObj.code is not None:
275 #
200 #
276 # self.dataOut.nCode = self.radarControllerHeaderObj.nCode
201 # self.dataOut.nCode = self.radarControllerHeaderObj.nCode
277 #
202 #
278 # self.dataOut.nBaud = self.radarControllerHeaderObj.nBaud
203 # self.dataOut.nBaud = self.radarControllerHeaderObj.nBaud
279 #
204 #
280 # self.dataOut.code = self.radarControllerHeaderObj.code
205 # self.dataOut.code = self.radarControllerHeaderObj.code
281
206
282 self.dataOut.dtype = self.dtype
207 self.dataOut.dtype = self.dtype
283
208
284 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
209 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock
285
210
286 self.dataOut.heightList = numpy.arange(
211 self.dataOut.heightList = numpy.arange(
287 self.processingHeaderObj.nHeights) * self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight
212 self.processingHeaderObj.nHeights) * self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight
288
213
289 self.dataOut.channelList = list(range(self.systemHeaderObj.nChannels))
214 self.dataOut.channelList = list(range(self.systemHeaderObj.nChannels))
290
215
291 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
216 self.dataOut.nCohInt = self.processingHeaderObj.nCohInt
292
217
293 # asumo q la data no esta decodificada
218 # asumo q la data no esta decodificada
294 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode
219 self.dataOut.flagDecodeData = self.processingHeaderObj.flag_decode
295
220
296 # asumo q la data no esta sin flip
221 # asumo q la data no esta sin flip
297 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip
222 self.dataOut.flagDeflipData = self.processingHeaderObj.flag_deflip
298
223
299 self.dataOut.flagShiftFFT = self.processingHeaderObj.shif_fft
224 self.dataOut.flagShiftFFT = self.processingHeaderObj.shif_fft
300
225
301 def reshapeData(self):
226 def reshapeData(self):
302
227
303 if self.nTxs < 0:
228 if self.nTxs < 0:
304 return
229 return
305
230
306 if self.nTxs == 1:
231 if self.nTxs == 1:
307 return
232 return
308
233
309 if self.nTxs < 1 and self.processingHeaderObj.profilesPerBlock % (1. / self.nTxs) != 0:
234 if self.nTxs < 1 and self.processingHeaderObj.profilesPerBlock % (1. / self.nTxs) != 0:
310 raise ValueError("1./nTxs (=%f), should be a multiple of nProfiles (=%d)" % (
235 raise ValueError("1./nTxs (=%f), should be a multiple of nProfiles (=%d)" % (
311 1. / self.nTxs, self.processingHeaderObj.profilesPerBlock))
236 1. / self.nTxs, self.processingHeaderObj.profilesPerBlock))
312
237
313 if self.nTxs > 1 and self.processingHeaderObj.nHeights % self.nTxs != 0:
238 if self.nTxs > 1 and self.processingHeaderObj.nHeights % self.nTxs != 0:
314 raise ValueError("nTxs (=%d), should be a multiple of nHeights (=%d)" % (
239 raise ValueError("nTxs (=%d), should be a multiple of nHeights (=%d)" % (
315 self.nTxs, self.processingHeaderObj.nHeights))
240 self.nTxs, self.processingHeaderObj.nHeights))
316
241
317 self.datablock = self.datablock.reshape(
242 self.datablock = self.datablock.reshape(
318 (self.systemHeaderObj.nChannels, self.processingHeaderObj.profilesPerBlock * self.nTxs, int(self.processingHeaderObj.nHeights / self.nTxs)))
243 (self.systemHeaderObj.nChannels, self.processingHeaderObj.profilesPerBlock * self.nTxs, int(self.processingHeaderObj.nHeights / self.nTxs)))
319
244
320 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock * self.nTxs
245 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock * self.nTxs
321 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.nHeights / self.nTxs) * \
246 self.dataOut.heightList = numpy.arange(self.processingHeaderObj.nHeights / self.nTxs) * \
322 self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight
247 self.processingHeaderObj.deltaHeight + self.processingHeaderObj.firstHeight
323 self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
248 self.dataOut.radarControllerHeaderObj.ippSeconds = self.radarControllerHeaderObj.ippSeconds / self.nTxs
324
249
325 return
250 return
326
251
327 def readFirstHeaderFromServer(self):
252 def readFirstHeaderFromServer(self):
328
253
329 self.getFirstHeader()
254 self.getFirstHeader()
330
255
331 self.firstHeaderSize = self.basicHeaderObj.size
256 self.firstHeaderSize = self.basicHeaderObj.size
332
257
333 datatype = int(numpy.log2((self.processingHeaderObj.processFlags &
258 datatype = int(numpy.log2((self.processingHeaderObj.processFlags &
334 PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR))
259 PROCFLAG.DATATYPE_MASK)) - numpy.log2(PROCFLAG.DATATYPE_CHAR))
335 if datatype == 0:
260 if datatype == 0:
336 datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
261 datatype_str = numpy.dtype([('real', '<i1'), ('imag', '<i1')])
337 elif datatype == 1:
262 elif datatype == 1:
338 datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
263 datatype_str = numpy.dtype([('real', '<i2'), ('imag', '<i2')])
339 elif datatype == 2:
264 elif datatype == 2:
340 datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
265 datatype_str = numpy.dtype([('real', '<i4'), ('imag', '<i4')])
341 elif datatype == 3:
266 elif datatype == 3:
342 datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
267 datatype_str = numpy.dtype([('real', '<i8'), ('imag', '<i8')])
343 elif datatype == 4:
268 elif datatype == 4:
344 datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
269 datatype_str = numpy.dtype([('real', '<f4'), ('imag', '<f4')])
345 elif datatype == 5:
270 elif datatype == 5:
346 datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
271 datatype_str = numpy.dtype([('real', '<f8'), ('imag', '<f8')])
347 else:
272 else:
348 raise ValueError('Data type was not defined')
273 raise ValueError('Data type was not defined')
349
274
350 self.dtype = datatype_str
275 self.dtype = datatype_str
351 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
276 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
352 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \
277 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + \
353 self.firstHeaderSize + self.basicHeaderSize * \
278 self.firstHeaderSize + self.basicHeaderSize * \
354 (self.processingHeaderObj.dataBlocksPerFile - 1)
279 (self.processingHeaderObj.dataBlocksPerFile - 1)
355 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
280 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
356 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
281 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
357 self.getBlockDimension()
282 self.getBlockDimension()
358
283
359 def getFromServer(self):
284 def getFromServer(self):
360 self.flagDiscontinuousBlock = 0
285 self.flagDiscontinuousBlock = 0
361 self.profileIndex = 0
286 self.profileIndex = 0
362 self.flagIsNewBlock = 1
287 self.flagIsNewBlock = 1
363 self.dataOut.flagNoData = False
288 self.dataOut.flagNoData = False
364 self.nTotalBlocks += 1
289 self.nTotalBlocks += 1
365 self.nReadBlocks += 1
290 self.nReadBlocks += 1
366 self.blockPointer = 0
291 self.blockPointer = 0
367
292
368 block = self.receiver.recv()
293 block = self.receiver.recv()
369
294
370 self.basicHeaderObj.read(block[self.blockPointer:])
295 self.basicHeaderObj.read(block[self.blockPointer:])
371 self.blockPointer += self.basicHeaderObj.length
296 self.blockPointer += self.basicHeaderObj.length
372 self.systemHeaderObj.read(block[self.blockPointer:])
297 self.systemHeaderObj.read(block[self.blockPointer:])
373 self.blockPointer += self.systemHeaderObj.length
298 self.blockPointer += self.systemHeaderObj.length
374 self.radarControllerHeaderObj.read(block[self.blockPointer:])
299 self.radarControllerHeaderObj.read(block[self.blockPointer:])
375 self.blockPointer += self.radarControllerHeaderObj.length
300 self.blockPointer += self.radarControllerHeaderObj.length
376 self.processingHeaderObj.read(block[self.blockPointer:])
301 self.processingHeaderObj.read(block[self.blockPointer:])
377 self.blockPointer += self.processingHeaderObj.length
302 self.blockPointer += self.processingHeaderObj.length
378 self.readFirstHeaderFromServer()
303 self.readFirstHeaderFromServer()
379
304
380 timestamp = self.basicHeaderObj.get_datatime()
305 timestamp = self.basicHeaderObj.get_datatime()
381 print('[Reading] - Block {} - {}'.format(self.nTotalBlocks, timestamp))
306 print('[Reading] - Block {} - {}'.format(self.nTotalBlocks, timestamp))
382 current_pointer_location = self.blockPointer
307 current_pointer_location = self.blockPointer
383 junk = numpy.fromstring(
308 junk = numpy.fromstring(
384 block[self.blockPointer:], self.dtype, self.blocksize)
309 block[self.blockPointer:], self.dtype, self.blocksize)
385
310
386 try:
311 try:
387 junk = junk.reshape((self.processingHeaderObj.profilesPerBlock,
312 junk = junk.reshape((self.processingHeaderObj.profilesPerBlock,
388 self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels))
313 self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels))
389 except:
314 except:
390 # print "The read block (%3d) has not enough data" %self.nReadBlocks
315 # print "The read block (%3d) has not enough data" %self.nReadBlocks
391 if self.waitDataBlock(pointer_location=current_pointer_location):
316 if self.waitDataBlock(pointer_location=current_pointer_location):
392 junk = numpy.fromstring(
317 junk = numpy.fromstring(
393 block[self.blockPointer:], self.dtype, self.blocksize)
318 block[self.blockPointer:], self.dtype, self.blocksize)
394 junk = junk.reshape((self.processingHeaderObj.profilesPerBlock,
319 junk = junk.reshape((self.processingHeaderObj.profilesPerBlock,
395 self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels))
320 self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels))
396 # return 0
321 # return 0
397
322
398 # Dimensions : nChannels, nProfiles, nSamples
323 # Dimensions : nChannels, nProfiles, nSamples
399
324
400 junk = numpy.transpose(junk, (2, 0, 1))
325 junk = numpy.transpose(junk, (2, 0, 1))
401 self.datablock = junk['real'] + junk['imag'] * 1j
326 self.datablock = junk['real'] + junk['imag'] * 1j
402 self.profileIndex = 0
327 self.profileIndex = 0
403 if self.selBlocksize == None:
328 if self.selBlocksize == None:
404 self.selBlocksize = self.dataOut.nProfiles
329 self.selBlocksize = self.dataOut.nProfiles
405 if self.selBlocktime != None:
330 if self.selBlocktime != None:
406 if self.dataOut.nCohInt is not None:
331 if self.dataOut.nCohInt is not None:
407 nCohInt = self.dataOut.nCohInt
332 nCohInt = self.dataOut.nCohInt
408 else:
333 else:
409 nCohInt = 1
334 nCohInt = 1
410 self.selBlocksize = int(self.dataOut.nProfiles * round(self.selBlocktime / (
335 self.selBlocksize = int(self.dataOut.nProfiles * round(self.selBlocktime / (
411 nCohInt * self.dataOut.ippSeconds * self.dataOut.nProfiles)))
336 nCohInt * self.dataOut.ippSeconds * self.dataOut.nProfiles)))
412 self.dataOut.data = self.datablock[:,
337 self.dataOut.data = self.datablock[:,
413 self.profileIndex:self.profileIndex + self.selBlocksize, :]
338 self.profileIndex:self.profileIndex + self.selBlocksize, :]
414 datasize = self.dataOut.data.shape[1]
339 datasize = self.dataOut.data.shape[1]
415 if datasize < self.selBlocksize:
340 if datasize < self.selBlocksize:
416 buffer = numpy.zeros(
341 buffer = numpy.zeros(
417 (self.dataOut.data.shape[0], self.selBlocksize, self.dataOut.data.shape[2]), dtype='complex')
342 (self.dataOut.data.shape[0], self.selBlocksize, self.dataOut.data.shape[2]), dtype='complex')
418 buffer[:, :datasize, :] = self.dataOut.data
343 buffer[:, :datasize, :] = self.dataOut.data
419 self.dataOut.data = buffer
344 self.dataOut.data = buffer
420 self.profileIndex = blockIndex
345 self.profileIndex = blockIndex
421
346
422 self.dataOut.flagDataAsBlock = True
347 self.dataOut.flagDataAsBlock = True
423 self.flagIsNewBlock = 1
348 self.flagIsNewBlock = 1
424 self.dataOut.realtime = self.online
349 self.dataOut.realtime = self.online
425
350
426 return self.dataOut.data
351 return self.dataOut.data
427
352
428 def getData(self):
353 def getData(self):
429 """
354 """
430 getData obtiene una unidad de datos del buffer de lectura, un perfil, y la copia al objeto self.dataOut
355 getData obtiene una unidad de datos del buffer de lectura, un perfil, y la copia al objeto self.dataOut
431 del tipo "Voltage" con todos los parametros asociados a este (metadata). cuando no hay datos
356 del tipo "Voltage" con todos los parametros asociados a este (metadata). cuando no hay datos
432 en el buffer de lectura es necesario hacer una nueva lectura de los bloques de datos usando
357 en el buffer de lectura es necesario hacer una nueva lectura de los bloques de datos usando
433 "readNextBlock"
358 "readNextBlock"
434
359
435 Ademas incrementa el contador del buffer "self.profileIndex" en 1.
360 Ademas incrementa el contador del buffer "self.profileIndex" en 1.
436
361
437 Return:
362 Return:
438
363
439 Si el flag self.getByBlock ha sido seteado el bloque completo es copiado a self.dataOut y el self.profileIndex
364 Si el flag self.getByBlock ha sido seteado el bloque completo es copiado a self.dataOut y el self.profileIndex
440 es igual al total de perfiles leidos desde el archivo.
365 es igual al total de perfiles leidos desde el archivo.
441
366
442 Si self.getByBlock == False:
367 Si self.getByBlock == False:
443
368
444 self.dataOut.data = buffer[:, thisProfile, :]
369 self.dataOut.data = buffer[:, thisProfile, :]
445
370
446 shape = [nChannels, nHeis]
371 shape = [nChannels, nHeis]
447
372
448 Si self.getByBlock == True:
373 Si self.getByBlock == True:
449
374
450 self.dataOut.data = buffer[:, :, :]
375 self.dataOut.data = buffer[:, :, :]
451
376
452 shape = [nChannels, nProfiles, nHeis]
377 shape = [nChannels, nProfiles, nHeis]
453
378
454 Variables afectadas:
379 Variables afectadas:
455 self.dataOut
380 self.dataOut
456 self.profileIndex
381 self.profileIndex
457
382
458 Affected:
383 Affected:
459 self.dataOut
384 self.dataOut
460 self.profileIndex
385 self.profileIndex
461 self.flagDiscontinuousBlock
386 self.flagDiscontinuousBlock
462 self.flagIsNewBlock
387 self.flagIsNewBlock
463 """
388 """
464 if self.flagNoMoreFiles:
389 if self.flagNoMoreFiles:
465 self.dataOut.flagNoData = True
390 self.dataOut.flagNoData = True
466 return 0
391 return 0
467 self.flagDiscontinuousBlock = 0
392 self.flagDiscontinuousBlock = 0
468 self.flagIsNewBlock = 0
393 self.flagIsNewBlock = 0
469 if self.__hasNotDataInBuffer():
394 if self.__hasNotDataInBuffer():
470 if not(self.readNextBlock()):
395 if not(self.readNextBlock()):
471 return 0
396 return 0
472
397
473 self.getFirstHeader()
398 self.getFirstHeader()
474
399
475 self.reshapeData()
400 self.reshapeData()
476 if self.datablock is None:
401 if self.datablock is None:
477 self.dataOut.flagNoData = True
402 self.dataOut.flagNoData = True
478 return 0
403 return 0
479
404
480 if not self.getByBlock:
405 if not self.getByBlock:
481
406
482 """
407 """
483 Return profile by profile
408 Return profile by profile
484
409
485 If nTxs > 1 then one profile is divided by nTxs and number of total
410 If nTxs > 1 then one profile is divided by nTxs and number of total
486 blocks is increased by nTxs (nProfiles *= nTxs)
411 blocks is increased by nTxs (nProfiles *= nTxs)
487 """
412 """
488 self.dataOut.flagDataAsBlock = False
413 self.dataOut.flagDataAsBlock = False
489 self.dataOut.data = self.datablock[:, self.profileIndex, :]
414 self.dataOut.data = self.datablock[:, self.profileIndex, :]
490 self.dataOut.profileIndex = self.profileIndex
415 self.dataOut.profileIndex = self.profileIndex
491
416
492 self.profileIndex += 1
417 self.profileIndex += 1
493
418
494 else:
419 else:
495 """
420 """
496 Return a block
421 Return a block
497 """
422 """
498 if self.selBlocksize == None:
423 if self.selBlocksize == None:
499 self.selBlocksize = self.dataOut.nProfiles
424 self.selBlocksize = self.dataOut.nProfiles
500 if self.selBlocktime != None:
425 if self.selBlocktime != None:
501 if self.dataOut.nCohInt is not None:
426 if self.dataOut.nCohInt is not None:
502 nCohInt = self.dataOut.nCohInt
427 nCohInt = self.dataOut.nCohInt
503 else:
428 else:
504 nCohInt = 1
429 nCohInt = 1
505 self.selBlocksize = int(self.dataOut.nProfiles * round(self.selBlocktime / (
430 self.selBlocksize = int(self.dataOut.nProfiles * round(self.selBlocktime / (
506 nCohInt * self.dataOut.ippSeconds * self.dataOut.nProfiles)))
431 nCohInt * self.dataOut.ippSeconds * self.dataOut.nProfiles)))
507
432
508 self.dataOut.data = self.datablock[:,
433 self.dataOut.data = self.datablock[:,
509 self.profileIndex:self.profileIndex + self.selBlocksize, :]
434 self.profileIndex:self.profileIndex + self.selBlocksize, :]
510 self.profileIndex += self.selBlocksize
435 self.profileIndex += self.selBlocksize
511 datasize = self.dataOut.data.shape[1]
436 datasize = self.dataOut.data.shape[1]
512
437
513 if datasize < self.selBlocksize:
438 if datasize < self.selBlocksize:
514 buffer = numpy.zeros(
439 buffer = numpy.zeros(
515 (self.dataOut.data.shape[0], self.selBlocksize, self.dataOut.data.shape[2]), dtype='complex')
440 (self.dataOut.data.shape[0], self.selBlocksize, self.dataOut.data.shape[2]), dtype='complex')
516 buffer[:, :datasize, :] = self.dataOut.data
441 buffer[:, :datasize, :] = self.dataOut.data
517
442
518 while datasize < self.selBlocksize: # Not enough profiles to fill the block
443 while datasize < self.selBlocksize: # Not enough profiles to fill the block
519 if not(self.readNextBlock()):
444 if not(self.readNextBlock()):
520 return 0
445 return 0
521 self.getFirstHeader()
446 self.getFirstHeader()
522 self.reshapeData()
447 self.reshapeData()
523 if self.datablock is None:
448 if self.datablock is None:
524 self.dataOut.flagNoData = True
449 self.dataOut.flagNoData = True
525 return 0
450 return 0
526 # stack data
451 # stack data
527 blockIndex = self.selBlocksize - datasize
452 blockIndex = self.selBlocksize - datasize
528 datablock1 = self.datablock[:, :blockIndex, :]
453 datablock1 = self.datablock[:, :blockIndex, :]
529
454
530 buffer[:, datasize:datasize +
455 buffer[:, datasize:datasize +
531 datablock1.shape[1], :] = datablock1
456 datablock1.shape[1], :] = datablock1
532 datasize += datablock1.shape[1]
457 datasize += datablock1.shape[1]
533
458
534 self.dataOut.data = buffer
459 self.dataOut.data = buffer
535 self.profileIndex = blockIndex
460 self.profileIndex = blockIndex
536
461
537 self.dataOut.flagDataAsBlock = True
462 self.dataOut.flagDataAsBlock = True
538 self.dataOut.nProfiles = self.dataOut.data.shape[1]
463 self.dataOut.nProfiles = self.dataOut.data.shape[1]
539
464
540 self.dataOut.flagNoData = False
465 self.dataOut.flagNoData = False
541
466
542 self.getBasicHeader()
467 self.getBasicHeader()
543
468
544 self.dataOut.realtime = self.online
469 self.dataOut.realtime = self.online
545
470
546 return self.dataOut.data
471 return self.dataOut.data
547
472
473
548 @MPDecorator
474 @MPDecorator
549 class VoltageWriter(JRODataWriter, Operation):
475 class VoltageWriter(JRODataWriter, Operation):
550 """
476 """
551 Esta clase permite escribir datos de voltajes a archivos procesados (.r). La escritura
477 Esta clase permite escribir datos de voltajes a archivos procesados (.r). La escritura
552 de los datos siempre se realiza por bloques.
478 de los datos siempre se realiza por bloques.
553 """
479 """
554
480
555 ext = ".r"
481 ext = ".r"
556
482
557 optchar = "D"
483 optchar = "D"
558
484
559 shapeBuffer = None
485 shapeBuffer = None
560
486
561 def __init__(self):#, **kwargs):
487 def __init__(self):#, **kwargs):
562 """
488 """
563 Inicializador de la clase VoltageWriter para la escritura de datos de espectros.
489 Inicializador de la clase VoltageWriter para la escritura de datos de espectros.
564
490
565 Affected:
491 Affected:
566 self.dataOut
492 self.dataOut
567
493
568 Return: None
494 Return: None
569 """
495 """
570 Operation.__init__(self)#, **kwargs)
496 Operation.__init__(self)#, **kwargs)
571
497
572 self.nTotalBlocks = 0
498 self.nTotalBlocks = 0
573
499
574 self.profileIndex = 0
500 self.profileIndex = 0
575
501
576 self.isConfig = False
502 self.isConfig = False
577
503
578 self.fp = None
504 self.fp = None
579
505
580 self.flagIsNewFile = 1
506 self.flagIsNewFile = 1
581
507
582 self.blockIndex = 0
508 self.blockIndex = 0
583
509
584 self.flagIsNewBlock = 0
510 self.flagIsNewBlock = 0
585
511
586 self.setFile = None
512 self.setFile = None
587
513
588 self.dtype = None
514 self.dtype = None
589
515
590 self.path = None
516 self.path = None
591
517
592 self.filename = None
518 self.filename = None
593
519
594 self.basicHeaderObj = BasicHeader(LOCALTIME)
520 self.basicHeaderObj = BasicHeader(LOCALTIME)
595
521
596 self.systemHeaderObj = SystemHeader()
522 self.systemHeaderObj = SystemHeader()
597
523
598 self.radarControllerHeaderObj = RadarControllerHeader()
524 self.radarControllerHeaderObj = RadarControllerHeader()
599
525
600 self.processingHeaderObj = ProcessingHeader()
526 self.processingHeaderObj = ProcessingHeader()
601
527
602 def hasAllDataInBuffer(self):
528 def hasAllDataInBuffer(self):
603 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock:
529 if self.profileIndex >= self.processingHeaderObj.profilesPerBlock:
604 return 1
530 return 1
605 return 0
531 return 0
606
532
607 def setBlockDimension(self):
533 def setBlockDimension(self):
608 """
534 """
609 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
535 Obtiene las formas dimensionales del los subbloques de datos que componen un bloque
610
536
611 Affected:
537 Affected:
612 self.shape_spc_Buffer
538 self.shape_spc_Buffer
613 self.shape_cspc_Buffer
539 self.shape_cspc_Buffer
614 self.shape_dc_Buffer
540 self.shape_dc_Buffer
615
541
616 Return: None
542 Return: None
617 """
543 """
618 self.shapeBuffer = (self.processingHeaderObj.profilesPerBlock,
544 self.shapeBuffer = (self.processingHeaderObj.profilesPerBlock,
619 self.processingHeaderObj.nHeights,
545 self.processingHeaderObj.nHeights,
620 self.systemHeaderObj.nChannels)
546 self.systemHeaderObj.nChannels)
621
547
622 self.datablock = numpy.zeros((self.systemHeaderObj.nChannels,
548 self.datablock = numpy.zeros((self.systemHeaderObj.nChannels,
623 self.processingHeaderObj.profilesPerBlock,
549 self.processingHeaderObj.profilesPerBlock,
624 self.processingHeaderObj.nHeights),
550 self.processingHeaderObj.nHeights),
625 dtype=numpy.dtype('complex64'))
551 dtype=numpy.dtype('complex64'))
626
552
627 def writeBlock(self):
553 def writeBlock(self):
628 """
554 """
629 Escribe el buffer en el file designado
555 Escribe el buffer en el file designado
630
556
631 Affected:
557 Affected:
632 self.profileIndex
558 self.profileIndex
633 self.flagIsNewFile
559 self.flagIsNewFile
634 self.flagIsNewBlock
560 self.flagIsNewBlock
635 self.nTotalBlocks
561 self.nTotalBlocks
636 self.blockIndex
562 self.blockIndex
637
563
638 Return: None
564 Return: None
639 """
565 """
640 data = numpy.zeros(self.shapeBuffer, self.dtype)
566 data = numpy.zeros(self.shapeBuffer, self.dtype)
641
567
642 junk = numpy.transpose(self.datablock, (1, 2, 0))
568 junk = numpy.transpose(self.datablock, (1, 2, 0))
643
569
644 data['real'] = junk.real
570 data['real'] = junk.real
645 data['imag'] = junk.imag
571 data['imag'] = junk.imag
646
572
647 data = data.reshape((-1))
573 data = data.reshape((-1))
648
574
649 data.tofile(self.fp)
575 data.tofile(self.fp)
650
576
651 self.datablock.fill(0)
577 self.datablock.fill(0)
652
578
653 self.profileIndex = 0
579 self.profileIndex = 0
654 self.flagIsNewFile = 0
580 self.flagIsNewFile = 0
655 self.flagIsNewBlock = 1
581 self.flagIsNewBlock = 1
656
582
657 self.blockIndex += 1
583 self.blockIndex += 1
658 self.nTotalBlocks += 1
584 self.nTotalBlocks += 1
659
585
660 # print "[Writing] Block = %04d" %self.blockIndex
586 # print "[Writing] Block = %04d" %self.blockIndex
661
587
662 def putData(self):
588 def putData(self):
663 """
589 """
664 Setea un bloque de datos y luego los escribe en un file
590 Setea un bloque de datos y luego los escribe en un file
665
591
666 Affected:
592 Affected:
667 self.flagIsNewBlock
593 self.flagIsNewBlock
668 self.profileIndex
594 self.profileIndex
669
595
670 Return:
596 Return:
671 0 : Si no hay data o no hay mas files que puedan escribirse
597 0 : Si no hay data o no hay mas files que puedan escribirse
672 1 : Si se escribio la data de un bloque en un file
598 1 : Si se escribio la data de un bloque en un file
673 """
599 """
674 if self.dataOut.flagNoData:
600 if self.dataOut.flagNoData:
675 return 0
601 return 0
676
602
677 self.flagIsNewBlock = 0
603 self.flagIsNewBlock = 0
678
604
679 if self.dataOut.flagDiscontinuousBlock:
605 if self.dataOut.flagDiscontinuousBlock:
680 self.datablock.fill(0)
606 self.datablock.fill(0)
681 self.profileIndex = 0
607 self.profileIndex = 0
682 self.setNextFile()
608 self.setNextFile()
683
609
684 if self.profileIndex == 0:
610 if self.profileIndex == 0:
685 self.setBasicHeader()
611 self.setBasicHeader()
686
612
687 self.datablock[:, self.profileIndex, :] = self.dataOut.data
613 self.datablock[:, self.profileIndex, :] = self.dataOut.data
688
614
689 self.profileIndex += 1
615 self.profileIndex += 1
690
616
691 if self.hasAllDataInBuffer():
617 if self.hasAllDataInBuffer():
692 # if self.flagIsNewFile:
618 # if self.flagIsNewFile:
693 self.writeNextBlock()
619 self.writeNextBlock()
694 # self.setFirstHeader()
620 # self.setFirstHeader()
695
621
696 return 1
622 return 1
697
623
698 def __getBlockSize(self):
624 def __getBlockSize(self):
699 '''
625 '''
700 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Voltage
626 Este metodos determina el cantidad de bytes para un bloque de datos de tipo Voltage
701 '''
627 '''
702
628
703 dtype_width = self.getDtypeWidth()
629 dtype_width = self.getDtypeWidth()
704
630
705 blocksize = int(self.dataOut.nHeights * self.dataOut.nChannels *
631 blocksize = int(self.dataOut.nHeights * self.dataOut.nChannels *
706 self.profilesPerBlock * dtype_width * 2)
632 self.profilesPerBlock * dtype_width * 2)
707
633
708 return blocksize
634 return blocksize
709
635
710 def setFirstHeader(self):
636 def setFirstHeader(self):
711 """
637 """
712 Obtiene una copia del First Header
638 Obtiene una copia del First Header
713
639
714 Affected:
640 Affected:
715 self.systemHeaderObj
641 self.systemHeaderObj
716 self.radarControllerHeaderObj
642 self.radarControllerHeaderObj
717 self.dtype
643 self.dtype
718
644
719 Return:
645 Return:
720 None
646 None
721 """
647 """
722
648
723 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
649 self.systemHeaderObj = self.dataOut.systemHeaderObj.copy()
724 self.systemHeaderObj.nChannels = self.dataOut.nChannels
650 self.systemHeaderObj.nChannels = self.dataOut.nChannels
725 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
651 self.radarControllerHeaderObj = self.dataOut.radarControllerHeaderObj.copy()
726
652
727 self.processingHeaderObj.dtype = 0 # Voltage
653 self.processingHeaderObj.dtype = 0 # Voltage
728 self.processingHeaderObj.blockSize = self.__getBlockSize()
654 self.processingHeaderObj.blockSize = self.__getBlockSize()
729 self.processingHeaderObj.profilesPerBlock = self.profilesPerBlock
655 self.processingHeaderObj.profilesPerBlock = self.profilesPerBlock
730 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
656 self.processingHeaderObj.dataBlocksPerFile = self.blocksPerFile
731 # podria ser 1 o self.dataOut.processingHeaderObj.nWindows
657 # podria ser 1 o self.dataOut.processingHeaderObj.nWindows
732 self.processingHeaderObj.nWindows = 1
658 self.processingHeaderObj.nWindows = 1
733 self.processingHeaderObj.nCohInt = self.dataOut.nCohInt
659 self.processingHeaderObj.nCohInt = self.dataOut.nCohInt
734 # Cuando la data de origen es de tipo Voltage
660 # Cuando la data de origen es de tipo Voltage
735 self.processingHeaderObj.nIncohInt = 1
661 self.processingHeaderObj.nIncohInt = 1
736 # Cuando la data de origen es de tipo Voltage
662 # Cuando la data de origen es de tipo Voltage
737 self.processingHeaderObj.totalSpectra = 0
663 self.processingHeaderObj.totalSpectra = 0
738
664
739 if self.dataOut.code is not None:
665 if self.dataOut.code is not None:
740 self.processingHeaderObj.code = self.dataOut.code
666 self.processingHeaderObj.code = self.dataOut.code
741 self.processingHeaderObj.nCode = self.dataOut.nCode
667 self.processingHeaderObj.nCode = self.dataOut.nCode
742 self.processingHeaderObj.nBaud = self.dataOut.nBaud
668 self.processingHeaderObj.nBaud = self.dataOut.nBaud
743
669
744 if self.processingHeaderObj.nWindows != 0:
670 if self.processingHeaderObj.nWindows != 0:
745 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
671 self.processingHeaderObj.firstHeight = self.dataOut.heightList[0]
746 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - \
672 self.processingHeaderObj.deltaHeight = self.dataOut.heightList[1] - \
747 self.dataOut.heightList[0]
673 self.dataOut.heightList[0]
748 self.processingHeaderObj.nHeights = self.dataOut.nHeights
674 self.processingHeaderObj.nHeights = self.dataOut.nHeights
749 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
675 self.processingHeaderObj.samplesWin = self.dataOut.nHeights
750
676
751 self.processingHeaderObj.processFlags = self.getProcessFlags()
677 self.processingHeaderObj.processFlags = self.getProcessFlags()
752
678
753 self.setBasicHeader()
679 self.setBasicHeader()
754 No newline at end of file
680
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now