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