##// END OF EJS Templates
decimation a 300
José Chávez -
r1093:6f37ceb2e70a
parent child
Show More
@@ -1,939 +1,951
1
1
2 import os
2 import os
3 import time
3 import time
4 import glob
4 import glob
5 import datetime
5 import datetime
6 from multiprocessing import Process
6 from multiprocessing import Process
7
7
8 import zmq
8 import zmq
9 import numpy
9 import numpy
10 import matplotlib
10 import matplotlib
11 import matplotlib.pyplot as plt
11 import matplotlib.pyplot as plt
12 from mpl_toolkits.axes_grid1 import make_axes_locatable
12 from mpl_toolkits.axes_grid1 import make_axes_locatable
13 from matplotlib.ticker import FuncFormatter, LinearLocator, MultipleLocator
13 from matplotlib.ticker import FuncFormatter, LinearLocator, MultipleLocator
14
14
15 from schainpy.model.proc.jroproc_base import Operation
15 from schainpy.model.proc.jroproc_base import Operation
16 from schainpy.utils import log
16 from schainpy.utils import log
17
17
18 jet_values = matplotlib.pyplot.get_cmap("jet", 100)(numpy.arange(100))[10:90]
18 jet_values = matplotlib.pyplot.get_cmap("jet", 100)(numpy.arange(100))[10:90]
19 blu_values = matplotlib.pyplot.get_cmap(
19 blu_values = matplotlib.pyplot.get_cmap(
20 "seismic_r", 20)(numpy.arange(20))[10:15]
20 "seismic_r", 20)(numpy.arange(20))[10:15]
21 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list(
21 ncmap = matplotlib.colors.LinearSegmentedColormap.from_list(
22 "jro", numpy.vstack((blu_values, jet_values)))
22 "jro", numpy.vstack((blu_values, jet_values)))
23 matplotlib.pyplot.register_cmap(cmap=ncmap)
23 matplotlib.pyplot.register_cmap(cmap=ncmap)
24
24
25 CMAPS = [plt.get_cmap(s) for s in ('jro', 'jet', 'RdBu_r', 'seismic')]
25 CMAPS = [plt.get_cmap(s) for s in ('jro', 'jet', 'RdBu_r', 'seismic')]
26
26
27
27 def figpause(interval):
28 def figpause(interval):
28 backend = plt.rcParams['backend']
29 backend = plt.rcParams['backend']
29 if backend in matplotlib.rcsetup.interactive_bk:
30 if backend in matplotlib.rcsetup.interactive_bk:
30 figManager = matplotlib._pylab_helpers.Gcf.get_active()
31 figManager = matplotlib._pylab_helpers.Gcf.get_active()
31 if figManager is not None:
32 if figManager is not None:
32 canvas = figManager.canvas
33 canvas = figManager.canvas
33 if canvas.figure.stale:
34 if canvas.figure.stale:
34 canvas.draw()
35 canvas.draw()
35 canvas.start_event_loop(interval)
36 canvas.start_event_loop(interval)
36 return
37 return
37
38
39
38 class PlotData(Operation, Process):
40 class PlotData(Operation, Process):
39 '''
41 '''
40 Base class for Schain plotting operations
42 Base class for Schain plotting operations
41 '''
43 '''
42
44
43 CODE = 'Figure'
45 CODE = 'Figure'
44 colormap = 'jro'
46 colormap = 'jro'
45 bgcolor = 'white'
47 bgcolor = 'white'
46 CONFLATE = False
48 CONFLATE = False
47 __MAXNUMX = 80
49 __MAXNUMX = 80
48 __missing = 1E30
50 __missing = 1E30
49
51
50 def __init__(self, **kwargs):
52 def __init__(self, **kwargs):
51
53
52 Operation.__init__(self, plot=True, **kwargs)
54 Operation.__init__(self, plot=True, **kwargs)
53 Process.__init__(self)
55 Process.__init__(self)
56 self.contador = 0
54 self.kwargs['code'] = self.CODE
57 self.kwargs['code'] = self.CODE
55 self.mp = False
58 self.mp = False
56 self.data = None
59 self.data = None
57 self.isConfig = False
60 self.isConfig = False
58 self.figures = []
61 self.figures = []
59 self.axes = []
62 self.axes = []
60 self.cb_axes = []
63 self.cb_axes = []
61 self.localtime = kwargs.pop('localtime', True)
64 self.localtime = kwargs.pop('localtime', True)
62 self.show = kwargs.get('show', True)
65 self.show = kwargs.get('show', True)
63 self.save = kwargs.get('save', False)
66 self.save = kwargs.get('save', False)
64 self.colormap = kwargs.get('colormap', self.colormap)
67 self.colormap = kwargs.get('colormap', self.colormap)
65 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
68 self.colormap_coh = kwargs.get('colormap_coh', 'jet')
66 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
69 self.colormap_phase = kwargs.get('colormap_phase', 'RdBu_r')
67 self.colormaps = kwargs.get('colormaps', None)
70 self.colormaps = kwargs.get('colormaps', None)
68 self.bgcolor = kwargs.get('bgcolor', self.bgcolor)
71 self.bgcolor = kwargs.get('bgcolor', self.bgcolor)
69 self.showprofile = kwargs.get('showprofile', False)
72 self.showprofile = kwargs.get('showprofile', False)
70 self.title = kwargs.get('wintitle', self.CODE.upper())
73 self.title = kwargs.get('wintitle', self.CODE.upper())
71 self.cb_label = kwargs.get('cb_label', None)
74 self.cb_label = kwargs.get('cb_label', None)
72 self.cb_labels = kwargs.get('cb_labels', None)
75 self.cb_labels = kwargs.get('cb_labels', None)
73 self.xaxis = kwargs.get('xaxis', 'frequency')
76 self.xaxis = kwargs.get('xaxis', 'frequency')
74 self.zmin = kwargs.get('zmin', None)
77 self.zmin = kwargs.get('zmin', None)
75 self.zmax = kwargs.get('zmax', None)
78 self.zmax = kwargs.get('zmax', None)
76 self.zlimits = kwargs.get('zlimits', None)
79 self.zlimits = kwargs.get('zlimits', None)
77 self.xmin = kwargs.get('xmin', None)
80 self.xmin = kwargs.get('xmin', None)
78 self.xmax = kwargs.get('xmax', None)
81 self.xmax = kwargs.get('xmax', None)
79 self.xrange = kwargs.get('xrange', 24)
82 self.xrange = kwargs.get('xrange', 24)
80 self.ymin = kwargs.get('ymin', None)
83 self.ymin = kwargs.get('ymin', None)
81 self.ymax = kwargs.get('ymax', None)
84 self.ymax = kwargs.get('ymax', None)
82 self.xlabel = kwargs.get('xlabel', None)
85 self.xlabel = kwargs.get('xlabel', None)
83 self.__MAXNUMY = kwargs.get('decimation', 100)
86 self.__MAXNUMY = kwargs.get('decimation', 300)
84 self.showSNR = kwargs.get('showSNR', False)
87 self.showSNR = kwargs.get('showSNR', False)
85 self.oneFigure = kwargs.get('oneFigure', True)
88 self.oneFigure = kwargs.get('oneFigure', True)
86 self.width = kwargs.get('width', None)
89 self.width = kwargs.get('width', None)
87 self.height = kwargs.get('height', None)
90 self.height = kwargs.get('height', None)
88 self.colorbar = kwargs.get('colorbar', True)
91 self.colorbar = kwargs.get('colorbar', True)
89 self.factors = kwargs.get('factors', [1, 1, 1, 1, 1, 1, 1, 1])
92 self.factors = kwargs.get('factors', [1, 1, 1, 1, 1, 1, 1, 1])
90 self.titles = ['' for __ in range(16)]
93 self.titles = ['' for __ in range(16)]
91
94
92 def __fmtTime(self, x, pos):
95 def __fmtTime(self, x, pos):
93 '''
96 '''
94 '''
97 '''
95
98
96 return '{}'.format(self.getDateTime(x).strftime('%H:%M'))
99 return '{}'.format(self.getDateTime(x).strftime('%H:%M'))
97
100
98 def __setup(self):
101 def __setup(self):
99 '''
102 '''
100 Common setup for all figures, here figures and axes are created
103 Common setup for all figures, here figures and axes are created
101 '''
104 '''
102
105
103 self.setup()
106 self.setup()
104
107
105 self.time_label = 'LT' if self.localtime else 'UTC'
108 self.time_label = 'LT' if self.localtime else 'UTC'
106 if self.data.localtime:
109 if self.data.localtime:
107 self.getDateTime = datetime.datetime.fromtimestamp
110 self.getDateTime = datetime.datetime.fromtimestamp
108 else:
111 else:
109 self.getDateTime = datetime.datetime.utcfromtimestamp
112 self.getDateTime = datetime.datetime.utcfromtimestamp
110
113
111 if self.width is None:
114 if self.width is None:
112 self.width = 8
115 self.width = 8
113
116
114 self.figures = []
117 self.figures = []
115 self.axes = []
118 self.axes = []
116 self.cb_axes = []
119 self.cb_axes = []
117 self.pf_axes = []
120 self.pf_axes = []
118 self.cmaps = []
121 self.cmaps = []
119
122
120 size = '15%' if self.ncols == 1 else '30%'
123 size = '15%' if self.ncols == 1 else '30%'
121 pad = '4%' if self.ncols == 1 else '8%'
124 pad = '4%' if self.ncols == 1 else '8%'
122
125
123 if self.oneFigure:
126 if self.oneFigure:
124 if self.height is None:
127 if self.height is None:
125 self.height = 1.4 * self.nrows + 1
128 self.height = 1.4 * self.nrows + 1
126 fig = plt.figure(figsize=(self.width, self.height),
129 fig = plt.figure(figsize=(self.width, self.height),
127 edgecolor='k',
130 edgecolor='k',
128 facecolor='w')
131 facecolor='w')
129 self.figures.append(fig)
132 self.figures.append(fig)
130 for n in range(self.nplots):
133 for n in range(self.nplots):
131 ax = fig.add_subplot(self.nrows, self.ncols, n + 1)
134 ax = fig.add_subplot(self.nrows, self.ncols, n + 1)
132 ax.tick_params(labelsize=8)
135 ax.tick_params(labelsize=8)
133 ax.firsttime = True
136 ax.firsttime = True
134 ax.index = 0
137 ax.index = 0
135 ax.press = None
138 ax.press = None
136 self.axes.append(ax)
139 self.axes.append(ax)
137 if self.showprofile:
140 if self.showprofile:
138 cax = self.__add_axes(ax, size=size, pad=pad)
141 cax = self.__add_axes(ax, size=size, pad=pad)
139 cax.tick_params(labelsize=8)
142 cax.tick_params(labelsize=8)
140 self.pf_axes.append(cax)
143 self.pf_axes.append(cax)
141 else:
144 else:
142 if self.height is None:
145 if self.height is None:
143 self.height = 3
146 self.height = 3
144 for n in range(self.nplots):
147 for n in range(self.nplots):
145 fig = plt.figure(figsize=(self.width, self.height),
148 fig = plt.figure(figsize=(self.width, self.height),
146 edgecolor='k',
149 edgecolor='k',
147 facecolor='w')
150 facecolor='w')
148 ax = fig.add_subplot(1, 1, 1)
151 ax = fig.add_subplot(1, 1, 1)
149 ax.tick_params(labelsize=8)
152 ax.tick_params(labelsize=8)
150 ax.firsttime = True
153 ax.firsttime = True
151 ax.index = 0
154 ax.index = 0
152 ax.press = None
155 ax.press = None
153 self.figures.append(fig)
156 self.figures.append(fig)
154 self.axes.append(ax)
157 self.axes.append(ax)
155 if self.showprofile:
158 if self.showprofile:
156 cax = self.__add_axes(ax, size=size, pad=pad)
159 cax = self.__add_axes(ax, size=size, pad=pad)
157 cax.tick_params(labelsize=8)
160 cax.tick_params(labelsize=8)
158 self.pf_axes.append(cax)
161 self.pf_axes.append(cax)
159
162
160 for n in range(self.nrows):
163 for n in range(self.nrows):
161 if self.colormaps is not None:
164 if self.colormaps is not None:
162 cmap = plt.get_cmap(self.colormaps[n])
165 cmap = plt.get_cmap(self.colormaps[n])
163 else:
166 else:
164 cmap = plt.get_cmap(self.colormap)
167 cmap = plt.get_cmap(self.colormap)
165 cmap.set_bad(self.bgcolor, 1.)
168 cmap.set_bad(self.bgcolor, 1.)
166 self.cmaps.append(cmap)
169 self.cmaps.append(cmap)
167
170
168 for fig in self.figures:
171 for fig in self.figures:
169 fig.canvas.mpl_connect('key_press_event', self.OnKeyPress)
172 fig.canvas.mpl_connect('key_press_event', self.OnKeyPress)
170 fig.canvas.mpl_connect('scroll_event', self.OnBtnScroll)
173 fig.canvas.mpl_connect('scroll_event', self.OnBtnScroll)
171 fig.canvas.mpl_connect('button_press_event', self.onBtnPress)
174 fig.canvas.mpl_connect('button_press_event', self.onBtnPress)
172 fig.canvas.mpl_connect('motion_notify_event', self.onMotion)
175 fig.canvas.mpl_connect('motion_notify_event', self.onMotion)
173 fig.canvas.mpl_connect('button_release_event', self.onBtnRelease)
176 fig.canvas.mpl_connect('button_release_event', self.onBtnRelease)
174 if self.show:
177 if self.show:
175 fig.show()
178 fig.show()
176
179
177 def OnKeyPress(self, event):
180 def OnKeyPress(self, event):
178 '''
181 '''
179 Event for pressing keys (up, down) change colormap
182 Event for pressing keys (up, down) change colormap
180 '''
183 '''
181 ax = event.inaxes
184 ax = event.inaxes
182 if ax in self.axes:
185 if ax in self.axes:
183 if event.key == 'down':
186 if event.key == 'down':
184 ax.index += 1
187 ax.index += 1
185 elif event.key == 'up':
188 elif event.key == 'up':
186 ax.index -= 1
189 ax.index -= 1
187 if ax.index < 0:
190 if ax.index < 0:
188 ax.index = len(CMAPS) - 1
191 ax.index = len(CMAPS) - 1
189 elif ax.index == len(CMAPS):
192 elif ax.index == len(CMAPS):
190 ax.index = 0
193 ax.index = 0
191 cmap = CMAPS[ax.index]
194 cmap = CMAPS[ax.index]
192 ax.cbar.set_cmap(cmap)
195 ax.cbar.set_cmap(cmap)
193 ax.cbar.draw_all()
196 ax.cbar.draw_all()
194 ax.plt.set_cmap(cmap)
197 ax.plt.set_cmap(cmap)
195 ax.cbar.patch.figure.canvas.draw()
198 ax.cbar.patch.figure.canvas.draw()
196 self.colormap = cmap.name
199 self.colormap = cmap.name
197
200
198 def OnBtnScroll(self, event):
201 def OnBtnScroll(self, event):
199 '''
202 '''
200 Event for scrolling, scale figure
203 Event for scrolling, scale figure
201 '''
204 '''
202 cb_ax = event.inaxes
205 cb_ax = event.inaxes
203 if cb_ax in [ax.cbar.ax for ax in self.axes if ax.cbar]:
206 if cb_ax in [ax.cbar.ax for ax in self.axes if ax.cbar]:
204 ax = [ax for ax in self.axes if cb_ax == ax.cbar.ax][0]
207 ax = [ax for ax in self.axes if cb_ax == ax.cbar.ax][0]
205 pt = ax.cbar.ax.bbox.get_points()[:,1]
208 pt = ax.cbar.ax.bbox.get_points()[:, 1]
206 nrm = ax.cbar.norm
209 nrm = ax.cbar.norm
207 vmin, vmax, p0, p1, pS = (nrm.vmin, nrm.vmax, pt[0], pt[1], event.y)
210 vmin, vmax, p0, p1, pS = (
211 nrm.vmin, nrm.vmax, pt[0], pt[1], event.y)
208 scale = 2 if event.step == 1 else 0.5
212 scale = 2 if event.step == 1 else 0.5
209 point = vmin + (vmax - vmin) / (p1 - p0)*(pS - p0)
213 point = vmin + (vmax - vmin) / (p1 - p0) * (pS - p0)
210 ax.cbar.norm.vmin = point - scale*(point - vmin)
214 ax.cbar.norm.vmin = point - scale * (point - vmin)
211 ax.cbar.norm.vmax = point - scale*(point - vmax)
215 ax.cbar.norm.vmax = point - scale * (point - vmax)
212 ax.plt.set_norm(ax.cbar.norm)
216 ax.plt.set_norm(ax.cbar.norm)
213 ax.cbar.draw_all()
217 ax.cbar.draw_all()
214 ax.cbar.patch.figure.canvas.draw()
218 ax.cbar.patch.figure.canvas.draw()
215
219
216 def onBtnPress(self, event):
220 def onBtnPress(self, event):
217 '''
221 '''
218 Event for mouse button press
222 Event for mouse button press
219 '''
223 '''
220 cb_ax = event.inaxes
224 cb_ax = event.inaxes
221 if cb_ax is None:
225 if cb_ax is None:
222 return
226 return
223
227
224 if cb_ax in [ax.cbar.ax for ax in self.axes if ax.cbar]:
228 if cb_ax in [ax.cbar.ax for ax in self.axes if ax.cbar]:
225 cb_ax.press = event.x, event.y
229 cb_ax.press = event.x, event.y
226 else:
230 else:
227 cb_ax.press = None
231 cb_ax.press = None
228
232
229 def onMotion(self, event):
233 def onMotion(self, event):
230 '''
234 '''
231 Event for move inside colorbar
235 Event for move inside colorbar
232 '''
236 '''
233 cb_ax = event.inaxes
237 cb_ax = event.inaxes
234 if cb_ax is None:
238 if cb_ax is None:
235 return
239 return
236 if cb_ax not in [ax.cbar.ax for ax in self.axes if ax.cbar]:
240 if cb_ax not in [ax.cbar.ax for ax in self.axes if ax.cbar]:
237 return
241 return
238 if cb_ax.press is None:
242 if cb_ax.press is None:
239 return
243 return
240
244
241 ax = [ax for ax in self.axes if cb_ax == ax.cbar.ax][0]
245 ax = [ax for ax in self.axes if cb_ax == ax.cbar.ax][0]
242 xprev, yprev = cb_ax.press
246 xprev, yprev = cb_ax.press
243 dx = event.x - xprev
247 dx = event.x - xprev
244 dy = event.y - yprev
248 dy = event.y - yprev
245 cb_ax.press = event.x, event.y
249 cb_ax.press = event.x, event.y
246 scale = ax.cbar.norm.vmax - ax.cbar.norm.vmin
250 scale = ax.cbar.norm.vmax - ax.cbar.norm.vmin
247 perc = 0.03
251 perc = 0.03
248
252
249 if event.button == 1:
253 if event.button == 1:
250 ax.cbar.norm.vmin -= (perc*scale)*numpy.sign(dy)
254 ax.cbar.norm.vmin -= (perc * scale) * numpy.sign(dy)
251 ax.cbar.norm.vmax -= (perc*scale)*numpy.sign(dy)
255 ax.cbar.norm.vmax -= (perc * scale) * numpy.sign(dy)
252 elif event.button == 3:
256 elif event.button == 3:
253 ax.cbar.norm.vmin -= (perc*scale)*numpy.sign(dy)
257 ax.cbar.norm.vmin -= (perc * scale) * numpy.sign(dy)
254 ax.cbar.norm.vmax += (perc*scale)*numpy.sign(dy)
258 ax.cbar.norm.vmax += (perc * scale) * numpy.sign(dy)
255
259
256 ax.cbar.draw_all()
260 ax.cbar.draw_all()
257 ax.plt.set_norm(ax.cbar.norm)
261 ax.plt.set_norm(ax.cbar.norm)
258 ax.cbar.patch.figure.canvas.draw()
262 ax.cbar.patch.figure.canvas.draw()
259
263
260 def onBtnRelease(self, event):
264 def onBtnRelease(self, event):
261 '''
265 '''
262 Event for mouse button release
266 Event for mouse button release
263 '''
267 '''
264 cb_ax = event.inaxes
268 cb_ax = event.inaxes
265 if cb_ax is not None:
269 if cb_ax is not None:
266 cb_ax.press = None
270 cb_ax.press = None
267
271
268 def __add_axes(self, ax, size='30%', pad='8%'):
272 def __add_axes(self, ax, size='30%', pad='8%'):
269 '''
273 '''
270 Add new axes to the given figure
274 Add new axes to the given figure
271 '''
275 '''
272 divider = make_axes_locatable(ax)
276 divider = make_axes_locatable(ax)
273 nax = divider.new_horizontal(size=size, pad=pad)
277 nax = divider.new_horizontal(size=size, pad=pad)
274 ax.figure.add_axes(nax)
278 ax.figure.add_axes(nax)
275 return nax
279 return nax
276
280
277 self.setup()
281 self.setup()
278
282
279 def setup(self):
283 def setup(self):
280 '''
284 '''
281 This method should be implemented in the child class, the following
285 This method should be implemented in the child class, the following
282 attributes should be set:
286 attributes should be set:
283
287
284 self.nrows: number of rows
288 self.nrows: number of rows
285 self.ncols: number of cols
289 self.ncols: number of cols
286 self.nplots: number of plots (channels or pairs)
290 self.nplots: number of plots (channels or pairs)
287 self.ylabel: label for Y axes
291 self.ylabel: label for Y axes
288 self.titles: list of axes title
292 self.titles: list of axes title
289
293
290 '''
294 '''
291 raise(NotImplementedError, 'Implement this method in child class')
295 raise(NotImplementedError, 'Implement this method in child class')
292
296
293 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
297 def fill_gaps(self, x_buffer, y_buffer, z_buffer):
294 '''
298 '''
295 Create a masked array for missing data
299 Create a masked array for missing data
296 '''
300 '''
297 if x_buffer.shape[0] < 2:
301 if x_buffer.shape[0] < 2:
298 return x_buffer, y_buffer, z_buffer
302 return x_buffer, y_buffer, z_buffer
299
303
300 deltas = x_buffer[1:] - x_buffer[0:-1]
304 deltas = x_buffer[1:] - x_buffer[0:-1]
301 x_median = numpy.median(deltas)
305 x_median = numpy.median(deltas)
302
306
303 index = numpy.where(deltas > 5 * x_median)
307 index = numpy.where(deltas > 5 * x_median)
304
308
305 if len(index[0]) != 0:
309 if len(index[0]) != 0:
306 z_buffer[::, index[0], ::] = self.__missing
310 z_buffer[::, index[0], ::] = self.__missing
307 z_buffer = numpy.ma.masked_inside(z_buffer,
311 z_buffer = numpy.ma.masked_inside(z_buffer,
308 0.99 * self.__missing,
312 0.99 * self.__missing,
309 1.01 * self.__missing)
313 1.01 * self.__missing)
310
314
311 return x_buffer, y_buffer, z_buffer
315 return x_buffer, y_buffer, z_buffer
312
316
313 def decimate(self):
317 def decimate(self):
314
318
315 # dx = int(len(self.x)/self.__MAXNUMX) + 1
319 # dx = int(len(self.x)/self.__MAXNUMX) + 1
316 dy = int(len(self.y) / self.__MAXNUMY) + 1
320 dy = int(len(self.y) / self.__MAXNUMY) + 1
317
321
318 # x = self.x[::dx]
322 # x = self.x[::dx]
319 x = self.x
323 x = self.x
320 y = self.y[::dy]
324 y = self.y[::dy]
321 z = self.z[::, ::, ::dy]
325 z = self.z[::, ::, ::dy]
322
326
323 return x, y, z
327 return x, y, z
324
328
325 def format(self):
329 def format(self):
326 '''
330 '''
327 Set min and max values, labels, ticks and titles
331 Set min and max values, labels, ticks and titles
328 '''
332 '''
329
333
330 if self.xmin is None:
334 if self.xmin is None:
331 xmin = self.min_time
335 xmin = self.min_time
332 else:
336 else:
333 if self.xaxis is 'time':
337 if self.xaxis is 'time':
334 dt = self.getDateTime(self.min_time)
338 dt = self.getDateTime(self.min_time)
335 xmin = (dt.replace(hour=int(self.xmin), minute=0, second=0) - datetime.datetime(1970, 1, 1)).total_seconds()
339 xmin = (dt.replace(hour=int(self.xmin), minute=0, second=0) -
340 datetime.datetime(1970, 1, 1)).total_seconds()
336 if self.data.localtime:
341 if self.data.localtime:
337 xmin += time.timezone
342 xmin += time.timezone
338 else:
343 else:
339 xmin = self.xmin
344 xmin = self.xmin
340
345
341 if self.xmax is None:
346 if self.xmax is None:
342 xmax = xmin + self.xrange * 60 * 60
347 xmax = xmin + self.xrange * 60 * 60
343 else:
348 else:
344 if self.xaxis is 'time':
349 if self.xaxis is 'time':
345 dt = self.getDateTime(self.max_time)
350 dt = self.getDateTime(self.max_time)
346 xmax = (dt.replace(hour=int(self.xmax), minute=0, second=0) - datetime.datetime(1970, 1, 1)).total_seconds()
351 xmax = (dt.replace(hour=int(self.xmax), minute=0, second=0) -
352 datetime.datetime(1970, 1, 1)).total_seconds()
347 if self.data.localtime:
353 if self.data.localtime:
348 xmax += time.timezone
354 xmax += time.timezone
349 else:
355 else:
350 xmax = self.xmax
356 xmax = self.xmax
351
357
352 ymin = self.ymin if self.ymin else numpy.nanmin(self.y)
358 ymin = self.ymin if self.ymin else numpy.nanmin(self.y)
353 ymax = self.ymax if self.ymax else numpy.nanmax(self.y)
359 ymax = self.ymax if self.ymax else numpy.nanmax(self.y)
354
360
355 Y = numpy.array([10, 20, 50, 100, 200, 500, 1000, 2000])
361 Y = numpy.array([10, 20, 50, 100, 200, 500, 1000, 2000])
356 i = 1 if numpy.where(ymax < Y)[0][0] < 0 else numpy.where(ymax < Y)[0][0]
362 i = 1 if numpy.where(ymax < Y)[
357 ystep = Y[i-1]/5
363 0][0] < 0 else numpy.where(ymax < Y)[0][0]
364 ystep = Y[i - 1] / 5
358
365
359 ystep = 200 if ymax >= 800 else 100 if ymax >= 400 else 50 if ymax >= 200 else 20
366 ystep = 200 if ymax >= 800 else 100 if ymax >= 400 else 50 if ymax >= 200 else 20
360
367
361 for n, ax in enumerate(self.axes):
368 for n, ax in enumerate(self.axes):
362 if ax.firsttime:
369 if ax.firsttime:
363 ax.set_facecolor(self.bgcolor)
370 ax.set_facecolor(self.bgcolor)
364 ax.yaxis.set_major_locator(MultipleLocator(ystep))
371 ax.yaxis.set_major_locator(MultipleLocator(ystep))
365 if self.xaxis is 'time':
372 if self.xaxis is 'time':
366 ax.xaxis.set_major_formatter(FuncFormatter(self.__fmtTime))
373 ax.xaxis.set_major_formatter(FuncFormatter(self.__fmtTime))
367 ax.xaxis.set_major_locator(LinearLocator(9))
374 ax.xaxis.set_major_locator(LinearLocator(9))
368 if self.xlabel is not None:
375 if self.xlabel is not None:
369 ax.set_xlabel(self.xlabel)
376 ax.set_xlabel(self.xlabel)
370 ax.set_ylabel(self.ylabel)
377 ax.set_ylabel(self.ylabel)
371 ax.firsttime = False
378 ax.firsttime = False
372 if self.showprofile:
379 if self.showprofile:
373 self.pf_axes[n].set_ylim(ymin, ymax)
380 self.pf_axes[n].set_ylim(ymin, ymax)
374 self.pf_axes[n].set_xlim(self.zmin, self.zmax)
381 self.pf_axes[n].set_xlim(self.zmin, self.zmax)
375 self.pf_axes[n].set_xlabel('dB')
382 self.pf_axes[n].set_xlabel('dB')
376 self.pf_axes[n].grid(b=True, axis='x')
383 self.pf_axes[n].grid(b=True, axis='x')
377 [tick.set_visible(False)
384 [tick.set_visible(False)
378 for tick in self.pf_axes[n].get_yticklabels()]
385 for tick in self.pf_axes[n].get_yticklabels()]
379 if self.colorbar:
386 if self.colorbar:
380 ax.cbar = plt.colorbar(ax.plt, ax=ax, pad=0.02, aspect=10)
387 ax.cbar = plt.colorbar(ax.plt, ax=ax, pad=0.02, aspect=10)
381 ax.cbar.ax.tick_params(labelsize=8)
388 ax.cbar.ax.tick_params(labelsize=8)
382 ax.cbar.ax.press = None
389 ax.cbar.ax.press = None
383 if self.cb_label:
390 if self.cb_label:
384 ax.cbar.set_label(self.cb_label, size=8)
391 ax.cbar.set_label(self.cb_label, size=8)
385 elif self.cb_labels:
392 elif self.cb_labels:
386 ax.cbar.set_label(self.cb_labels[n], size=8)
393 ax.cbar.set_label(self.cb_labels[n], size=8)
387 else:
394 else:
388 ax.cbar = None
395 ax.cbar = None
389
396
390 ax.set_title('{} - {} {}'.format(
397 ax.set_title('{} - {} {}'.format(
391 self.titles[n],
398 self.titles[n],
392 self.getDateTime(self.max_time).strftime('%H:%M:%S'),
399 self.getDateTime(self.max_time).strftime('%H:%M:%S'),
393 self.time_label),
400 self.time_label),
394 size=8)
401 size=8)
395 ax.set_xlim(xmin, xmax)
402 ax.set_xlim(xmin, xmax)
396 ax.set_ylim(ymin, ymax)
403 ax.set_ylim(ymin, ymax)
397
404
398 def __plot(self):
405 def __plot(self):
399 '''
406 '''
400 '''
407 '''
401 log.success('Plotting', self.name)
408 log.success('Plotting', self.name)
402
409
403 self.plot()
410 self.plot()
404 self.format()
411 self.format()
405
412
406 for n, fig in enumerate(self.figures):
413 for n, fig in enumerate(self.figures):
407 if self.nrows == 0 or self.nplots == 0:
414 if self.nrows == 0 or self.nplots == 0:
408 log.warning('No data', self.name)
415 log.warning('No data', self.name)
409 continue
416 continue
410
417
411 fig.tight_layout()
418 fig.tight_layout()
412 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
419 fig.canvas.manager.set_window_title('{} - {}'.format(self.title,
413 self.getDateTime(self.max_time).strftime('%Y/%m/%d')))
420 self.getDateTime(self.max_time).strftime('%Y/%m/%d')))
414 # fig.canvas.draw()
421 # fig.canvas.draw()
415
422
416 if self.save and self.data.ended:
423 if self.save: # and self.data.ended:
424 self.contador += 1
417 channels = range(self.nrows)
425 channels = range(self.nrows)
418 if self.oneFigure:
426 if self.oneFigure:
419 label = ''
427 label = ''
420 else:
428 else:
421 label = '_{}'.format(channels[n])
429 label = '_{}'.format(channels[n])
422 figname = os.path.join(
430 figname = os.path.join(
423 self.save,
431 self.save,
424 '{}{}_{}.png'.format(
432 '{}{}_{}{}.png'.format(
425 self.CODE,
433 self.CODE,
426 label,
434 label,
427 self.getDateTime(self.saveTime).strftime('%y%m%d_%H%M%S')
435 self.getDateTime(self.saveTime).strftime(
436 '%y%m%d_%H%M%S'),
437 str(self.contador),
428 )
438 )
429 )
439 )
430 print 'Saving figure: {}'.format(figname)
440 print 'Saving figure: {}'.format(figname)
431 fig.savefig(figname)
441 fig.savefig(figname)
432
442
433 def plot(self):
443 def plot(self):
434 '''
444 '''
435 '''
445 '''
436 raise(NotImplementedError, 'Implement this method in child class')
446 raise(NotImplementedError, 'Implement this method in child class')
437
447
438 def run(self):
448 def run(self):
439
449
440 log.success('Starting', self.name)
450 log.success('Starting', self.name)
441
451
442 context = zmq.Context()
452 context = zmq.Context()
443 receiver = context.socket(zmq.SUB)
453 receiver = context.socket(zmq.SUB)
444 receiver.setsockopt(zmq.SUBSCRIBE, '')
454 receiver.setsockopt(zmq.SUBSCRIBE, '')
445 receiver.setsockopt(zmq.CONFLATE, self.CONFLATE)
455 receiver.setsockopt(zmq.CONFLATE, self.CONFLATE)
446
456
447 if 'server' in self.kwargs['parent']:
457 if 'server' in self.kwargs['parent']:
448 receiver.connect(
458 receiver.connect(
449 'ipc:///tmp/{}.plots'.format(self.kwargs['parent']['server']))
459 'ipc:///tmp/{}.plots'.format(self.kwargs['parent']['server']))
450 else:
460 else:
451 receiver.connect("ipc:///tmp/zmq.plots")
461 receiver.connect("ipc:///tmp/zmq.plots")
452
462
453 while True:
463 while True:
454 try:
464 try:
455 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)
465 self.data = receiver.recv_pyobj(flags=zmq.NOBLOCK)
456 if self.data.localtime and self.localtime:
466 if self.data.localtime and self.localtime:
457 self.times = self.data.times
467 self.times = self.data.times
458 elif self.data.localtime and not self.localtime:
468 elif self.data.localtime and not self.localtime:
459 self.times = self.data.times + time.timezone
469 self.times = self.data.times + time.timezone
460 elif not self.data.localtime and self.localtime:
470 elif not self.data.localtime and self.localtime:
461 self.times = self.data.times - time.timezone
471 self.times = self.data.times - time.timezone
462 else:
472 else:
463 self.times = self.data.times
473 self.times = self.data.times
464
474
465 self.min_time = self.times[0]
475 self.min_time = self.times[0]
466 self.max_time = self.times[-1]
476 self.max_time = self.times[-1]
467
477
468 if self.isConfig is False:
478 if self.isConfig is False:
469 self.__setup()
479 self.__setup()
470 self.isConfig = True
480 self.isConfig = True
471
481
472 self.__plot()
482 self.__plot()
473
483
474 except zmq.Again as e:
484 except zmq.Again as e:
475 log.log('Waiting for data...')
485 log.log('Waiting for data...')
476 if self.data:
486 if self.data:
477 figpause(self.data.throttle)
487 figpause(self.data.throttle)
478 else:
488 else:
479 time.sleep(2)
489 time.sleep(2)
480
490
481 def close(self):
491 def close(self):
482 if self.data:
492 if self.data:
483 self.__plot()
493 self.__plot()
484
494
485
495
486 class PlotSpectraData(PlotData):
496 class PlotSpectraData(PlotData):
487 '''
497 '''
488 Plot for Spectra data
498 Plot for Spectra data
489 '''
499 '''
490
500
491 CODE = 'spc'
501 CODE = 'spc'
492 colormap = 'jro'
502 colormap = 'jro'
493
503
494 def setup(self):
504 def setup(self):
495 self.nplots = len(self.data.channels)
505 self.nplots = len(self.data.channels)
496 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
506 self.ncols = int(numpy.sqrt(self.nplots) + 0.9)
497 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
507 self.nrows = int((1.0 * self.nplots / self.ncols) + 0.9)
498 self.width = 3.4 * self.ncols
508 self.width = 3.4 * self.ncols
499 self.height = 3 * self.nrows
509 self.height = 3 * self.nrows
500 self.cb_label = 'dB'
510 self.cb_label = 'dB'
501 if self.showprofile:
511 if self.showprofile:
502 self.width += 0.8 * self.ncols
512 self.width += 0.8 * self.ncols
503
513
504 self.ylabel = 'Range [Km]'
514 self.ylabel = 'Range [Km]'
505
515
506 def plot(self):
516 def plot(self):
507 if self.xaxis == "frequency":
517 if self.xaxis == "frequency":
508 x = self.data.xrange[0]
518 x = self.data.xrange[0]
509 self.xlabel = "Frequency (kHz)"
519 self.xlabel = "Frequency (kHz)"
510 elif self.xaxis == "time":
520 elif self.xaxis == "time":
511 x = self.data.xrange[1]
521 x = self.data.xrange[1]
512 self.xlabel = "Time (ms)"
522 self.xlabel = "Time (ms)"
513 else:
523 else:
514 x = self.data.xrange[2]
524 x = self.data.xrange[2]
515 self.xlabel = "Velocity (m/s)"
525 self.xlabel = "Velocity (m/s)"
516
526
517 if self.CODE == 'spc_mean':
527 if self.CODE == 'spc_mean':
518 x = self.data.xrange[2]
528 x = self.data.xrange[2]
519 self.xlabel = "Velocity (m/s)"
529 self.xlabel = "Velocity (m/s)"
520
530
521 self.titles = []
531 self.titles = []
522
532
523 y = self.data.heights
533 y = self.data.heights
524 self.y = y
534 self.y = y
525 z = self.data['spc']
535 z = self.data['spc']
526
536
527 for n, ax in enumerate(self.axes):
537 for n, ax in enumerate(self.axes):
528 noise = self.data['noise'][n][-1]
538 noise = self.data['noise'][n][-1]
529 if self.CODE == 'spc_mean':
539 if self.CODE == 'spc_mean':
530 mean = self.data['mean'][n][-1]
540 mean = self.data['mean'][n][-1]
531 if ax.firsttime:
541 if ax.firsttime:
532 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
542 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
533 self.xmin = self.xmin if self.xmin else -self.xmax
543 self.xmin = self.xmin if self.xmin else -self.xmax
534 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
544 self.zmin = self.zmin if self.zmin else numpy.nanmin(z)
535 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
545 self.zmax = self.zmax if self.zmax else numpy.nanmax(z)
536 ax.plt = ax.pcolormesh(x, y, z[n].T,
546 ax.plt = ax.pcolormesh(x, y, z[n].T,
537 vmin=self.zmin,
547 vmin=self.zmin,
538 vmax=self.zmax,
548 vmax=self.zmax,
539 cmap=plt.get_cmap(self.colormap)
549 cmap=plt.get_cmap(self.colormap)
540 )
550 )
541
551
542 if self.showprofile:
552 if self.showprofile:
543 ax.plt_profile = self.pf_axes[n].plot(
553 ax.plt_profile = self.pf_axes[n].plot(
544 self.data['rti'][n][-1], y)[0]
554 self.data['rti'][n][-1], y)[0]
545 ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
555 ax.plt_noise = self.pf_axes[n].plot(numpy.repeat(noise, len(y)), y,
546 color="k", linestyle="dashed", lw=1)[0]
556 color="k", linestyle="dashed", lw=1)[0]
547 if self.CODE == 'spc_mean':
557 if self.CODE == 'spc_mean':
548 ax.plt_mean = ax.plot(mean, y, color='k')[0]
558 ax.plt_mean = ax.plot(mean, y, color='k')[0]
549 else:
559 else:
550 ax.plt.set_array(z[n].T.ravel())
560 ax.plt.set_array(z[n].T.ravel())
551 if self.showprofile:
561 if self.showprofile:
552 ax.plt_profile.set_data(self.data['rti'][n][-1], y)
562 ax.plt_profile.set_data(self.data['rti'][n][-1], y)
553 ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
563 ax.plt_noise.set_data(numpy.repeat(noise, len(y)), y)
554 if self.CODE == 'spc_mean':
564 if self.CODE == 'spc_mean':
555 ax.plt_mean.set_data(mean, y)
565 ax.plt_mean.set_data(mean, y)
556
566
557 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
567 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
558 self.saveTime = self.max_time
568 self.saveTime = self.max_time
559
569
560
570
561 class PlotCrossSpectraData(PlotData):
571 class PlotCrossSpectraData(PlotData):
562
572
563 CODE = 'cspc'
573 CODE = 'cspc'
564 zmin_coh = None
574 zmin_coh = None
565 zmax_coh = None
575 zmax_coh = None
566 zmin_phase = None
576 zmin_phase = None
567 zmax_phase = None
577 zmax_phase = None
568
578
569 def setup(self):
579 def setup(self):
570
580
571 self.ncols = 4
581 self.ncols = 4
572 self.nrows = len(self.data.pairs)
582 self.nrows = len(self.data.pairs)
573 self.nplots = self.nrows * 4
583 self.nplots = self.nrows * 4
574 self.width = 3.4 * self.ncols
584 self.width = 3.4 * self.ncols
575 self.height = 3 * self.nrows
585 self.height = 3 * self.nrows
576 self.ylabel = 'Range [Km]'
586 self.ylabel = 'Range [Km]'
577 self.showprofile = False
587 self.showprofile = False
578
588
579 def plot(self):
589 def plot(self):
580
590
581 if self.xaxis == "frequency":
591 if self.xaxis == "frequency":
582 x = self.data.xrange[0]
592 x = self.data.xrange[0]
583 self.xlabel = "Frequency (kHz)"
593 self.xlabel = "Frequency (kHz)"
584 elif self.xaxis == "time":
594 elif self.xaxis == "time":
585 x = self.data.xrange[1]
595 x = self.data.xrange[1]
586 self.xlabel = "Time (ms)"
596 self.xlabel = "Time (ms)"
587 else:
597 else:
588 x = self.data.xrange[2]
598 x = self.data.xrange[2]
589 self.xlabel = "Velocity (m/s)"
599 self.xlabel = "Velocity (m/s)"
590
600
591 self.titles = []
601 self.titles = []
592
602
593 y = self.data.heights
603 y = self.data.heights
594 self.y = y
604 self.y = y
595 spc = self.data['spc']
605 spc = self.data['spc']
596 cspc = self.data['cspc']
606 cspc = self.data['cspc']
597
607
598 for n in range(self.nrows):
608 for n in range(self.nrows):
599 noise = self.data['noise'][n][-1]
609 noise = self.data['noise'][n][-1]
600 pair = self.data.pairs[n]
610 pair = self.data.pairs[n]
601 ax = self.axes[4 * n]
611 ax = self.axes[4 * n]
602 ax3 = self.axes[4 * n + 3]
612 ax3 = self.axes[4 * n + 3]
603 if ax.firsttime:
613 if ax.firsttime:
604 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
614 self.xmax = self.xmax if self.xmax else numpy.nanmax(x)
605 self.xmin = self.xmin if self.xmin else -self.xmax
615 self.xmin = self.xmin if self.xmin else -self.xmax
606 self.zmin = self.zmin if self.zmin else numpy.nanmin(spc)
616 self.zmin = self.zmin if self.zmin else numpy.nanmin(spc)
607 self.zmax = self.zmax if self.zmax else numpy.nanmax(spc)
617 self.zmax = self.zmax if self.zmax else numpy.nanmax(spc)
608 ax.plt = ax.pcolormesh(x, y, spc[pair[0]].T,
618 ax.plt = ax.pcolormesh(x, y, spc[pair[0]].T,
609 vmin=self.zmin,
619 vmin=self.zmin,
610 vmax=self.zmax,
620 vmax=self.zmax,
611 cmap=plt.get_cmap(self.colormap)
621 cmap=plt.get_cmap(self.colormap)
612 )
622 )
613 else:
623 else:
614 ax.plt.set_array(spc[pair[0]].T.ravel())
624 ax.plt.set_array(spc[pair[0]].T.ravel())
615 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
625 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
616
626
617 ax = self.axes[4 * n + 1]
627 ax = self.axes[4 * n + 1]
618 if ax.firsttime:
628 if ax.firsttime:
619 ax.plt = ax.pcolormesh(x, y, spc[pair[1]].T,
629 ax.plt = ax.pcolormesh(x, y, spc[pair[1]].T,
620 vmin=self.zmin,
630 vmin=self.zmin,
621 vmax=self.zmax,
631 vmax=self.zmax,
622 cmap=plt.get_cmap(self.colormap)
632 cmap=plt.get_cmap(self.colormap)
623 )
633 )
624 else:
634 else:
625 ax.plt.set_array(spc[pair[1]].T.ravel())
635 ax.plt.set_array(spc[pair[1]].T.ravel())
626 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
636 self.titles.append('CH {}: {:3.2f}dB'.format(n, noise))
627
637
628 out = cspc[n] / numpy.sqrt(spc[pair[0]] * spc[pair[1]])
638 out = cspc[n] / numpy.sqrt(spc[pair[0]] * spc[pair[1]])
629 coh = numpy.abs(out)
639 coh = numpy.abs(out)
630 phase = numpy.arctan2(out.imag, out.real) * 180 / numpy.pi
640 phase = numpy.arctan2(out.imag, out.real) * 180 / numpy.pi
631
641
632 ax = self.axes[4 * n + 2]
642 ax = self.axes[4 * n + 2]
633 if ax.firsttime:
643 if ax.firsttime:
634 ax.plt = ax.pcolormesh(x, y, coh.T,
644 ax.plt = ax.pcolormesh(x, y, coh.T,
635 vmin=0,
645 vmin=0,
636 vmax=1,
646 vmax=1,
637 cmap=plt.get_cmap(self.colormap_coh)
647 cmap=plt.get_cmap(self.colormap_coh)
638 )
648 )
639 else:
649 else:
640 ax.plt.set_array(coh.T.ravel())
650 ax.plt.set_array(coh.T.ravel())
641 self.titles.append(
651 self.titles.append(
642 'Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
652 'Coherence Ch{} * Ch{}'.format(pair[0], pair[1]))
643
653
644 ax = self.axes[4 * n + 3]
654 ax = self.axes[4 * n + 3]
645 if ax.firsttime:
655 if ax.firsttime:
646 ax.plt = ax.pcolormesh(x, y, phase.T,
656 ax.plt = ax.pcolormesh(x, y, phase.T,
647 vmin=-180,
657 vmin=-180,
648 vmax=180,
658 vmax=180,
649 cmap=plt.get_cmap(self.colormap_phase)
659 cmap=plt.get_cmap(self.colormap_phase)
650 )
660 )
651 else:
661 else:
652 ax.plt.set_array(phase.T.ravel())
662 ax.plt.set_array(phase.T.ravel())
653 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
663 self.titles.append('Phase CH{} * CH{}'.format(pair[0], pair[1]))
654
664
655 self.saveTime = self.max_time
665 self.saveTime = self.max_time
656
666
657
667
658 class PlotSpectraMeanData(PlotSpectraData):
668 class PlotSpectraMeanData(PlotSpectraData):
659 '''
669 '''
660 Plot for Spectra and Mean
670 Plot for Spectra and Mean
661 '''
671 '''
662 CODE = 'spc_mean'
672 CODE = 'spc_mean'
663 colormap = 'jro'
673 colormap = 'jro'
664
674
665
675
666 class PlotRTIData(PlotData):
676 class PlotRTIData(PlotData):
667 '''
677 '''
668 Plot for RTI data
678 Plot for RTI data
669 '''
679 '''
670
680
671 CODE = 'rti'
681 CODE = 'rti'
672 colormap = 'jro'
682 colormap = 'jro'
673
683
674 def setup(self):
684 def setup(self):
675 self.xaxis = 'time'
685 self.xaxis = 'time'
676 self.ncols = 1
686 self.ncols = 1
677 self.nrows = len(self.data.channels)
687 self.nrows = len(self.data.channels)
678 self.nplots = len(self.data.channels)
688 self.nplots = len(self.data.channels)
679 self.ylabel = 'Range [Km]'
689 self.ylabel = 'Range [Km]'
680 self.cb_label = 'dB'
690 self.cb_label = 'dB'
681 self.titles = ['{} Channel {}'.format(
691 self.titles = ['{} Channel {}'.format(
682 self.CODE.upper(), x) for x in range(self.nrows)]
692 self.CODE.upper(), x) for x in range(self.nrows)]
683
693
684 def plot(self):
694 def plot(self):
685 self.x = self.times
695 self.x = self.times
686 self.y = self.data.heights
696 self.y = self.data.heights
687 self.z = self.data[self.CODE]
697 self.z = self.data[self.CODE]
688 self.z = numpy.ma.masked_invalid(self.z)
698 self.z = numpy.ma.masked_invalid(self.z)
689
699
690 for n, ax in enumerate(self.axes):
700 for n, ax in enumerate(self.axes):
691 x, y, z = self.fill_gaps(*self.decimate())
701 x, y, z = self.fill_gaps(*self.decimate())
692 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
702 self.zmin = self.zmin if self.zmin else numpy.min(self.z)
693 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
703 self.zmax = self.zmax if self.zmax else numpy.max(self.z)
694 if ax.firsttime:
704 if ax.firsttime:
695 ax.plt = ax.pcolormesh(x, y, z[n].T,
705 ax.plt = ax.pcolormesh(x, y, z[n].T,
696 vmin=self.zmin,
706 vmin=self.zmin,
697 vmax=self.zmax,
707 vmax=self.zmax,
698 cmap=plt.get_cmap(self.colormap)
708 cmap=plt.get_cmap(self.colormap)
699 )
709 )
700 if self.showprofile:
710 if self.showprofile:
701 ax.plot_profile = self.pf_axes[n].plot(
711 ax.plot_profile = self.pf_axes[n].plot(
702 self.data['rti'][n][-1], self.y)[0]
712 self.data['rti'][n][-1], self.y)[0]
703 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y,
713 ax.plot_noise = self.pf_axes[n].plot(numpy.repeat(self.data['noise'][n][-1], len(self.y)), self.y,
704 color="k", linestyle="dashed", lw=1)[0]
714 color="k", linestyle="dashed", lw=1)[0]
705 else:
715 else:
706 ax.collections.remove(ax.collections[0])
716 ax.collections.remove(ax.collections[0])
707 ax.plt = ax.pcolormesh(x, y, z[n].T,
717 ax.plt = ax.pcolormesh(x, y, z[n].T,
708 vmin=self.zmin,
718 vmin=self.zmin,
709 vmax=self.zmax,
719 vmax=self.zmax,
710 cmap=plt.get_cmap(self.colormap)
720 cmap=plt.get_cmap(self.colormap)
711 )
721 )
712 if self.showprofile:
722 if self.showprofile:
713 ax.plot_profile.set_data(self.data['rti'][n][-1], self.y)
723 ax.plot_profile.set_data(self.data['rti'][n][-1], self.y)
714 ax.plot_noise.set_data(numpy.repeat(
724 ax.plot_noise.set_data(numpy.repeat(
715 self.data['noise'][n][-1], len(self.y)), self.y)
725 self.data['noise'][n][-1], len(self.y)), self.y)
716
726
717 self.saveTime = self.min_time
727 self.saveTime = self.min_time
718
728
719
729
720 class PlotCOHData(PlotRTIData):
730 class PlotCOHData(PlotRTIData):
721 '''
731 '''
722 Plot for Coherence data
732 Plot for Coherence data
723 '''
733 '''
724
734
725 CODE = 'coh'
735 CODE = 'coh'
726
736
727 def setup(self):
737 def setup(self):
728 self.xaxis = 'time'
738 self.xaxis = 'time'
729 self.ncols = 1
739 self.ncols = 1
730 self.nrows = len(self.data.pairs)
740 self.nrows = len(self.data.pairs)
731 self.nplots = len(self.data.pairs)
741 self.nplots = len(self.data.pairs)
732 self.ylabel = 'Range [Km]'
742 self.ylabel = 'Range [Km]'
733 if self.CODE == 'coh':
743 if self.CODE == 'coh':
734 self.cb_label = ''
744 self.cb_label = ''
735 self.titles = [
745 self.titles = [
736 'Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
746 'Coherence Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
737 else:
747 else:
738 self.cb_label = 'Degrees'
748 self.cb_label = 'Degrees'
739 self.titles = [
749 self.titles = [
740 'Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
750 'Phase Map Ch{} * Ch{}'.format(x[0], x[1]) for x in self.data.pairs]
741
751
742
752
743 class PlotPHASEData(PlotCOHData):
753 class PlotPHASEData(PlotCOHData):
744 '''
754 '''
745 Plot for Phase map data
755 Plot for Phase map data
746 '''
756 '''
747
757
748 CODE = 'phase'
758 CODE = 'phase'
749 colormap = 'seismic'
759 colormap = 'seismic'
750
760
751
761
752 class PlotNoiseData(PlotData):
762 class PlotNoiseData(PlotData):
753 '''
763 '''
754 Plot for noise
764 Plot for noise
755 '''
765 '''
756
766
757 CODE = 'noise'
767 CODE = 'noise'
758
768
759 def setup(self):
769 def setup(self):
760 self.xaxis = 'time'
770 self.xaxis = 'time'
761 self.ncols = 1
771 self.ncols = 1
762 self.nrows = 1
772 self.nrows = 1
763 self.nplots = 1
773 self.nplots = 1
764 self.ylabel = 'Intensity [dB]'
774 self.ylabel = 'Intensity [dB]'
765 self.titles = ['Noise']
775 self.titles = ['Noise']
766 self.colorbar = False
776 self.colorbar = False
767
777
768 def plot(self):
778 def plot(self):
769
779
770 x = self.times
780 x = self.times
771 xmin = self.min_time
781 xmin = self.min_time
772 xmax = xmin + self.xrange * 60 * 60
782 xmax = xmin + self.xrange * 60 * 60
773 Y = self.data[self.CODE]
783 Y = self.data[self.CODE]
774
784
775 if self.axes[0].firsttime:
785 if self.axes[0].firsttime:
776 for ch in self.data.channels:
786 for ch in self.data.channels:
777 y = Y[ch]
787 y = Y[ch]
778 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
788 self.axes[0].plot(x, y, lw=1, label='Ch{}'.format(ch))
779 plt.legend()
789 plt.legend()
780 else:
790 else:
781 for ch in self.data.channels:
791 for ch in self.data.channels:
782 y = Y[ch]
792 y = Y[ch]
783 self.axes[0].lines[ch].set_data(x, y)
793 self.axes[0].lines[ch].set_data(x, y)
784
794
785 self.ymin = numpy.nanmin(Y) - 5
795 self.ymin = numpy.nanmin(Y) - 5
786 self.ymax = numpy.nanmax(Y) + 5
796 self.ymax = numpy.nanmax(Y) + 5
787 self.saveTime = self.min_time
797 self.saveTime = self.min_time
788
798
789
799
790 class PlotSNRData(PlotRTIData):
800 class PlotSNRData(PlotRTIData):
791 '''
801 '''
792 Plot for SNR Data
802 Plot for SNR Data
793 '''
803 '''
794
804
795 CODE = 'snr'
805 CODE = 'snr'
796 colormap = 'jet'
806 colormap = 'jet'
797
807
798
808
799 class PlotDOPData(PlotRTIData):
809 class PlotDOPData(PlotRTIData):
800 '''
810 '''
801 Plot for DOPPLER Data
811 Plot for DOPPLER Data
802 '''
812 '''
803
813
804 CODE = 'dop'
814 CODE = 'dop'
805 colormap = 'jet'
815 colormap = 'jet'
806
816
807
817
808 class PlotSkyMapData(PlotData):
818 class PlotSkyMapData(PlotData):
809 '''
819 '''
810 Plot for meteors detection data
820 Plot for meteors detection data
811 '''
821 '''
812
822
813 CODE = 'met'
823 CODE = 'met'
814
824
815 def setup(self):
825 def setup(self):
816
826
817 self.ncols = 1
827 self.ncols = 1
818 self.nrows = 1
828 self.nrows = 1
819 self.width = 7.2
829 self.width = 7.2
820 self.height = 7.2
830 self.height = 7.2
821
831
822 self.xlabel = 'Zonal Zenith Angle (deg)'
832 self.xlabel = 'Zonal Zenith Angle (deg)'
823 self.ylabel = 'Meridional Zenith Angle (deg)'
833 self.ylabel = 'Meridional Zenith Angle (deg)'
824
834
825 if self.figure is None:
835 if self.figure is None:
826 self.figure = plt.figure(figsize=(self.width, self.height),
836 self.figure = plt.figure(figsize=(self.width, self.height),
827 edgecolor='k',
837 edgecolor='k',
828 facecolor='w')
838 facecolor='w')
829 else:
839 else:
830 self.figure.clf()
840 self.figure.clf()
831
841
832 self.ax = plt.subplot2grid(
842 self.ax = plt.subplot2grid(
833 (self.nrows, self.ncols), (0, 0), 1, 1, polar=True)
843 (self.nrows, self.ncols), (0, 0), 1, 1, polar=True)
834 self.ax.firsttime = True
844 self.ax.firsttime = True
835
845
836 def plot(self):
846 def plot(self):
837
847
838 arrayParameters = numpy.concatenate(
848 arrayParameters = numpy.concatenate(
839 [self.data['param'][t] for t in self.times])
849 [self.data['param'][t] for t in self.times])
840 error = arrayParameters[:, -1]
850 error = arrayParameters[:, -1]
841 indValid = numpy.where(error == 0)[0]
851 indValid = numpy.where(error == 0)[0]
842 finalMeteor = arrayParameters[indValid, :]
852 finalMeteor = arrayParameters[indValid, :]
843 finalAzimuth = finalMeteor[:, 3]
853 finalAzimuth = finalMeteor[:, 3]
844 finalZenith = finalMeteor[:, 4]
854 finalZenith = finalMeteor[:, 4]
845
855
846 x = finalAzimuth * numpy.pi / 180
856 x = finalAzimuth * numpy.pi / 180
847 y = finalZenith
857 y = finalZenith
848
858
849 if self.ax.firsttime:
859 if self.ax.firsttime:
850 self.ax.plot = self.ax.plot(x, y, 'bo', markersize=5)[0]
860 self.ax.plot = self.ax.plot(x, y, 'bo', markersize=5)[0]
851 self.ax.set_ylim(0, 90)
861 self.ax.set_ylim(0, 90)
852 self.ax.set_yticks(numpy.arange(0, 90, 20))
862 self.ax.set_yticks(numpy.arange(0, 90, 20))
853 self.ax.set_xlabel(self.xlabel)
863 self.ax.set_xlabel(self.xlabel)
854 self.ax.set_ylabel(self.ylabel)
864 self.ax.set_ylabel(self.ylabel)
855 self.ax.yaxis.labelpad = 40
865 self.ax.yaxis.labelpad = 40
856 self.ax.firsttime = False
866 self.ax.firsttime = False
857 else:
867 else:
858 self.ax.plot.set_data(x, y)
868 self.ax.plot.set_data(x, y)
859
869
860
861 dt1 = self.getDateTime(self.min_time).strftime('%y/%m/%d %H:%M:%S')
870 dt1 = self.getDateTime(self.min_time).strftime('%y/%m/%d %H:%M:%S')
862 dt2 = self.getDateTime(self.max_time).strftime('%y/%m/%d %H:%M:%S')
871 dt2 = self.getDateTime(self.max_time).strftime('%y/%m/%d %H:%M:%S')
863 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
872 title = 'Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n' % (dt1,
864 dt2,
873 dt2,
865 len(x))
874 len(x))
866 self.ax.set_title(title, size=8)
875 self.ax.set_title(title, size=8)
867 self.saveTime = self.max_time
876 self.saveTime = self.max_time
868
877
869
878
870 class PlotParamData(PlotRTIData):
879 class PlotParamData(PlotRTIData):
871 '''
880 '''
872 Plot for data_param object
881 Plot for data_param object
873 '''
882 '''
874
883
875 CODE = 'param'
884 CODE = 'param'
876 colormap = 'seismic'
885 colormap = 'seismic'
877
886
878 def setup(self):
887 def setup(self):
879 self.xaxis = 'time'
888 self.xaxis = 'time'
880 self.ncols = 1
889 self.ncols = 1
881 self.nrows = self.data.shape(self.CODE)[0]
890 self.nrows = self.data.shape(self.CODE)[0]
882 self.nplots = self.nrows
891 self.nplots = self.nrows
883 if self.showSNR:
892 if self.showSNR:
884 self.nrows += 1
893 self.nrows += 1
885 self.nplots += 1
894 self.nplots += 1
886
895
887 self.ylabel = 'Height [Km]'
896 self.ylabel = 'Height [Km]'
888 self.titles = self.data.parameters \
897 self.titles = self.data.parameters \
889 if self.data.parameters else ['Param {}'.format(x) for x in xrange(self.nrows)]
898 if self.data.parameters else ['Param {}'.format(x) for x in xrange(self.nrows)]
890 if self.showSNR:
899 if self.showSNR:
891 self.titles.append('SNR')
900 self.titles.append('SNR')
892
901
893 def plot(self):
902 def plot(self):
894 self.data.normalize_heights()
903 self.data.normalize_heights()
895 self.x = self.times
904 self.x = self.times
896 self.y = self.data.heights
905 self.y = self.data.heights
897 if self.showSNR:
906 if self.showSNR:
898 self.z = numpy.concatenate(
907 self.z = numpy.concatenate(
899 (self.data[self.CODE], self.data['snr'])
908 (self.data[self.CODE], self.data['snr'])
900 )
909 )
901 else:
910 else:
902 self.z = self.data[self.CODE]
911 self.z = self.data[self.CODE]
903
912
904 self.z = numpy.ma.masked_invalid(self.z)
913 self.z = numpy.ma.masked_invalid(self.z)
905
914
906 for n, ax in enumerate(self.axes):
915 for n, ax in enumerate(self.axes):
907
916
908 x, y, z = self.fill_gaps(*self.decimate())
917 x, y, z = self.fill_gaps(*self.decimate())
909 self.zmax = self.zmax if self.zmax is not None else numpy.max(self.z[n])
918 self.zmax = self.zmax if self.zmax is not None else numpy.max(
910 self.zmin = self.zmin if self.zmin is not None else numpy.min(self.z[n])
919 self.z[n])
911
920 self.zmin = self.zmin if self.zmin is not None else numpy.min(
921 self.z[n])
922
912 if ax.firsttime:
923 if ax.firsttime:
913 if self.zlimits is not None:
924 if self.zlimits is not None:
914 self.zmin, self.zmax = self.zlimits[n]
925 self.zmin, self.zmax = self.zlimits[n]
915
926
916 ax.plt = ax.pcolormesh(x, y, z[n].T*self.factors[n],
927 ax.plt = ax.pcolormesh(x, y, z[n].T * self.factors[n],
917 vmin=self.zmin,
928 vmin=self.zmin,
918 vmax=self.zmax,
929 vmax=self.zmax,
919 cmap=self.cmaps[n]
930 cmap=self.cmaps[n]
920 )
931 )
921 else:
932 else:
922 if self.zlimits is not None:
933 if self.zlimits is not None:
923 self.zmin, self.zmax = self.zlimits[n]
934 self.zmin, self.zmax = self.zlimits[n]
924 ax.collections.remove(ax.collections[0])
935 ax.collections.remove(ax.collections[0])
925 ax.plt = ax.pcolormesh(x, y, z[n].T*self.factors[n],
936 ax.plt = ax.pcolormesh(x, y, z[n].T * self.factors[n],
926 vmin=self.zmin,
937 vmin=self.zmin,
927 vmax=self.zmax,
938 vmax=self.zmax,
928 cmap=self.cmaps[n]
939 cmap=self.cmaps[n]
929 )
940 )
930
941
931 self.saveTime = self.min_time
942 self.saveTime = self.min_time
932
943
944
933 class PlotOutputData(PlotParamData):
945 class PlotOutputData(PlotParamData):
934 '''
946 '''
935 Plot data_output object
947 Plot data_output object
936 '''
948 '''
937
949
938 CODE = 'output'
950 CODE = 'output'
939 colormap = 'seismic'
951 colormap = 'seismic'
General Comments 0
You need to be logged in to leave comments. Login now