##// END OF EJS Templates
Se agrega el metodo deflip a jroprocessing.py....
Daniel Valdez -
r239:2e1c2331660d
parent child
Show More
@@ -1,353 +1,368
1 import os
1 import os
2 import numpy
2 import numpy
3 import time, datetime
3 import time, datetime
4 import mpldriver
4 import mpldriver
5
5
6
6
7 class Figure:
7 class Figure:
8
8
9 __driver = mpldriver
9 __driver = mpldriver
10 fig = None
10 fig = None
11
11
12 idfigure = None
12 idfigure = None
13 wintitle = None
13 wintitle = None
14 width = None
14 width = None
15 height = None
15 height = None
16 nplots = None
16 nplots = None
17 timerange = None
17 timerange = None
18
18
19 axesObjList = []
19 axesObjList = []
20
20
21 WIDTH = None
21 WIDTH = None
22 HEIGHT = None
22 HEIGHT = None
23 PREFIX = 'fig'
23 PREFIX = 'fig'
24
24
25 def __init__(self):
25 def __init__(self):
26
26
27 raise ValueError, "This method is not implemented"
27 raise ValueError, "This method is not implemented"
28
28
29 def __del__(self):
29 def __del__(self):
30
30
31 self.__driver.closeFigure()
31 self.__driver.closeFigure()
32
32
33 def getFilename(self, name, ext='.png'):
33 def getFilename(self, name, ext='.png'):
34
34
35 filename = '%s-%s_%s%s' %(self.wintitle[0:10], self.PREFIX, name, ext)
35 filename = '%s-%s_%s%s' %(self.wintitle[0:10], self.PREFIX, name, ext)
36
36
37 return filename
37 return filename
38
38
39 def getAxesObjList(self):
39 def getAxesObjList(self):
40
40
41 return self.axesObjList
41 return self.axesObjList
42
42
43 def getSubplots(self):
43 def getSubplots(self):
44
44
45 raise ValueError, "Abstract method: This method should be defined"
45 raise ValueError, "Abstract method: This method should be defined"
46
46
47 def getScreenDim(self, widthplot, heightplot):
47 def getScreenDim(self, widthplot, heightplot):
48
48
49 nrow, ncol = self.getSubplots()
49 nrow, ncol = self.getSubplots()
50
50
51 widthscreen = widthplot*ncol
51 widthscreen = widthplot*ncol
52 heightscreen = heightplot*nrow
52 heightscreen = heightplot*nrow
53
53
54 return widthscreen, heightscreen
54 return widthscreen, heightscreen
55
55
56 def getTimeLim(self, x, xmin, xmax):
56 def getTimeLim(self, x, xmin, xmax):
57
57
58 thisdatetime = datetime.datetime.fromtimestamp(numpy.min(x))
58 thisdatetime = datetime.datetime.fromtimestamp(numpy.min(x))
59 thisdate = datetime.datetime.combine(thisdatetime.date(), datetime.time(0,0,0))
59 thisdate = datetime.datetime.combine(thisdatetime.date(), datetime.time(0,0,0))
60
60
61 ####################################################
61 ####################################################
62 #If the x is out of xrange
62 #If the x is out of xrange
63 if xmax < (thisdatetime - thisdate).seconds/(60*60.):
63 if xmax < (thisdatetime - thisdate).seconds/(60*60.):
64 xmin = None
64 xmin = None
65 xmax = None
65 xmax = None
66
66
67 if xmin == None:
67 if xmin == None:
68 td = thisdatetime - thisdate
68 td = thisdatetime - thisdate
69 xmin = td.seconds/(60*60.)
69 xmin = td.seconds/(60*60.)
70
70
71 if xmax == None:
71 if xmax == None:
72 xmax = xmin + self.timerange/(60*60.)
72 xmax = xmin + self.timerange/(60*60.)
73
73
74 mindt = thisdate + datetime.timedelta(0,0,0,0,0, xmin)
74 mindt = thisdate + datetime.timedelta(0,0,0,0,0, xmin)
75 tmin = time.mktime(mindt.timetuple())
75 tmin = time.mktime(mindt.timetuple())
76
76
77 maxdt = thisdate + datetime.timedelta(0,0,0,0,0, xmax)
77 maxdt = thisdate + datetime.timedelta(0,0,0,0,0, xmax)
78 tmax = time.mktime(maxdt.timetuple())
78 tmax = time.mktime(maxdt.timetuple())
79
79
80 self.timerange = tmax - tmin
80 self.timerange = tmax - tmin
81
81
82 return tmin, tmax
82 return tmin, tmax
83
83
84 def init(self, idfigure, nplots, wintitle):
84 def init(self, idfigure, nplots, wintitle):
85
85
86 raise ValueError, "This method has been replaced with createFigure"
86 raise ValueError, "This method has been replaced with createFigure"
87
87
88 def createFigure(self, idfigure, wintitle, widthplot=None, heightplot=None):
88 def createFigure(self, idfigure, wintitle, widthplot=None, heightplot=None):
89
89
90 """
90 """
91 Crea la figura de acuerdo al driver y parametros seleccionados seleccionados.
91 Crea la figura de acuerdo al driver y parametros seleccionados seleccionados.
92 Las dimensiones de la pantalla es calculada a partir de los atributos self.WIDTH
92 Las dimensiones de la pantalla es calculada a partir de los atributos self.WIDTH
93 y self.HEIGHT y el numero de subplots (nrow, ncol)
93 y self.HEIGHT y el numero de subplots (nrow, ncol)
94
94
95 Input:
95 Input:
96 idfigure : Los parametros necesarios son
96 idfigure : Los parametros necesarios son
97 wintitle :
97 wintitle :
98
98
99 """
99 """
100
100
101 if widthplot == None:
101 if widthplot == None:
102 widthplot = self.WIDTH
102 widthplot = self.WIDTH
103
103
104 if heightplot == None:
104 if heightplot == None:
105 heightplot = self.HEIGHT
105 heightplot = self.HEIGHT
106
106
107 self.idfigure = idfigure
107 self.idfigure = idfigure
108
108
109 self.wintitle = wintitle
109 self.wintitle = wintitle
110
110
111 self.widthscreen, self.heightscreen = self.getScreenDim(widthplot, heightplot)
111 self.widthscreen, self.heightscreen = self.getScreenDim(widthplot, heightplot)
112
112
113 self.fig = self.__driver.createFigure(self.idfigure,
113 self.fig = self.__driver.createFigure(self.idfigure,
114 self.wintitle,
114 self.wintitle,
115 self.widthscreen,
115 self.widthscreen,
116 self.heightscreen)
116 self.heightscreen)
117
117
118 self.axesObjList = []
118 self.axesObjList = []
119
119
120 def setDriver(self, driver=mpldriver):
120 def setDriver(self, driver=mpldriver):
121
121
122 self.__driver = driver
122 self.__driver = driver
123
123
124 def setTitle(self, title):
124 def setTitle(self, title):
125
125
126 self.__driver.setTitle(self.fig, title)
126 self.__driver.setTitle(self.fig, title)
127
127
128 def setWinTitle(self, title):
128 def setWinTitle(self, title):
129
129
130 self.__driver.setWinTitle(self.fig, title=title)
130 self.__driver.setWinTitle(self.fig, title=title)
131
131
132 def setTextFromAxes(self, text):
132 def setTextFromAxes(self, text):
133
133
134 raise ValueError, "Este metodo ha sido reemplazaado con el metodo setText de la clase Axes"
134 raise ValueError, "Este metodo ha sido reemplazaado con el metodo setText de la clase Axes"
135
135
136 def makeAxes(self, nrow, ncol, xpos, ypos, colspan, rowspan):
136 def makeAxes(self, nrow, ncol, xpos, ypos, colspan, rowspan):
137
137
138 raise ValueError, "Este metodo ha sido reemplazaado con el metodo addAxes"
138 raise ValueError, "Este metodo ha sido reemplazaado con el metodo addAxes"
139
139
140 def addAxes(self, *args):
140 def addAxes(self, *args):
141 """
141 """
142
142
143 Input:
143 Input:
144 *args : Los parametros necesarios son
144 *args : Los parametros necesarios son
145 nrow, ncol, xpos, ypos, colspan, rowspan
145 nrow, ncol, xpos, ypos, colspan, rowspan
146 """
146 """
147
147
148 axesObj = Axes(self.fig, *args)
148 axesObj = Axes(self.fig, *args)
149 self.axesObjList.append(axesObj)
149 self.axesObjList.append(axesObj)
150
150
151 def saveFigure(self, figpath, figfile, *args):
151 def saveFigure(self, figpath, figfile, *args):
152
152
153 filename = os.path.join(figpath, figfile)
153 filename = os.path.join(figpath, figfile)
154 self.__driver.saveFigure(self.fig, filename, *args)
154 self.__driver.saveFigure(self.fig, filename, *args)
155
155
156 def draw(self):
156 def draw(self):
157
157
158 self.__driver.draw(self.fig)
158 self.__driver.draw(self.fig)
159
159
160 def run(self):
160 def run(self):
161
161
162 raise ValueError, "This method is not implemented"
162 raise ValueError, "This method is not implemented"
163
163
164 axesList = property(getAxesObjList)
164 axesList = property(getAxesObjList)
165
165
166
166
167 class Axes:
167 class Axes:
168
168
169 __driver = mpldriver
169 __driver = mpldriver
170 fig = None
170 fig = None
171 ax = None
171 ax = None
172 plot = None
172 plot = None
173
173
174 __firsttime = None
174 __firsttime = None
175
175
176 __showprofile = False
176 __showprofile = False
177
177
178 xmin = None
178 xmin = None
179 xmax = None
179 xmax = None
180 ymin = None
180 ymin = None
181 ymax = None
181 ymax = None
182 zmin = None
182 zmin = None
183 zmax = None
183 zmax = None
184
184
185 def __init__(self, *args):
185 def __init__(self, *args):
186
186
187 """
187 """
188
188
189 Input:
189 Input:
190 *args : Los parametros necesarios son
190 *args : Los parametros necesarios son
191 fig, nrow, ncol, xpos, ypos, colspan, rowspan
191 fig, nrow, ncol, xpos, ypos, colspan, rowspan
192 """
192 """
193
193
194 ax = self.__driver.createAxes(*args)
194 ax = self.__driver.createAxes(*args)
195 self.fig = args[0]
195 self.fig = args[0]
196 self.ax = ax
196 self.ax = ax
197 self.plot = None
197 self.plot = None
198
198
199 self.__firsttime = True
199 self.__firsttime = True
200 self.idlineList = []
200
201
201 def setText(self, text):
202 def setText(self, text):
202
203
203 self.__driver.setAxesText(self.ax, text)
204 self.__driver.setAxesText(self.ax, text)
204
205
205 def setXAxisAsTime(self):
206 def setXAxisAsTime(self):
206 pass
207 pass
207
208
208 def pline(self, x, y,
209 def pline(self, x, y,
209 xmin=None, xmax=None,
210 xmin=None, xmax=None,
210 ymin=None, ymax=None,
211 ymin=None, ymax=None,
211 xlabel='', ylabel='',
212 xlabel='', ylabel='',
212 title='',
213 title='',
213 **kwargs):
214 **kwargs):
214
215
215 """
216 """
216
217
217 Input:
218 Input:
218 x :
219 x :
219 y :
220 y :
220 xmin :
221 xmin :
221 xmax :
222 xmax :
222 ymin :
223 ymin :
223 ymax :
224 ymax :
224 xlabel :
225 xlabel :
225 ylabel :
226 ylabel :
226 title :
227 title :
227 **kwargs : Los parametros aceptados son
228 **kwargs : Los parametros aceptados son
228
229
229 ticksize
230 ticksize
230 ytick_visible
231 ytick_visible
231 """
232 """
232
233
233 if self.__firsttime:
234 if self.__firsttime:
234
235
235 if xmin == None: xmin = numpy.nanmin(x)
236 if xmin == None: xmin = numpy.nanmin(x)
236 if xmax == None: xmax = numpy.nanmax(x)
237 if xmax == None: xmax = numpy.nanmax(x)
237 if ymin == None: ymin = numpy.nanmin(y)
238 if ymin == None: ymin = numpy.nanmin(y)
238 if ymax == None: ymax = numpy.nanmax(y)
239 if ymax == None: ymax = numpy.nanmax(y)
239
240
240 self.plot = self.__driver.createPline(self.ax, x, y,
241 self.plot = self.__driver.createPline(self.ax, x, y,
241 xmin, xmax,
242 xmin, xmax,
242 ymin, ymax,
243 ymin, ymax,
243 xlabel=xlabel,
244 xlabel=xlabel,
244 ylabel=ylabel,
245 ylabel=ylabel,
245 title=title,
246 title=title,
246 **kwargs)
247 **kwargs)
248
249 self.idlineList.append(0)
247 self.__firsttime = False
250 self.__firsttime = False
248 return
251 return
249
252
250 self.__driver.pline(self.plot, x, y, xlabel=xlabel,
253 self.__driver.pline(self.plot, x, y, xlabel=xlabel,
251 ylabel=ylabel,
254 ylabel=ylabel,
252 title=title)
255 title=title)
256
257 def addpline(self, x, y, idline, **kwargs):
258 lines = self.ax.lines
259
260 if idline in self.idlineList:
261 self.__driver.set_linedata(self.ax, x, y, idline)
262
263 if idline not in(self.idlineList):
264 self.__driver.addpline(self.ax, x, y, **kwargs)
265 self.idlineList.append(idline)
266
267 return
253
268
254 def pmultiline(self, x, y,
269 def pmultiline(self, x, y,
255 xmin=None, xmax=None,
270 xmin=None, xmax=None,
256 ymin=None, ymax=None,
271 ymin=None, ymax=None,
257 xlabel='', ylabel='',
272 xlabel='', ylabel='',
258 title='',
273 title='',
259 **kwargs):
274 **kwargs):
260
275
261 if self.__firsttime:
276 if self.__firsttime:
262
277
263 if xmin == None: xmin = numpy.nanmin(x)
278 if xmin == None: xmin = numpy.nanmin(x)
264 if xmax == None: xmax = numpy.nanmax(x)
279 if xmax == None: xmax = numpy.nanmax(x)
265 if ymin == None: ymin = numpy.nanmin(y)
280 if ymin == None: ymin = numpy.nanmin(y)
266 if ymax == None: ymax = numpy.nanmax(y)
281 if ymax == None: ymax = numpy.nanmax(y)
267
282
268 self.plot = self.__driver.createPmultiline(self.ax, x, y,
283 self.plot = self.__driver.createPmultiline(self.ax, x, y,
269 xmin, xmax,
284 xmin, xmax,
270 ymin, ymax,
285 ymin, ymax,
271 xlabel=xlabel,
286 xlabel=xlabel,
272 ylabel=ylabel,
287 ylabel=ylabel,
273 title=title,
288 title=title,
274 **kwargs)
289 **kwargs)
275 self.__firsttime = False
290 self.__firsttime = False
276 return
291 return
277
292
278 self.__driver.pmultiline(self.plot, x, y, xlabel=xlabel,
293 self.__driver.pmultiline(self.plot, x, y, xlabel=xlabel,
279 ylabel=ylabel,
294 ylabel=ylabel,
280 title=title)
295 title=title)
281
296
282 def pcolor(self, x, y, z,
297 def pcolor(self, x, y, z,
283 xmin=None, xmax=None,
298 xmin=None, xmax=None,
284 ymin=None, ymax=None,
299 ymin=None, ymax=None,
285 zmin=None, zmax=None,
300 zmin=None, zmax=None,
286 xlabel='', ylabel='',
301 xlabel='', ylabel='',
287 title='', rti = False, colormap='jet',
302 title='', rti = False, colormap='jet',
288 **kwargs):
303 **kwargs):
289
304
290 """
305 """
291 Input:
306 Input:
292 x :
307 x :
293 y :
308 y :
294 x :
309 x :
295 xmin :
310 xmin :
296 xmax :
311 xmax :
297 ymin :
312 ymin :
298 ymax :
313 ymax :
299 zmin :
314 zmin :
300 zmax :
315 zmax :
301 xlabel :
316 xlabel :
302 ylabel :
317 ylabel :
303 title :
318 title :
304 **kwargs : Los parametros aceptados son
319 **kwargs : Los parametros aceptados son
305 ticksize=9,
320 ticksize=9,
306 cblabel=''
321 cblabel=''
307 rti = True or False
322 rti = True or False
308 """
323 """
309
324
310 if self.__firsttime:
325 if self.__firsttime:
311
326
312 if xmin == None: xmin = numpy.nanmin(x)
327 if xmin == None: xmin = numpy.nanmin(x)
313 if xmax == None: xmax = numpy.nanmax(x)
328 if xmax == None: xmax = numpy.nanmax(x)
314 if ymin == None: ymin = numpy.nanmin(y)
329 if ymin == None: ymin = numpy.nanmin(y)
315 if ymax == None: ymax = numpy.nanmax(y)
330 if ymax == None: ymax = numpy.nanmax(y)
316 if zmin == None: zmin = numpy.nanmin(z)
331 if zmin == None: zmin = numpy.nanmin(z)
317 if zmax == None: zmax = numpy.nanmax(z)
332 if zmax == None: zmax = numpy.nanmax(z)
318
333
319
334
320 self.plot = self.__driver.createPcolor(self.ax, x, y, z,
335 self.plot = self.__driver.createPcolor(self.ax, x, y, z,
321 xmin, xmax,
336 xmin, xmax,
322 ymin, ymax,
337 ymin, ymax,
323 zmin, zmax,
338 zmin, zmax,
324 xlabel=xlabel,
339 xlabel=xlabel,
325 ylabel=ylabel,
340 ylabel=ylabel,
326 title=title,
341 title=title,
327 colormap=colormap,
342 colormap=colormap,
328 **kwargs)
343 **kwargs)
329
344
330 if self.xmin == None: self.xmin = xmin
345 if self.xmin == None: self.xmin = xmin
331 if self.xmax == None: self.xmax = xmax
346 if self.xmax == None: self.xmax = xmax
332 if self.ymin == None: self.ymin = ymin
347 if self.ymin == None: self.ymin = ymin
333 if self.ymax == None: self.ymax = ymax
348 if self.ymax == None: self.ymax = ymax
334 if self.zmin == None: self.zmin = zmin
349 if self.zmin == None: self.zmin = zmin
335 if self.zmax == None: self.zmax = zmax
350 if self.zmax == None: self.zmax = zmax
336
351
337 self.__firsttime = False
352 self.__firsttime = False
338 return
353 return
339
354
340 if rti:
355 if rti:
341 self.__driver.addpcolor(self.ax, x, y, z, self.zmin, self.zmax,
356 self.__driver.addpcolor(self.ax, x, y, z, self.zmin, self.zmax,
342 xlabel=xlabel,
357 xlabel=xlabel,
343 ylabel=ylabel,
358 ylabel=ylabel,
344 title=title,
359 title=title,
345 colormap=colormap)
360 colormap=colormap)
346 return
361 return
347
362
348 self.__driver.pcolor(self.plot, z,
363 self.__driver.pcolor(self.plot, z,
349 xlabel=xlabel,
364 xlabel=xlabel,
350 ylabel=ylabel,
365 ylabel=ylabel,
351 title=title)
366 title=title)
352
367
353 No newline at end of file
368
@@ -1,268 +1,275
1 import numpy
1 import numpy
2 import datetime
2 import datetime
3 import matplotlib
3 import matplotlib
4 matplotlib.use("TKAgg")
4 matplotlib.use("TKAgg")
5 import matplotlib.pyplot
5 import matplotlib.pyplot
6 import matplotlib.dates
6 import matplotlib.dates
7 #import scitools.numpyutils
7 #import scitools.numpyutils
8 from mpl_toolkits.axes_grid1 import make_axes_locatable
8 from mpl_toolkits.axes_grid1 import make_axes_locatable
9
9
10 from matplotlib.dates import DayLocator, HourLocator, MinuteLocator, SecondLocator, DateFormatter
10 from matplotlib.dates import DayLocator, HourLocator, MinuteLocator, SecondLocator, DateFormatter
11 from matplotlib.ticker import FuncFormatter
11 from matplotlib.ticker import FuncFormatter
12 from matplotlib.ticker import *
12 from matplotlib.ticker import *
13
13
14 ###########################################
14 ###########################################
15 #Actualizacion de las funciones del driver
15 #Actualizacion de las funciones del driver
16 ###########################################
16 ###########################################
17
17
18 def createFigure(idfigure, wintitle, width, height, facecolor="w"):
18 def createFigure(idfigure, wintitle, width, height, facecolor="w"):
19
19
20 matplotlib.pyplot.ioff()
20 matplotlib.pyplot.ioff()
21 fig = matplotlib.pyplot.figure(num=idfigure, facecolor=facecolor)
21 fig = matplotlib.pyplot.figure(num=idfigure, facecolor=facecolor)
22 fig.canvas.manager.set_window_title(wintitle)
22 fig.canvas.manager.set_window_title(wintitle)
23 fig.canvas.manager.resize(width, height)
23 fig.canvas.manager.resize(width, height)
24 matplotlib.pyplot.ion()
24 matplotlib.pyplot.ion()
25
25
26 return fig
26 return fig
27
27
28 def closeFigure():
28 def closeFigure():
29
29
30 matplotlib.pyplot.ioff()
30 matplotlib.pyplot.ioff()
31 matplotlib.pyplot.show()
31 matplotlib.pyplot.show()
32
32
33 return
33 return
34
34
35 def saveFigure(fig, filename):
35 def saveFigure(fig, filename):
36 fig.savefig(filename)
36 fig.savefig(filename)
37
37
38 def setWinTitle(fig, title):
38 def setWinTitle(fig, title):
39
39
40 fig.canvas.manager.set_window_title(title)
40 fig.canvas.manager.set_window_title(title)
41
41
42 def setTitle(fig, title):
42 def setTitle(fig, title):
43
43
44 fig.suptitle(title)
44 fig.suptitle(title)
45
45
46 def createAxes(fig, nrow, ncol, xpos, ypos, colspan, rowspan):
46 def createAxes(fig, nrow, ncol, xpos, ypos, colspan, rowspan):
47
47
48 matplotlib.pyplot.figure(fig.number)
48 matplotlib.pyplot.figure(fig.number)
49 axes = matplotlib.pyplot.subplot2grid((nrow, ncol),
49 axes = matplotlib.pyplot.subplot2grid((nrow, ncol),
50 (xpos, ypos),
50 (xpos, ypos),
51 colspan=colspan,
51 colspan=colspan,
52 rowspan=rowspan)
52 rowspan=rowspan)
53 return axes
53 return axes
54
54
55 def setAxesText(ax, text):
55 def setAxesText(ax, text):
56
56
57 ax.annotate(text,
57 ax.annotate(text,
58 xy = (.1, .99),
58 xy = (.1, .99),
59 xycoords = 'figure fraction',
59 xycoords = 'figure fraction',
60 horizontalalignment = 'left',
60 horizontalalignment = 'left',
61 verticalalignment = 'top',
61 verticalalignment = 'top',
62 fontsize = 10)
62 fontsize = 10)
63
63
64 def printLabels(ax, xlabel, ylabel, title):
64 def printLabels(ax, xlabel, ylabel, title):
65
65
66 ax.set_xlabel(xlabel, size=11)
66 ax.set_xlabel(xlabel, size=11)
67 ax.set_ylabel(ylabel, size=11)
67 ax.set_ylabel(ylabel, size=11)
68 ax.set_title(title, size=12)
68 ax.set_title(title, size=12)
69
69
70 def createPline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='',
70 def createPline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='',
71 ticksize=9, xtick_visible=True, ytick_visible=True,
71 ticksize=9, xtick_visible=True, ytick_visible=True,
72 nxticks=4, nyticks=10,
72 nxticks=4, nyticks=10,
73 grid=None):
73 grid=None):
74
74
75 """
75 """
76
76
77 Input:
77 Input:
78 grid : None, 'both', 'x', 'y'
78 grid : None, 'both', 'x', 'y'
79 """
79 """
80
80
81 ax.plot(x, y)
81 ax.plot(x, y)
82 ax.set_xlim([xmin,xmax])
82 ax.set_xlim([xmin,xmax])
83 ax.set_ylim([ymin,ymax])
83 ax.set_ylim([ymin,ymax])
84
84
85 printLabels(ax, xlabel, ylabel, title)
85 printLabels(ax, xlabel, ylabel, title)
86
86
87 ######################################################
87 ######################################################
88 if (xmax-xmin)<=1:
88 if (xmax-xmin)<=1:
89 xtickspos = numpy.linspace(xmin,xmax,nxticks)
89 xtickspos = numpy.linspace(xmin,xmax,nxticks)
90 xtickspos = numpy.array([float("%.1f"%i) for i in xtickspos])
90 xtickspos = numpy.array([float("%.1f"%i) for i in xtickspos])
91 ax.set_xticks(xtickspos)
91 ax.set_xticks(xtickspos)
92 else:
92 else:
93 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
93 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
94 ax.set_xticks(xtickspos)
94 ax.set_xticks(xtickspos)
95
95
96 for tick in ax.get_xticklabels():
96 for tick in ax.get_xticklabels():
97 tick.set_visible(xtick_visible)
97 tick.set_visible(xtick_visible)
98
98
99 for tick in ax.xaxis.get_major_ticks():
99 for tick in ax.xaxis.get_major_ticks():
100 tick.label.set_fontsize(ticksize)
100 tick.label.set_fontsize(ticksize)
101
101
102 ######################################################
102 ######################################################
103 for tick in ax.get_yticklabels():
103 for tick in ax.get_yticklabels():
104 tick.set_visible(ytick_visible)
104 tick.set_visible(ytick_visible)
105
105
106 for tick in ax.yaxis.get_major_ticks():
106 for tick in ax.yaxis.get_major_ticks():
107 tick.label.set_fontsize(ticksize)
107 tick.label.set_fontsize(ticksize)
108
108
109 iplot = ax.lines[-1]
109 iplot = ax.lines[-1]
110
110
111 ######################################################
111 ######################################################
112 if '0.' in matplotlib.__version__[0:2]:
112 if '0.' in matplotlib.__version__[0:2]:
113 print "The matplotlib version has to be updated to 1.1 or newer"
113 print "The matplotlib version has to be updated to 1.1 or newer"
114 return iplot
114 return iplot
115
115
116 if '1.0.' in matplotlib.__version__[0:4]:
116 if '1.0.' in matplotlib.__version__[0:4]:
117 print "The matplotlib version has to be updated to 1.1 or newer"
117 print "The matplotlib version has to be updated to 1.1 or newer"
118 return iplot
118 return iplot
119
119
120 if grid != None:
120 if grid != None:
121 ax.grid(b=True, which='major', axis=grid)
121 ax.grid(b=True, which='major', axis=grid)
122
122
123 matplotlib.pyplot.tight_layout()
123 matplotlib.pyplot.tight_layout()
124
124
125 return iplot
125 return iplot
126
126
127 def pline(iplot, x, y, xlabel='', ylabel='', title=''):
127 def pline(iplot, x, y, xlabel='', ylabel='', title=''):
128
128
129 ax = iplot.get_axes()
129 ax = iplot.get_axes()
130
130
131 printLabels(ax, xlabel, ylabel, title)
131 printLabels(ax, xlabel, ylabel, title)
132
132
133 iplot.set_data(x, y)
133 set_linedata(ax, x, y, idline=0)
134
135 def addpline(ax, x, y, color, linestyle, lw):
136 ax.plot(x,y,color=color,linestyle=linestyle,lw=lw)
137
138
139 def set_linedata(ax, x, y, idline):
140 ax.lines[idline].set_data(x,y)
134
141
135 def createPmultiline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
142 def createPmultiline(ax, x, y, xmin, xmax, ymin, ymax, xlabel='', ylabel='', title='', legendlabels=None,
136 ticksize=9, xtick_visible=True, ytick_visible=True,
143 ticksize=9, xtick_visible=True, ytick_visible=True,
137 nxticks=4, nyticks=10,
144 nxticks=4, nyticks=10,
138 grid=None):
145 grid=None):
139
146
140 """
147 """
141
148
142 Input:
149 Input:
143 grid : None, 'both', 'x', 'y'
150 grid : None, 'both', 'x', 'y'
144 """
151 """
145
152
146 lines = ax.plot(x.T, y)
153 lines = ax.plot(x.T, y)
147 leg = ax.legend(lines, legendlabels, loc='upper left')
154 leg = ax.legend(lines, legendlabels, loc='upper left')
148 leg.get_frame().set_alpha(0.5)
155 leg.get_frame().set_alpha(0.5)
149 ax.set_xlim([xmin,xmax])
156 ax.set_xlim([xmin,xmax])
150 ax.set_ylim([ymin,ymax])
157 ax.set_ylim([ymin,ymax])
151 printLabels(ax, xlabel, ylabel, title)
158 printLabels(ax, xlabel, ylabel, title)
152
159
153 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
160 xtickspos = numpy.arange(nxticks)*int((xmax-xmin)/(nxticks)) + int(xmin)
154 ax.set_xticks(xtickspos)
161 ax.set_xticks(xtickspos)
155
162
156 for tick in ax.get_xticklabels():
163 for tick in ax.get_xticklabels():
157 tick.set_visible(xtick_visible)
164 tick.set_visible(xtick_visible)
158
165
159 for tick in ax.xaxis.get_major_ticks():
166 for tick in ax.xaxis.get_major_ticks():
160 tick.label.set_fontsize(ticksize)
167 tick.label.set_fontsize(ticksize)
161
168
162 for tick in ax.get_yticklabels():
169 for tick in ax.get_yticklabels():
163 tick.set_visible(ytick_visible)
170 tick.set_visible(ytick_visible)
164
171
165 for tick in ax.yaxis.get_major_ticks():
172 for tick in ax.yaxis.get_major_ticks():
166 tick.label.set_fontsize(ticksize)
173 tick.label.set_fontsize(ticksize)
167
174
168 iplot = ax.lines[-1]
175 iplot = ax.lines[-1]
169
176
170 if '0.' in matplotlib.__version__[0:2]:
177 if '0.' in matplotlib.__version__[0:2]:
171 print "The matplotlib version has to be updated to 1.1 or newer"
178 print "The matplotlib version has to be updated to 1.1 or newer"
172 return iplot
179 return iplot
173
180
174 if '1.0.' in matplotlib.__version__[0:4]:
181 if '1.0.' in matplotlib.__version__[0:4]:
175 print "The matplotlib version has to be updated to 1.1 or newer"
182 print "The matplotlib version has to be updated to 1.1 or newer"
176 return iplot
183 return iplot
177
184
178 if grid != None:
185 if grid != None:
179 ax.grid(b=True, which='major', axis=grid)
186 ax.grid(b=True, which='major', axis=grid)
180
187
181 matplotlib.pyplot.tight_layout()
188 matplotlib.pyplot.tight_layout()
182
189
183 return iplot
190 return iplot
184
191
185
192
186 def pmultiline(iplot, x, y, xlabel='', ylabel='', title=''):
193 def pmultiline(iplot, x, y, xlabel='', ylabel='', title=''):
187
194
188 ax = iplot.get_axes()
195 ax = iplot.get_axes()
189
196
190 printLabels(ax, xlabel, ylabel, title)
197 printLabels(ax, xlabel, ylabel, title)
191
198
192 for i in range(len(ax.lines)):
199 for i in range(len(ax.lines)):
193 line = ax.lines[i]
200 line = ax.lines[i]
194 line.set_data(x[i,:],y)
201 line.set_data(x[i,:],y)
195
202
196 def createPcolor(ax, x, y, z, xmin, xmax, ymin, ymax, zmin, zmax,
203 def createPcolor(ax, x, y, z, xmin, xmax, ymin, ymax, zmin, zmax,
197 xlabel='', ylabel='', title='', ticksize = 9,
204 xlabel='', ylabel='', title='', ticksize = 9,
198 colormap='jet',cblabel='', cbsize="5%",
205 colormap='jet',cblabel='', cbsize="5%",
199 XAxisAsTime=False):
206 XAxisAsTime=False):
200
207
201 divider = make_axes_locatable(ax)
208 divider = make_axes_locatable(ax)
202 ax_cb = divider.new_horizontal(size=cbsize, pad=0.05)
209 ax_cb = divider.new_horizontal(size=cbsize, pad=0.05)
203 fig = ax.get_figure()
210 fig = ax.get_figure()
204 fig.add_axes(ax_cb)
211 fig.add_axes(ax_cb)
205
212
206 ax.set_xlim([xmin,xmax])
213 ax.set_xlim([xmin,xmax])
207 ax.set_ylim([ymin,ymax])
214 ax.set_ylim([ymin,ymax])
208
215
209 printLabels(ax, xlabel, ylabel, title)
216 printLabels(ax, xlabel, ylabel, title)
210
217
211 imesh = ax.pcolormesh(x,y,z.T, vmin=zmin, vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
218 imesh = ax.pcolormesh(x,y,z.T, vmin=zmin, vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
212 cb = matplotlib.pyplot.colorbar(imesh, cax=ax_cb)
219 cb = matplotlib.pyplot.colorbar(imesh, cax=ax_cb)
213 cb.set_label(cblabel)
220 cb.set_label(cblabel)
214
221
215 # for tl in ax_cb.get_yticklabels():
222 # for tl in ax_cb.get_yticklabels():
216 # tl.set_visible(True)
223 # tl.set_visible(True)
217
224
218 for tick in ax.yaxis.get_major_ticks():
225 for tick in ax.yaxis.get_major_ticks():
219 tick.label.set_fontsize(ticksize)
226 tick.label.set_fontsize(ticksize)
220
227
221 for tick in ax.xaxis.get_major_ticks():
228 for tick in ax.xaxis.get_major_ticks():
222 tick.label.set_fontsize(ticksize)
229 tick.label.set_fontsize(ticksize)
223
230
224 for tick in cb.ax.get_yticklabels():
231 for tick in cb.ax.get_yticklabels():
225 tick.set_fontsize(ticksize)
232 tick.set_fontsize(ticksize)
226
233
227 ax_cb.yaxis.tick_right()
234 ax_cb.yaxis.tick_right()
228
235
229 if '0.' in matplotlib.__version__[0:2]:
236 if '0.' in matplotlib.__version__[0:2]:
230 print "The matplotlib version has to be updated to 1.1 or newer"
237 print "The matplotlib version has to be updated to 1.1 or newer"
231 return imesh
238 return imesh
232
239
233 if '1.0.' in matplotlib.__version__[0:4]:
240 if '1.0.' in matplotlib.__version__[0:4]:
234 print "The matplotlib version has to be updated to 1.1 or newer"
241 print "The matplotlib version has to be updated to 1.1 or newer"
235 return imesh
242 return imesh
236
243
237 matplotlib.pyplot.tight_layout()
244 matplotlib.pyplot.tight_layout()
238
245
239 if XAxisAsTime:
246 if XAxisAsTime:
240
247
241 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
248 func = lambda x, pos: ('%s') %(datetime.datetime.utcfromtimestamp(x).strftime("%H:%M:%S"))
242 ax.xaxis.set_major_formatter(FuncFormatter(func))
249 ax.xaxis.set_major_formatter(FuncFormatter(func))
243 ax.xaxis.set_major_locator(LinearLocator(7))
250 ax.xaxis.set_major_locator(LinearLocator(7))
244
251
245 return imesh
252 return imesh
246
253
247 def pcolor(imesh, z, xlabel='', ylabel='', title=''):
254 def pcolor(imesh, z, xlabel='', ylabel='', title=''):
248
255
249 z = z.T
256 z = z.T
250
257
251 ax = imesh.get_axes()
258 ax = imesh.get_axes()
252
259
253 printLabels(ax, xlabel, ylabel, title)
260 printLabels(ax, xlabel, ylabel, title)
254
261
255 imesh.set_array(z.ravel())
262 imesh.set_array(z.ravel())
256
263
257 def addpcolor(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
264 def addpcolor(ax, x, y, z, zmin, zmax, xlabel='', ylabel='', title='', colormap='jet'):
258
265
259 printLabels(ax, xlabel, ylabel, title)
266 printLabels(ax, xlabel, ylabel, title)
260
267
261 imesh = ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
268 imesh = ax.pcolormesh(x,y,z.T,vmin=zmin,vmax=zmax, cmap=matplotlib.pyplot.get_cmap(colormap))
262
269
263 def draw(fig):
270 def draw(fig):
264
271
265 if type(fig) == 'int':
272 if type(fig) == 'int':
266 raise ValueError, "This parameter should be of tpye matplotlib figure"
273 raise ValueError, "This parameter should be of tpye matplotlib figure"
267
274
268 fig.canvas.draw() No newline at end of file
275 fig.canvas.draw()
@@ -1,983 +1,986
1 import numpy
1 import numpy
2 import time, datetime
2 import time, datetime
3 from graphics.figure import *
3 from graphics.figure import *
4
4
5 class CrossSpectraPlot(Figure):
5 class CrossSpectraPlot(Figure):
6
6
7 __isConfig = None
7 __isConfig = None
8 __nsubplots = None
8 __nsubplots = None
9
9
10 WIDTH = None
10 WIDTH = None
11 HEIGHT = None
11 HEIGHT = None
12 WIDTHPROF = None
12 WIDTHPROF = None
13 HEIGHTPROF = None
13 HEIGHTPROF = None
14 PREFIX = 'cspc'
14 PREFIX = 'cspc'
15
15
16 def __init__(self):
16 def __init__(self):
17
17
18 self.__isConfig = False
18 self.__isConfig = False
19 self.__nsubplots = 4
19 self.__nsubplots = 4
20
20
21 self.WIDTH = 250
21 self.WIDTH = 250
22 self.HEIGHT = 250
22 self.HEIGHT = 250
23 self.WIDTHPROF = 0
23 self.WIDTHPROF = 0
24 self.HEIGHTPROF = 0
24 self.HEIGHTPROF = 0
25
25
26 def getSubplots(self):
26 def getSubplots(self):
27
27
28 ncol = 4
28 ncol = 4
29 nrow = self.nplots
29 nrow = self.nplots
30
30
31 return nrow, ncol
31 return nrow, ncol
32
32
33 def setup(self, idfigure, nplots, wintitle, showprofile=True):
33 def setup(self, idfigure, nplots, wintitle, showprofile=True):
34
34
35 self.__showprofile = showprofile
35 self.__showprofile = showprofile
36 self.nplots = nplots
36 self.nplots = nplots
37
37
38 ncolspan = 1
38 ncolspan = 1
39 colspan = 1
39 colspan = 1
40
40
41 self.createFigure(idfigure = idfigure,
41 self.createFigure(idfigure = idfigure,
42 wintitle = wintitle,
42 wintitle = wintitle,
43 widthplot = self.WIDTH + self.WIDTHPROF,
43 widthplot = self.WIDTH + self.WIDTHPROF,
44 heightplot = self.HEIGHT + self.HEIGHTPROF)
44 heightplot = self.HEIGHT + self.HEIGHTPROF)
45
45
46 nrow, ncol = self.getSubplots()
46 nrow, ncol = self.getSubplots()
47
47
48 counter = 0
48 counter = 0
49 for y in range(nrow):
49 for y in range(nrow):
50 for x in range(ncol):
50 for x in range(ncol):
51 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
51 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
52
52
53 counter += 1
53 counter += 1
54
54
55 def run(self, dataOut, idfigure, wintitle="", pairsList=None, showprofile='True',
55 def run(self, dataOut, idfigure, wintitle="", pairsList=None, showprofile='True',
56 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
56 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
57 save=False, figpath='./', figfile=None):
57 save=False, figpath='./', figfile=None):
58
58
59 """
59 """
60
60
61 Input:
61 Input:
62 dataOut :
62 dataOut :
63 idfigure :
63 idfigure :
64 wintitle :
64 wintitle :
65 channelList :
65 channelList :
66 showProfile :
66 showProfile :
67 xmin : None,
67 xmin : None,
68 xmax : None,
68 xmax : None,
69 ymin : None,
69 ymin : None,
70 ymax : None,
70 ymax : None,
71 zmin : None,
71 zmin : None,
72 zmax : None
72 zmax : None
73 """
73 """
74
74
75 if pairsList == None:
75 if pairsList == None:
76 pairsIndexList = dataOut.pairsIndexList
76 pairsIndexList = dataOut.pairsIndexList
77 else:
77 else:
78 pairsIndexList = []
78 pairsIndexList = []
79 for pair in pairsList:
79 for pair in pairsList:
80 if pair not in dataOut.pairsList:
80 if pair not in dataOut.pairsList:
81 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
81 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
82 pairsIndexList.append(dataOut.pairsList.index(pair))
82 pairsIndexList.append(dataOut.pairsList.index(pair))
83
83
84 if pairsIndexList == []:
84 if pairsIndexList == []:
85 return
85 return
86
86
87 if len(pairsIndexList) > 4:
87 if len(pairsIndexList) > 4:
88 pairsIndexList = pairsIndexList[0:4]
88 pairsIndexList = pairsIndexList[0:4]
89
89
90 x = dataOut.getVelRange(1)
90 x = dataOut.getVelRange(1)
91 y = dataOut.getHeiRange()
91 y = dataOut.getHeiRange()
92 z = 10.*numpy.log10(dataOut.data_spc[:,:,:])
92 z = 10.*numpy.log10(dataOut.data_spc[:,:,:])
93 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
93 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
94 avg = numpy.average(numpy.abs(z), axis=1)
94 avg = numpy.average(numpy.abs(z), axis=1)
95
95
96 noise = dataOut.getNoise()
96 noise = dataOut.getNoise()
97
97
98 thisDatetime = dataOut.datatime
98 thisDatetime = dataOut.datatime
99 title = "Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
99 title = "Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
100 xlabel = "Velocity (m/s)"
100 xlabel = "Velocity (m/s)"
101 ylabel = "Range (Km)"
101 ylabel = "Range (Km)"
102
102
103 if not self.__isConfig:
103 if not self.__isConfig:
104
104
105 nplots = len(pairsIndexList)
105 nplots = len(pairsIndexList)
106
106
107 self.setup(idfigure=idfigure,
107 self.setup(idfigure=idfigure,
108 nplots=nplots,
108 nplots=nplots,
109 wintitle=wintitle,
109 wintitle=wintitle,
110 showprofile=showprofile)
110 showprofile=showprofile)
111
111
112 if xmin == None: xmin = numpy.nanmin(x)
112 if xmin == None: xmin = numpy.nanmin(x)
113 if xmax == None: xmax = numpy.nanmax(x)
113 if xmax == None: xmax = numpy.nanmax(x)
114 if ymin == None: ymin = numpy.nanmin(y)
114 if ymin == None: ymin = numpy.nanmin(y)
115 if ymax == None: ymax = numpy.nanmax(y)
115 if ymax == None: ymax = numpy.nanmax(y)
116 if zmin == None: zmin = numpy.nanmin(avg)*0.9
116 if zmin == None: zmin = numpy.nanmin(avg)*0.9
117 if zmax == None: zmax = numpy.nanmax(avg)*0.9
117 if zmax == None: zmax = numpy.nanmax(avg)*0.9
118
118
119 self.__isConfig = True
119 self.__isConfig = True
120
120
121 self.setWinTitle(title)
121 self.setWinTitle(title)
122
122
123 for i in range(self.nplots):
123 for i in range(self.nplots):
124 pair = dataOut.pairsList[pairsIndexList[i]]
124 pair = dataOut.pairsList[pairsIndexList[i]]
125
125
126 title = "Channel %d: %4.2fdB" %(pair[0], noise[pair[0]])
126 title = "Channel %d: %4.2fdB" %(pair[0], noise[pair[0]])
127 z = 10.*numpy.log10(dataOut.data_spc[pair[0],:,:])
127 z = 10.*numpy.log10(dataOut.data_spc[pair[0],:,:])
128 axes0 = self.axesList[i*self.__nsubplots]
128 axes0 = self.axesList[i*self.__nsubplots]
129 axes0.pcolor(x, y, z,
129 axes0.pcolor(x, y, z,
130 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
130 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
131 xlabel=xlabel, ylabel=ylabel, title=title,
131 xlabel=xlabel, ylabel=ylabel, title=title,
132 ticksize=9, cblabel='')
132 ticksize=9, cblabel='')
133
133
134 title = "Channel %d: %4.2fdB" %(pair[1], noise[pair[1]])
134 title = "Channel %d: %4.2fdB" %(pair[1], noise[pair[1]])
135 z = 10.*numpy.log10(dataOut.data_spc[pair[1],:,:])
135 z = 10.*numpy.log10(dataOut.data_spc[pair[1],:,:])
136 axes0 = self.axesList[i*self.__nsubplots+1]
136 axes0 = self.axesList[i*self.__nsubplots+1]
137 axes0.pcolor(x, y, z,
137 axes0.pcolor(x, y, z,
138 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
138 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
139 xlabel=xlabel, ylabel=ylabel, title=title,
139 xlabel=xlabel, ylabel=ylabel, title=title,
140 ticksize=9, cblabel='')
140 ticksize=9, cblabel='')
141
141
142 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[pair[0],:,:]*dataOut.data_spc[pair[1],:,:])
142 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[pair[0],:,:]*dataOut.data_spc[pair[1],:,:])
143 coherence = numpy.abs(coherenceComplex)
143 coherence = numpy.abs(coherenceComplex)
144 phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
144 phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
145
145
146
146
147 title = "Coherence %d%d" %(pair[0], pair[1])
147 title = "Coherence %d%d" %(pair[0], pair[1])
148 axes0 = self.axesList[i*self.__nsubplots+2]
148 axes0 = self.axesList[i*self.__nsubplots+2]
149 axes0.pcolor(x, y, coherence,
149 axes0.pcolor(x, y, coherence,
150 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=0, zmax=1,
150 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=0, zmax=1,
151 xlabel=xlabel, ylabel=ylabel, title=title,
151 xlabel=xlabel, ylabel=ylabel, title=title,
152 ticksize=9, cblabel='')
152 ticksize=9, cblabel='')
153
153
154 title = "Phase %d%d" %(pair[0], pair[1])
154 title = "Phase %d%d" %(pair[0], pair[1])
155 axes0 = self.axesList[i*self.__nsubplots+3]
155 axes0 = self.axesList[i*self.__nsubplots+3]
156 axes0.pcolor(x, y, phase,
156 axes0.pcolor(x, y, phase,
157 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=-180, zmax=180,
157 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=-180, zmax=180,
158 xlabel=xlabel, ylabel=ylabel, title=title,
158 xlabel=xlabel, ylabel=ylabel, title=title,
159 ticksize=9, cblabel='', colormap='RdBu_r')
159 ticksize=9, cblabel='', colormap='RdBu_r')
160
160
161
161
162
162
163 self.draw()
163 self.draw()
164
164
165 if save:
165 if save:
166 date = thisDatetime.strftime("%Y%m%d_%H%M%S")
166 date = thisDatetime.strftime("%Y%m%d_%H%M%S")
167 if figfile == None:
167 if figfile == None:
168 figfile = self.getFilename(name = date)
168 figfile = self.getFilename(name = date)
169
169
170 self.saveFigure(figpath, figfile)
170 self.saveFigure(figpath, figfile)
171
171
172
172
173 class RTIPlot(Figure):
173 class RTIPlot(Figure):
174
174
175 __isConfig = None
175 __isConfig = None
176 __nsubplots = None
176 __nsubplots = None
177
177
178 WIDTHPROF = None
178 WIDTHPROF = None
179 HEIGHTPROF = None
179 HEIGHTPROF = None
180 PREFIX = 'rti'
180 PREFIX = 'rti'
181
181
182 def __init__(self):
182 def __init__(self):
183
183
184 self.timerange = 2*60*60
184 self.timerange = 2*60*60
185 self.__isConfig = False
185 self.__isConfig = False
186 self.__nsubplots = 1
186 self.__nsubplots = 1
187
187
188 self.WIDTH = 800
188 self.WIDTH = 800
189 self.HEIGHT = 200
189 self.HEIGHT = 200
190 self.WIDTHPROF = 120
190 self.WIDTHPROF = 120
191 self.HEIGHTPROF = 0
191 self.HEIGHTPROF = 0
192
192
193 def getSubplots(self):
193 def getSubplots(self):
194
194
195 ncol = 1
195 ncol = 1
196 nrow = self.nplots
196 nrow = self.nplots
197
197
198 return nrow, ncol
198 return nrow, ncol
199
199
200 def setup(self, idfigure, nplots, wintitle, showprofile=True):
200 def setup(self, idfigure, nplots, wintitle, showprofile=True):
201
201
202 self.__showprofile = showprofile
202 self.__showprofile = showprofile
203 self.nplots = nplots
203 self.nplots = nplots
204
204
205 ncolspan = 1
205 ncolspan = 1
206 colspan = 1
206 colspan = 1
207 if showprofile:
207 if showprofile:
208 ncolspan = 7
208 ncolspan = 7
209 colspan = 6
209 colspan = 6
210 self.__nsubplots = 2
210 self.__nsubplots = 2
211
211
212 self.createFigure(idfigure = idfigure,
212 self.createFigure(idfigure = idfigure,
213 wintitle = wintitle,
213 wintitle = wintitle,
214 widthplot = self.WIDTH + self.WIDTHPROF,
214 widthplot = self.WIDTH + self.WIDTHPROF,
215 heightplot = self.HEIGHT + self.HEIGHTPROF)
215 heightplot = self.HEIGHT + self.HEIGHTPROF)
216
216
217 nrow, ncol = self.getSubplots()
217 nrow, ncol = self.getSubplots()
218
218
219 counter = 0
219 counter = 0
220 for y in range(nrow):
220 for y in range(nrow):
221 for x in range(ncol):
221 for x in range(ncol):
222
222
223 if counter >= self.nplots:
223 if counter >= self.nplots:
224 break
224 break
225
225
226 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
226 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
227
227
228 if showprofile:
228 if showprofile:
229 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
229 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
230
230
231 counter += 1
231 counter += 1
232
232
233 def run(self, dataOut, idfigure, wintitle="", channelList=None, showprofile='True',
233 def run(self, dataOut, idfigure, wintitle="", channelList=None, showprofile='True',
234 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
234 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
235 timerange=None,
235 timerange=None,
236 save=False, figpath='./', figfile=None):
236 save=False, figpath='./', figfile=None):
237
237
238 """
238 """
239
239
240 Input:
240 Input:
241 dataOut :
241 dataOut :
242 idfigure :
242 idfigure :
243 wintitle :
243 wintitle :
244 channelList :
244 channelList :
245 showProfile :
245 showProfile :
246 xmin : None,
246 xmin : None,
247 xmax : None,
247 xmax : None,
248 ymin : None,
248 ymin : None,
249 ymax : None,
249 ymax : None,
250 zmin : None,
250 zmin : None,
251 zmax : None
251 zmax : None
252 """
252 """
253
253
254 if channelList == None:
254 if channelList == None:
255 channelIndexList = dataOut.channelIndexList
255 channelIndexList = dataOut.channelIndexList
256 else:
256 else:
257 channelIndexList = []
257 channelIndexList = []
258 for channel in channelList:
258 for channel in channelList:
259 if channel not in dataOut.channelList:
259 if channel not in dataOut.channelList:
260 raise ValueError, "Channel %d is not in dataOut.channelList"
260 raise ValueError, "Channel %d is not in dataOut.channelList"
261 channelIndexList.append(dataOut.channelList.index(channel))
261 channelIndexList.append(dataOut.channelList.index(channel))
262
262
263 if timerange != None:
263 if timerange != None:
264 self.timerange = timerange
264 self.timerange = timerange
265
265
266 tmin = None
266 tmin = None
267 tmax = None
267 tmax = None
268 x = dataOut.getTimeRange()
268 x = dataOut.getTimeRange()
269 y = dataOut.getHeiRange()
269 y = dataOut.getHeiRange()
270 z = 10.*numpy.log10(dataOut.data_spc[channelIndexList,:,:])
270 z = 10.*numpy.log10(dataOut.data_spc[channelIndexList,:,:])
271 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
271 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
272 avg = numpy.average(z, axis=1)
272 avg = numpy.average(z, axis=1)
273
273
274 noise = dataOut.getNoise()
274 noise = dataOut.getNoise()
275
275
276 thisDatetime = dataOut.datatime
276 thisDatetime = dataOut.datatime
277 title = "RTI: %s" %(thisDatetime.strftime("%d-%b-%Y"))
277 title = "RTI: %s" %(thisDatetime.strftime("%d-%b-%Y"))
278 xlabel = "Velocity (m/s)"
278 xlabel = "Velocity (m/s)"
279 ylabel = "Range (Km)"
279 ylabel = "Range (Km)"
280
280
281 if not self.__isConfig:
281 if not self.__isConfig:
282
282
283 nplots = len(channelIndexList)
283 nplots = len(channelIndexList)
284
284
285 self.setup(idfigure=idfigure,
285 self.setup(idfigure=idfigure,
286 nplots=nplots,
286 nplots=nplots,
287 wintitle=wintitle,
287 wintitle=wintitle,
288 showprofile=showprofile)
288 showprofile=showprofile)
289
289
290 tmin, tmax = self.getTimeLim(x, xmin, xmax)
290 tmin, tmax = self.getTimeLim(x, xmin, xmax)
291 if ymin == None: ymin = numpy.nanmin(y)
291 if ymin == None: ymin = numpy.nanmin(y)
292 if ymax == None: ymax = numpy.nanmax(y)
292 if ymax == None: ymax = numpy.nanmax(y)
293 if zmin == None: zmin = numpy.nanmin(avg)*0.9
293 if zmin == None: zmin = numpy.nanmin(avg)*0.9
294 if zmax == None: zmax = numpy.nanmax(avg)*0.9
294 if zmax == None: zmax = numpy.nanmax(avg)*0.9
295
295
296 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
296 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
297 self.__isConfig = True
297 self.__isConfig = True
298
298
299
299
300 self.setWinTitle(title)
300 self.setWinTitle(title)
301
301
302 for i in range(self.nplots):
302 for i in range(self.nplots):
303 title = "Channel %d: %s" %(dataOut.channelList[i], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
303 title = "Channel %d: %s" %(dataOut.channelList[i], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
304 axes = self.axesList[i*self.__nsubplots]
304 axes = self.axesList[i*self.__nsubplots]
305 z = avg[i].reshape((1,-1))
305 z = avg[i].reshape((1,-1))
306 axes.pcolor(x, y, z,
306 axes.pcolor(x, y, z,
307 xmin=tmin, xmax=tmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
307 xmin=tmin, xmax=tmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
308 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
308 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
309 ticksize=9, cblabel='', cbsize="1%")
309 ticksize=9, cblabel='', cbsize="1%")
310
310
311 if self.__showprofile:
311 if self.__showprofile:
312 axes = self.axesList[i*self.__nsubplots +1]
312 axes = self.axesList[i*self.__nsubplots +1]
313 axes.pline(avg[i], y,
313 axes.pline(avg[i], y,
314 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
314 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
315 xlabel='dB', ylabel='', title='',
315 xlabel='dB', ylabel='', title='',
316 ytick_visible=False,
316 ytick_visible=False,
317 grid='x')
317 grid='x')
318
318
319 self.draw()
319 self.draw()
320
320
321 if save:
321 if save:
322
322
323 if figfile == None:
323 if figfile == None:
324 figfile = self.getFilename(name = self.name)
324 figfile = self.getFilename(name = self.name)
325
325
326 self.saveFigure(figpath, figfile)
326 self.saveFigure(figpath, figfile)
327
327
328 if x[1] + (x[1]-x[0]) >= self.axesList[0].xmax:
328 if x[1] + (x[1]-x[0]) >= self.axesList[0].xmax:
329 self.__isConfig = False
329 self.__isConfig = False
330
330
331 class SpectraPlot(Figure):
331 class SpectraPlot(Figure):
332
332
333 __isConfig = None
333 __isConfig = None
334 __nsubplots = None
334 __nsubplots = None
335
335
336 WIDTHPROF = None
336 WIDTHPROF = None
337 HEIGHTPROF = None
337 HEIGHTPROF = None
338 PREFIX = 'spc'
338 PREFIX = 'spc'
339
339
340 def __init__(self):
340 def __init__(self):
341
341
342 self.__isConfig = False
342 self.__isConfig = False
343 self.__nsubplots = 1
343 self.__nsubplots = 1
344
344
345 self.WIDTH = 230
345 self.WIDTH = 230
346 self.HEIGHT = 250
346 self.HEIGHT = 250
347 self.WIDTHPROF = 120
347 self.WIDTHPROF = 120
348 self.HEIGHTPROF = 0
348 self.HEIGHTPROF = 0
349
349
350 def getSubplots(self):
350 def getSubplots(self):
351
351
352 ncol = int(numpy.sqrt(self.nplots)+0.9)
352 ncol = int(numpy.sqrt(self.nplots)+0.9)
353 nrow = int(self.nplots*1./ncol + 0.9)
353 nrow = int(self.nplots*1./ncol + 0.9)
354
354
355 return nrow, ncol
355 return nrow, ncol
356
356
357 def setup(self, idfigure, nplots, wintitle, showprofile=True):
357 def setup(self, idfigure, nplots, wintitle, showprofile=True):
358
358
359 self.__showprofile = showprofile
359 self.__showprofile = showprofile
360 self.nplots = nplots
360 self.nplots = nplots
361
361
362 ncolspan = 1
362 ncolspan = 1
363 colspan = 1
363 colspan = 1
364 if showprofile:
364 if showprofile:
365 ncolspan = 3
365 ncolspan = 3
366 colspan = 2
366 colspan = 2
367 self.__nsubplots = 2
367 self.__nsubplots = 2
368
368
369 self.createFigure(idfigure = idfigure,
369 self.createFigure(idfigure = idfigure,
370 wintitle = wintitle,
370 wintitle = wintitle,
371 widthplot = self.WIDTH + self.WIDTHPROF,
371 widthplot = self.WIDTH + self.WIDTHPROF,
372 heightplot = self.HEIGHT + self.HEIGHTPROF)
372 heightplot = self.HEIGHT + self.HEIGHTPROF)
373
373
374 nrow, ncol = self.getSubplots()
374 nrow, ncol = self.getSubplots()
375
375
376 counter = 0
376 counter = 0
377 for y in range(nrow):
377 for y in range(nrow):
378 for x in range(ncol):
378 for x in range(ncol):
379
379
380 if counter >= self.nplots:
380 if counter >= self.nplots:
381 break
381 break
382
382
383 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
383 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
384
384
385 if showprofile:
385 if showprofile:
386 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
386 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
387
387
388 counter += 1
388 counter += 1
389
389
390 def run(self, dataOut, idfigure, wintitle="", channelList=None, showprofile='True',
390 def run(self, dataOut, idfigure, wintitle="", channelList=None, showprofile='True',
391 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
391 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
392 save=False, figpath='./', figfile=None):
392 save=False, figpath='./', figfile=None):
393
393
394 """
394 """
395
395
396 Input:
396 Input:
397 dataOut :
397 dataOut :
398 idfigure :
398 idfigure :
399 wintitle :
399 wintitle :
400 channelList :
400 channelList :
401 showProfile :
401 showProfile :
402 xmin : None,
402 xmin : None,
403 xmax : None,
403 xmax : None,
404 ymin : None,
404 ymin : None,
405 ymax : None,
405 ymax : None,
406 zmin : None,
406 zmin : None,
407 zmax : None
407 zmax : None
408 """
408 """
409
409
410 if channelList == None:
410 if channelList == None:
411 channelIndexList = dataOut.channelIndexList
411 channelIndexList = dataOut.channelIndexList
412 else:
412 else:
413 channelIndexList = []
413 channelIndexList = []
414 for channel in channelList:
414 for channel in channelList:
415 if channel not in dataOut.channelList:
415 if channel not in dataOut.channelList:
416 raise ValueError, "Channel %d is not in dataOut.channelList"
416 raise ValueError, "Channel %d is not in dataOut.channelList"
417 channelIndexList.append(dataOut.channelList.index(channel))
417 channelIndexList.append(dataOut.channelList.index(channel))
418
418
419 x = dataOut.getVelRange(1)
419 x = dataOut.getVelRange(1)
420 y = dataOut.getHeiRange()
420 y = dataOut.getHeiRange()
421
421
422 z = 10.*numpy.log10(dataOut.data_spc[channelIndexList,:,:])
422 z = 10.*numpy.log10(dataOut.data_spc[channelIndexList,:,:])
423 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
423 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
424 avg = numpy.average(z, axis=1)
424 avg = numpy.average(z, axis=1)
425
425
426 noise = dataOut.getNoise()
426 noise = dataOut.getNoise()
427
427
428 thisDatetime = dataOut.datatime
428 thisDatetime = dataOut.datatime
429 title = "Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
429 title = "Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
430 xlabel = "Velocity (m/s)"
430 xlabel = "Velocity (m/s)"
431 ylabel = "Range (Km)"
431 ylabel = "Range (Km)"
432
432
433 if not self.__isConfig:
433 if not self.__isConfig:
434
434
435 nplots = len(channelIndexList)
435 nplots = len(channelIndexList)
436
436
437 self.setup(idfigure=idfigure,
437 self.setup(idfigure=idfigure,
438 nplots=nplots,
438 nplots=nplots,
439 wintitle=wintitle,
439 wintitle=wintitle,
440 showprofile=showprofile)
440 showprofile=showprofile)
441
441
442 if xmin == None: xmin = numpy.nanmin(x)
442 if xmin == None: xmin = numpy.nanmin(x)
443 if xmax == None: xmax = numpy.nanmax(x)
443 if xmax == None: xmax = numpy.nanmax(x)
444 if ymin == None: ymin = numpy.nanmin(y)
444 if ymin == None: ymin = numpy.nanmin(y)
445 if ymax == None: ymax = numpy.nanmax(y)
445 if ymax == None: ymax = numpy.nanmax(y)
446 if zmin == None: zmin = numpy.nanmin(avg)*0.9
446 if zmin == None: zmin = numpy.nanmin(avg)*0.9
447 if zmax == None: zmax = numpy.nanmax(avg)*0.9
447 if zmax == None: zmax = numpy.nanmax(avg)*0.9
448
448
449 self.__isConfig = True
449 self.__isConfig = True
450
450
451 self.setWinTitle(title)
451 self.setWinTitle(title)
452
452
453 for i in range(self.nplots):
453 for i in range(self.nplots):
454 title = "Channel %d: %4.2fdB" %(dataOut.channelList[i], noise[i])
454 title = "Channel %d: %4.2fdB" %(dataOut.channelList[i], noise[i])
455 axes = self.axesList[i*self.__nsubplots]
455 axes = self.axesList[i*self.__nsubplots]
456 axes.pcolor(x, y, z[i,:,:],
456 axes.pcolor(x, y, z[i,:,:],
457 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
457 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
458 xlabel=xlabel, ylabel=ylabel, title=title,
458 xlabel=xlabel, ylabel=ylabel, title=title,
459 ticksize=9, cblabel='')
459 ticksize=9, cblabel='')
460
460
461 if self.__showprofile:
461 if self.__showprofile:
462 axes = self.axesList[i*self.__nsubplots +1]
462 axes = self.axesList[i*self.__nsubplots +1]
463 axes.pline(avg[i], y,
463 axes.pline(avg[i], y,
464 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
464 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
465 xlabel='dB', ylabel='', title='',
465 xlabel='dB', ylabel='', title='',
466 ytick_visible=False,
466 ytick_visible=False,
467 grid='x')
467 grid='x')
468
469 noiseline = numpy.repeat(noise[i], len(y))
470 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
468
471
469 self.draw()
472 self.draw()
470
473
471 if save:
474 if save:
472 date = thisDatetime.strftime("%Y%m%d_%H%M%S")
475 date = thisDatetime.strftime("%Y%m%d_%H%M%S")
473 if figfile == None:
476 if figfile == None:
474 figfile = self.getFilename(name = date)
477 figfile = self.getFilename(name = date)
475
478
476 self.saveFigure(figpath, figfile)
479 self.saveFigure(figpath, figfile)
477
480
478 class Scope(Figure):
481 class Scope(Figure):
479
482
480 __isConfig = None
483 __isConfig = None
481
484
482 def __init__(self):
485 def __init__(self):
483
486
484 self.__isConfig = False
487 self.__isConfig = False
485 self.WIDTH = 600
488 self.WIDTH = 600
486 self.HEIGHT = 200
489 self.HEIGHT = 200
487
490
488 def getSubplots(self):
491 def getSubplots(self):
489
492
490 nrow = self.nplots
493 nrow = self.nplots
491 ncol = 3
494 ncol = 3
492 return nrow, ncol
495 return nrow, ncol
493
496
494 def setup(self, idfigure, nplots, wintitle):
497 def setup(self, idfigure, nplots, wintitle):
495
498
496 self.nplots = nplots
499 self.nplots = nplots
497
500
498 self.createFigure(idfigure, wintitle)
501 self.createFigure(idfigure, wintitle)
499
502
500 nrow,ncol = self.getSubplots()
503 nrow,ncol = self.getSubplots()
501 colspan = 3
504 colspan = 3
502 rowspan = 1
505 rowspan = 1
503
506
504 for i in range(nplots):
507 for i in range(nplots):
505 self.addAxes(nrow, ncol, i, 0, colspan, rowspan)
508 self.addAxes(nrow, ncol, i, 0, colspan, rowspan)
506
509
507
510
508
511
509 def run(self, dataOut, idfigure, wintitle="", channelList=None,
512 def run(self, dataOut, idfigure, wintitle="", channelList=None,
510 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
513 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
511 figpath='./', figfile=None):
514 figpath='./', figfile=None):
512
515
513 """
516 """
514
517
515 Input:
518 Input:
516 dataOut :
519 dataOut :
517 idfigure :
520 idfigure :
518 wintitle :
521 wintitle :
519 channelList :
522 channelList :
520 xmin : None,
523 xmin : None,
521 xmax : None,
524 xmax : None,
522 ymin : None,
525 ymin : None,
523 ymax : None,
526 ymax : None,
524 """
527 """
525
528
526 if channelList == None:
529 if channelList == None:
527 channelIndexList = dataOut.channelIndexList
530 channelIndexList = dataOut.channelIndexList
528 else:
531 else:
529 channelIndexList = []
532 channelIndexList = []
530 for channel in channelList:
533 for channel in channelList:
531 if channel not in dataOut.channelList:
534 if channel not in dataOut.channelList:
532 raise ValueError, "Channel %d is not in dataOut.channelList"
535 raise ValueError, "Channel %d is not in dataOut.channelList"
533 channelIndexList.append(dataOut.channelList.index(channel))
536 channelIndexList.append(dataOut.channelList.index(channel))
534
537
535 x = dataOut.heightList
538 x = dataOut.heightList
536 y = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
539 y = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
537 y = y.real
540 y = y.real
538
541
539 thisDatetime = dataOut.datatime
542 thisDatetime = dataOut.datatime
540 title = "Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
543 title = "Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
541 xlabel = "Range (Km)"
544 xlabel = "Range (Km)"
542 ylabel = "Intensity"
545 ylabel = "Intensity"
543
546
544 if not self.__isConfig:
547 if not self.__isConfig:
545 nplots = len(channelIndexList)
548 nplots = len(channelIndexList)
546
549
547 self.setup(idfigure=idfigure,
550 self.setup(idfigure=idfigure,
548 nplots=nplots,
551 nplots=nplots,
549 wintitle=wintitle)
552 wintitle=wintitle)
550
553
551 if xmin == None: xmin = numpy.nanmin(x)
554 if xmin == None: xmin = numpy.nanmin(x)
552 if xmax == None: xmax = numpy.nanmax(x)
555 if xmax == None: xmax = numpy.nanmax(x)
553 if ymin == None: ymin = numpy.nanmin(y)
556 if ymin == None: ymin = numpy.nanmin(y)
554 if ymax == None: ymax = numpy.nanmax(y)
557 if ymax == None: ymax = numpy.nanmax(y)
555
558
556 self.__isConfig = True
559 self.__isConfig = True
557
560
558 self.setWinTitle(title)
561 self.setWinTitle(title)
559
562
560 for i in range(len(self.axesList)):
563 for i in range(len(self.axesList)):
561 title = "Channel %d" %(i)
564 title = "Channel %d" %(i)
562 axes = self.axesList[i]
565 axes = self.axesList[i]
563 ychannel = y[i,:]
566 ychannel = y[i,:]
564 axes.pline(x, ychannel,
567 axes.pline(x, ychannel,
565 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
568 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
566 xlabel=xlabel, ylabel=ylabel, title=title)
569 xlabel=xlabel, ylabel=ylabel, title=title)
567
570
568 self.draw()
571 self.draw()
569
572
570 if save:
573 if save:
571 date = thisDatetime.strftime("%Y%m%d_%H%M%S")
574 date = thisDatetime.strftime("%Y%m%d_%H%M%S")
572 if figfile == None:
575 if figfile == None:
573 figfile = self.getFilename(name = date)
576 figfile = self.getFilename(name = date)
574
577
575 self.saveFigure(figpath, figfile)
578 self.saveFigure(figpath, figfile)
576
579
577 class ProfilePlot(Figure):
580 class ProfilePlot(Figure):
578 __isConfig = None
581 __isConfig = None
579 __nsubplots = None
582 __nsubplots = None
580
583
581 WIDTHPROF = None
584 WIDTHPROF = None
582 HEIGHTPROF = None
585 HEIGHTPROF = None
583 PREFIX = 'spcprofile'
586 PREFIX = 'spcprofile'
584
587
585 def __init__(self):
588 def __init__(self):
586 self.__isConfig = False
589 self.__isConfig = False
587 self.__nsubplots = 1
590 self.__nsubplots = 1
588
591
589 self.WIDTH = 300
592 self.WIDTH = 300
590 self.HEIGHT = 500
593 self.HEIGHT = 500
591
594
592 def getSubplots(self):
595 def getSubplots(self):
593 ncol = 1
596 ncol = 1
594 nrow = 1
597 nrow = 1
595
598
596 return nrow, ncol
599 return nrow, ncol
597
600
598 def setup(self, idfigure, nplots, wintitle):
601 def setup(self, idfigure, nplots, wintitle):
599
602
600 self.nplots = nplots
603 self.nplots = nplots
601
604
602 ncolspan = 1
605 ncolspan = 1
603 colspan = 1
606 colspan = 1
604
607
605 self.createFigure(idfigure = idfigure,
608 self.createFigure(idfigure = idfigure,
606 wintitle = wintitle,
609 wintitle = wintitle,
607 widthplot = self.WIDTH,
610 widthplot = self.WIDTH,
608 heightplot = self.HEIGHT)
611 heightplot = self.HEIGHT)
609
612
610 nrow, ncol = self.getSubplots()
613 nrow, ncol = self.getSubplots()
611
614
612 counter = 0
615 counter = 0
613 for y in range(nrow):
616 for y in range(nrow):
614 for x in range(ncol):
617 for x in range(ncol):
615 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
618 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
616
619
617 def run(self, dataOut, idfigure, wintitle="", channelList=None,
620 def run(self, dataOut, idfigure, wintitle="", channelList=None,
618 xmin=None, xmax=None, ymin=None, ymax=None,
621 xmin=None, xmax=None, ymin=None, ymax=None,
619 save=False, figpath='./', figfile=None):
622 save=False, figpath='./', figfile=None):
620
623
621 if channelList == None:
624 if channelList == None:
622 channelIndexList = dataOut.channelIndexList
625 channelIndexList = dataOut.channelIndexList
623 channelList = dataOut.channelList
626 channelList = dataOut.channelList
624 else:
627 else:
625 channelIndexList = []
628 channelIndexList = []
626 for channel in channelList:
629 for channel in channelList:
627 if channel not in dataOut.channelList:
630 if channel not in dataOut.channelList:
628 raise ValueError, "Channel %d is not in dataOut.channelList"
631 raise ValueError, "Channel %d is not in dataOut.channelList"
629 channelIndexList.append(dataOut.channelList.index(channel))
632 channelIndexList.append(dataOut.channelList.index(channel))
630
633
631
634
632 y = dataOut.getHeiRange()
635 y = dataOut.getHeiRange()
633 x = 10.*numpy.log10(dataOut.data_spc[channelIndexList,:,:])
636 x = 10.*numpy.log10(dataOut.data_spc[channelIndexList,:,:])
634 avg = numpy.average(x, axis=1)
637 avg = numpy.average(x, axis=1)
635
638
636 thisDatetime = dataOut.datatime
639 thisDatetime = dataOut.datatime
637 title = "Power Profile"
640 title = "Power Profile"
638 xlabel = "dB"
641 xlabel = "dB"
639 ylabel = "Range (Km)"
642 ylabel = "Range (Km)"
640
643
641 if not self.__isConfig:
644 if not self.__isConfig:
642
645
643 nplots = 1
646 nplots = 1
644
647
645 self.setup(idfigure=idfigure,
648 self.setup(idfigure=idfigure,
646 nplots=nplots,
649 nplots=nplots,
647 wintitle=wintitle)
650 wintitle=wintitle)
648
651
649 if ymin == None: ymin = numpy.nanmin(y)
652 if ymin == None: ymin = numpy.nanmin(y)
650 if ymax == None: ymax = numpy.nanmax(y)
653 if ymax == None: ymax = numpy.nanmax(y)
651 if xmin == None: xmin = numpy.nanmin(avg)*0.9
654 if xmin == None: xmin = numpy.nanmin(avg)*0.9
652 if xmax == None: xmax = numpy.nanmax(avg)*0.9
655 if xmax == None: xmax = numpy.nanmax(avg)*0.9
653
656
654 self.__isConfig = True
657 self.__isConfig = True
655
658
656 self.setWinTitle(title)
659 self.setWinTitle(title)
657
660
658
661
659 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
662 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
660 axes = self.axesList[0]
663 axes = self.axesList[0]
661
664
662 legendlabels = ["channel %d"%x for x in channelList]
665 legendlabels = ["channel %d"%x for x in channelList]
663 axes.pmultiline(avg, y,
666 axes.pmultiline(avg, y,
664 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
667 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
665 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
668 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
666 ytick_visible=True, nxticks=5,
669 ytick_visible=True, nxticks=5,
667 grid='x')
670 grid='x')
668
671
669 self.draw()
672 self.draw()
670
673
671 if save:
674 if save:
672 date = thisDatetime.strftime("%Y%m%d")
675 date = thisDatetime.strftime("%Y%m%d")
673 if figfile == None:
676 if figfile == None:
674 figfile = self.getFilename(name = date)
677 figfile = self.getFilename(name = date)
675
678
676 self.saveFigure(figpath, figfile)
679 self.saveFigure(figpath, figfile)
677
680
678 class CoherenceMap(Figure):
681 class CoherenceMap(Figure):
679 __isConfig = None
682 __isConfig = None
680 __nsubplots = None
683 __nsubplots = None
681
684
682 WIDTHPROF = None
685 WIDTHPROF = None
683 HEIGHTPROF = None
686 HEIGHTPROF = None
684 PREFIX = 'coherencemap'
687 PREFIX = 'coherencemap'
685
688
686 def __init__(self):
689 def __init__(self):
687 self.timerange = 2*60*60
690 self.timerange = 2*60*60
688 self.__isConfig = False
691 self.__isConfig = False
689 self.__nsubplots = 1
692 self.__nsubplots = 1
690
693
691 self.WIDTH = 800
694 self.WIDTH = 800
692 self.HEIGHT = 200
695 self.HEIGHT = 200
693 self.WIDTHPROF = 120
696 self.WIDTHPROF = 120
694 self.HEIGHTPROF = 0
697 self.HEIGHTPROF = 0
695
698
696 def getSubplots(self):
699 def getSubplots(self):
697 ncol = 1
700 ncol = 1
698 nrow = self.nplots*2
701 nrow = self.nplots*2
699
702
700 return nrow, ncol
703 return nrow, ncol
701
704
702 def setup(self, idfigure, nplots, wintitle, showprofile=True):
705 def setup(self, idfigure, nplots, wintitle, showprofile=True):
703 self.__showprofile = showprofile
706 self.__showprofile = showprofile
704 self.nplots = nplots
707 self.nplots = nplots
705
708
706 ncolspan = 1
709 ncolspan = 1
707 colspan = 1
710 colspan = 1
708 if showprofile:
711 if showprofile:
709 ncolspan = 7
712 ncolspan = 7
710 colspan = 6
713 colspan = 6
711 self.__nsubplots = 2
714 self.__nsubplots = 2
712
715
713 self.createFigure(idfigure = idfigure,
716 self.createFigure(idfigure = idfigure,
714 wintitle = wintitle,
717 wintitle = wintitle,
715 widthplot = self.WIDTH + self.WIDTHPROF,
718 widthplot = self.WIDTH + self.WIDTHPROF,
716 heightplot = self.HEIGHT + self.HEIGHTPROF)
719 heightplot = self.HEIGHT + self.HEIGHTPROF)
717
720
718 nrow, ncol = self.getSubplots()
721 nrow, ncol = self.getSubplots()
719
722
720 for y in range(nrow):
723 for y in range(nrow):
721 for x in range(ncol):
724 for x in range(ncol):
722
725
723 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
726 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
724
727
725 if showprofile:
728 if showprofile:
726 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
729 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
727
730
728 def run(self, dataOut, idfigure, wintitle="", pairsList=None, showprofile='True',
731 def run(self, dataOut, idfigure, wintitle="", pairsList=None, showprofile='True',
729 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
732 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
730 timerange=None,
733 timerange=None,
731 save=False, figpath='./', figfile=None):
734 save=False, figpath='./', figfile=None):
732
735
733 if pairsList == None:
736 if pairsList == None:
734 pairsIndexList = dataOut.pairsIndexList
737 pairsIndexList = dataOut.pairsIndexList
735 else:
738 else:
736 pairsIndexList = []
739 pairsIndexList = []
737 for pair in pairsList:
740 for pair in pairsList:
738 if pair not in dataOut.pairsList:
741 if pair not in dataOut.pairsList:
739 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
742 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
740 pairsIndexList.append(dataOut.pairsList.index(pair))
743 pairsIndexList.append(dataOut.pairsList.index(pair))
741
744
742 if timerange != None:
745 if timerange != None:
743 self.timerange = timerange
746 self.timerange = timerange
744
747
745 if pairsIndexList == []:
748 if pairsIndexList == []:
746 return
749 return
747
750
748 if len(pairsIndexList) > 4:
751 if len(pairsIndexList) > 4:
749 pairsIndexList = pairsIndexList[0:4]
752 pairsIndexList = pairsIndexList[0:4]
750
753
751 tmin = None
754 tmin = None
752 tmax = None
755 tmax = None
753 x = dataOut.getTimeRange()
756 x = dataOut.getTimeRange()
754 y = dataOut.getHeiRange()
757 y = dataOut.getHeiRange()
755
758
756 thisDatetime = dataOut.datatime
759 thisDatetime = dataOut.datatime
757 title = "CoherenceMap: %s" %(thisDatetime.strftime("%d-%b-%Y"))
760 title = "CoherenceMap: %s" %(thisDatetime.strftime("%d-%b-%Y"))
758 xlabel = ""
761 xlabel = ""
759 ylabel = "Range (Km)"
762 ylabel = "Range (Km)"
760
763
761 if not self.__isConfig:
764 if not self.__isConfig:
762 nplots = len(pairsIndexList)
765 nplots = len(pairsIndexList)
763 self.setup(idfigure=idfigure,
766 self.setup(idfigure=idfigure,
764 nplots=nplots,
767 nplots=nplots,
765 wintitle=wintitle,
768 wintitle=wintitle,
766 showprofile=showprofile)
769 showprofile=showprofile)
767
770
768 tmin, tmax = self.getTimeLim(x, xmin, xmax)
771 tmin, tmax = self.getTimeLim(x, xmin, xmax)
769 if ymin == None: ymin = numpy.nanmin(y)
772 if ymin == None: ymin = numpy.nanmin(y)
770 if ymax == None: ymax = numpy.nanmax(y)
773 if ymax == None: ymax = numpy.nanmax(y)
771
774
772 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
775 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
773
776
774 self.__isConfig = True
777 self.__isConfig = True
775
778
776 self.setWinTitle(title)
779 self.setWinTitle(title)
777
780
778 for i in range(self.nplots):
781 for i in range(self.nplots):
779
782
780 pair = dataOut.pairsList[pairsIndexList[i]]
783 pair = dataOut.pairsList[pairsIndexList[i]]
781 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[pair[0],:,:]*dataOut.data_spc[pair[1],:,:])
784 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[pair[0],:,:]*dataOut.data_spc[pair[1],:,:])
782 coherence = numpy.abs(coherenceComplex)
785 coherence = numpy.abs(coherenceComplex)
783 avg = numpy.average(coherence, axis=0)
786 avg = numpy.average(coherence, axis=0)
784 z = avg.reshape((1,-1))
787 z = avg.reshape((1,-1))
785
788
786 counter = 0
789 counter = 0
787
790
788 title = "Coherence %d%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
791 title = "Coherence %d%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
789 axes = self.axesList[i*self.__nsubplots*2]
792 axes = self.axesList[i*self.__nsubplots*2]
790 axes.pcolor(x, y, z,
793 axes.pcolor(x, y, z,
791 xmin=tmin, xmax=tmax, ymin=ymin, ymax=ymax, zmin=0, zmax=1,
794 xmin=tmin, xmax=tmax, ymin=ymin, ymax=ymax, zmin=0, zmax=1,
792 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
795 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
793 ticksize=9, cblabel='', cbsize="1%")
796 ticksize=9, cblabel='', cbsize="1%")
794
797
795 if self.__showprofile:
798 if self.__showprofile:
796 counter += 1
799 counter += 1
797 axes = self.axesList[i*self.__nsubplots*2 + counter]
800 axes = self.axesList[i*self.__nsubplots*2 + counter]
798 axes.pline(avg, y,
801 axes.pline(avg, y,
799 xmin=0, xmax=1, ymin=ymin, ymax=ymax,
802 xmin=0, xmax=1, ymin=ymin, ymax=ymax,
800 xlabel='', ylabel='', title='', ticksize=7,
803 xlabel='', ylabel='', title='', ticksize=7,
801 ytick_visible=False, nxticks=5,
804 ytick_visible=False, nxticks=5,
802 grid='x')
805 grid='x')
803
806
804 counter += 1
807 counter += 1
805 phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
808 phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
806 avg = numpy.average(phase, axis=0)
809 avg = numpy.average(phase, axis=0)
807 z = avg.reshape((1,-1))
810 z = avg.reshape((1,-1))
808
811
809 title = "Phase %d%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
812 title = "Phase %d%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
810 axes = self.axesList[i*self.__nsubplots*2 + counter]
813 axes = self.axesList[i*self.__nsubplots*2 + counter]
811 axes.pcolor(x, y, z,
814 axes.pcolor(x, y, z,
812 xmin=tmin, xmax=tmax, ymin=ymin, ymax=ymax, zmin=-180, zmax=180,
815 xmin=tmin, xmax=tmax, ymin=ymin, ymax=ymax, zmin=-180, zmax=180,
813 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
816 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
814 ticksize=9, cblabel='', colormap='RdBu', cbsize="1%")
817 ticksize=9, cblabel='', colormap='RdBu', cbsize="1%")
815
818
816 if self.__showprofile:
819 if self.__showprofile:
817 counter += 1
820 counter += 1
818 axes = self.axesList[i*self.__nsubplots*2 + counter]
821 axes = self.axesList[i*self.__nsubplots*2 + counter]
819 axes.pline(avg, y,
822 axes.pline(avg, y,
820 xmin=-180, xmax=180, ymin=ymin, ymax=ymax,
823 xmin=-180, xmax=180, ymin=ymin, ymax=ymax,
821 xlabel='', ylabel='', title='', ticksize=7,
824 xlabel='', ylabel='', title='', ticksize=7,
822 ytick_visible=False, nxticks=4,
825 ytick_visible=False, nxticks=4,
823 grid='x')
826 grid='x')
824
827
825 self.draw()
828 self.draw()
826
829
827 if save:
830 if save:
828
831
829 if figfile == None:
832 if figfile == None:
830 figfile = self.getFilename(name = self.name)
833 figfile = self.getFilename(name = self.name)
831
834
832 self.saveFigure(figpath, figfile)
835 self.saveFigure(figpath, figfile)
833
836
834 if x[1] + (x[1]-x[0]) >= self.axesList[0].xmax:
837 if x[1] + (x[1]-x[0]) >= self.axesList[0].xmax:
835 self.__isConfig = False
838 self.__isConfig = False
836
839
837 class RTIfromNoise(Figure):
840 class RTIfromNoise(Figure):
838
841
839 __isConfig = None
842 __isConfig = None
840 __nsubplots = None
843 __nsubplots = None
841
844
842 WIDTHPROF = None
845 WIDTHPROF = None
843 HEIGHTPROF = None
846 HEIGHTPROF = None
844 PREFIX = 'rti'
847 PREFIX = 'rti'
845
848
846 def __init__(self):
849 def __init__(self):
847
850
848 self.__timerange = 24*60*60
851 self.__timerange = 24*60*60
849 self.__isConfig = False
852 self.__isConfig = False
850 self.__nsubplots = 1
853 self.__nsubplots = 1
851
854
852 self.WIDTH = 800
855 self.WIDTH = 800
853 self.HEIGHT = 200
856 self.HEIGHT = 200
854
857
855 def getSubplots(self):
858 def getSubplots(self):
856
859
857 ncol = 1
860 ncol = 1
858 nrow = self.nplots
861 nrow = self.nplots
859
862
860 return nrow, ncol
863 return nrow, ncol
861
864
862 def setup(self, idfigure, nplots, wintitle, showprofile=True):
865 def setup(self, idfigure, nplots, wintitle, showprofile=True):
863
866
864 self.__showprofile = showprofile
867 self.__showprofile = showprofile
865 self.nplots = nplots
868 self.nplots = nplots
866
869
867 ncolspan = 1
870 ncolspan = 1
868 colspan = 1
871 colspan = 1
869
872
870 self.createFigure(idfigure = idfigure,
873 self.createFigure(idfigure = idfigure,
871 wintitle = wintitle,
874 wintitle = wintitle,
872 widthplot = self.WIDTH + self.WIDTHPROF,
875 widthplot = self.WIDTH + self.WIDTHPROF,
873 heightplot = self.HEIGHT + self.HEIGHTPROF)
876 heightplot = self.HEIGHT + self.HEIGHTPROF)
874
877
875 nrow, ncol = self.getSubplots()
878 nrow, ncol = self.getSubplots()
876
879
877 self.addAxes(nrow, ncol, 0, 0, 1, 1)
880 self.addAxes(nrow, ncol, 0, 0, 1, 1)
878
881
879
882
880
883
881 def __getTimeLim(self, x, xmin, xmax):
884 def __getTimeLim(self, x, xmin, xmax):
882
885
883 thisdatetime = datetime.datetime.fromtimestamp(numpy.min(x))
886 thisdatetime = datetime.datetime.fromtimestamp(numpy.min(x))
884 thisdate = datetime.datetime.combine(thisdatetime.date(), datetime.time(0,0,0))
887 thisdate = datetime.datetime.combine(thisdatetime.date(), datetime.time(0,0,0))
885
888
886 ####################################################
889 ####################################################
887 #If the x is out of xrange
890 #If the x is out of xrange
888 if xmax < (thisdatetime - thisdate).seconds/(60*60.):
891 if xmax < (thisdatetime - thisdate).seconds/(60*60.):
889 xmin = None
892 xmin = None
890 xmax = None
893 xmax = None
891
894
892 if xmin == None:
895 if xmin == None:
893 td = thisdatetime - thisdate
896 td = thisdatetime - thisdate
894 xmin = td.seconds/(60*60.)
897 xmin = td.seconds/(60*60.)
895
898
896 if xmax == None:
899 if xmax == None:
897 xmax = xmin + self.__timerange/(60*60.)
900 xmax = xmin + self.__timerange/(60*60.)
898
901
899 mindt = thisdate + datetime.timedelta(0,0,0,0,0, xmin)
902 mindt = thisdate + datetime.timedelta(0,0,0,0,0, xmin)
900 tmin = time.mktime(mindt.timetuple())
903 tmin = time.mktime(mindt.timetuple())
901
904
902 maxdt = thisdate + datetime.timedelta(0,0,0,0,0, xmax)
905 maxdt = thisdate + datetime.timedelta(0,0,0,0,0, xmax)
903 tmax = time.mktime(maxdt.timetuple())
906 tmax = time.mktime(maxdt.timetuple())
904
907
905 self.__timerange = tmax - tmin
908 self.__timerange = tmax - tmin
906
909
907 return tmin, tmax
910 return tmin, tmax
908
911
909 def run(self, dataOut, idfigure, wintitle="", channelList=None, showprofile='True',
912 def run(self, dataOut, idfigure, wintitle="", channelList=None, showprofile='True',
910 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
913 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
911 timerange=None,
914 timerange=None,
912 save=False, figpath='./', figfile=None):
915 save=False, figpath='./', figfile=None):
913
916
914 if channelList == None:
917 if channelList == None:
915 channelIndexList = dataOut.channelIndexList
918 channelIndexList = dataOut.channelIndexList
916 else:
919 else:
917 channelIndexList = []
920 channelIndexList = []
918 for channel in channelList:
921 for channel in channelList:
919 if channel not in dataOut.channelList:
922 if channel not in dataOut.channelList:
920 raise ValueError, "Channel %d is not in dataOut.channelList"
923 raise ValueError, "Channel %d is not in dataOut.channelList"
921 channelIndexList.append(dataOut.channelList.index(channel))
924 channelIndexList.append(dataOut.channelList.index(channel))
922
925
923 if timerange != None:
926 if timerange != None:
924 self.__timerange = timerange
927 self.__timerange = timerange
925
928
926 tmin = None
929 tmin = None
927 tmax = None
930 tmax = None
928 x = dataOut.getTimeRange()
931 x = dataOut.getTimeRange()
929 y = dataOut.getHeiRange()
932 y = dataOut.getHeiRange()
930 x1 = dataOut.datatime
933 x1 = dataOut.datatime
931 # z = 10.*numpy.log10(dataOut.data_spc[channelIndexList,:,:])
934 # z = 10.*numpy.log10(dataOut.data_spc[channelIndexList,:,:])
932 # avg = numpy.average(z, axis=1)
935 # avg = numpy.average(z, axis=1)
933
936
934 noise = dataOut.getNoise()
937 noise = dataOut.getNoise()
935
938
936 thisDatetime = dataOut.datatime
939 thisDatetime = dataOut.datatime
937 title = "RTI: %s" %(thisDatetime.strftime("%d-%b-%Y"))
940 title = "RTI: %s" %(thisDatetime.strftime("%d-%b-%Y"))
938 xlabel = "Velocity (m/s)"
941 xlabel = "Velocity (m/s)"
939 ylabel = "Range (Km)"
942 ylabel = "Range (Km)"
940
943
941
944
942 if not self.__isConfig:
945 if not self.__isConfig:
943
946
944 nplots = len(channelIndexList)
947 nplots = len(channelIndexList)
945
948
946 self.setup(idfigure=idfigure,
949 self.setup(idfigure=idfigure,
947 nplots=nplots,
950 nplots=nplots,
948 wintitle=wintitle,
951 wintitle=wintitle,
949 showprofile=showprofile)
952 showprofile=showprofile)
950
953
951 tmin, tmax = self.__getTimeLim(x, xmin, xmax)
954 tmin, tmax = self.__getTimeLim(x, xmin, xmax)
952 if ymin == None: ymin = numpy.nanmin(y)
955 if ymin == None: ymin = numpy.nanmin(y)
953 if ymax == None: ymax = numpy.nanmax(y)
956 if ymax == None: ymax = numpy.nanmax(y)
954 if zmin == None: zmin = numpy.nanmin(avg)*0.9
957 if zmin == None: zmin = numpy.nanmin(avg)*0.9
955 if zmax == None: zmax = numpy.nanmax(avg)*0.9
958 if zmax == None: zmax = numpy.nanmax(avg)*0.9
956
959
957 self.__isConfig = True
960 self.__isConfig = True
958
961
959
962
960 self.setWinTitle(title)
963 self.setWinTitle(title)
961
964
962 for i in range(self.nplots):
965 for i in range(self.nplots):
963 title = "Channel %d: %s" %(dataOut.channelList[i], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
966 title = "Channel %d: %s" %(dataOut.channelList[i], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
964 axes = self.axesList[i*self.__nsubplots]
967 axes = self.axesList[i*self.__nsubplots]
965 z = avg[i].reshape((1,-1))
968 z = avg[i].reshape((1,-1))
966 axes.pcolor(x, y, z,
969 axes.pcolor(x, y, z,
967 xmin=tmin, xmax=tmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
970 xmin=tmin, xmax=tmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
968 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
971 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
969 ticksize=9, cblabel='', cbsize="1%")
972 ticksize=9, cblabel='', cbsize="1%")
970
973
971
974
972 self.draw()
975 self.draw()
973
976
974 if save:
977 if save:
975 date = thisDatetime.strftime("%Y%m%d")
978 date = thisDatetime.strftime("%Y%m%d")
976 if figfile == None:
979 if figfile == None:
977 figfile = self.getFilename(name = date)
980 figfile = self.getFilename(name = date)
978
981
979 self.saveFigure(figpath, figfile)
982 self.saveFigure(figpath, figfile)
980
983
981 if x[1] + (x[1]-x[0]) >= self.axesList[0].xmax:
984 if x[1] + (x[1]-x[0]) >= self.axesList[0].xmax:
982 self.__isConfig = False
985 self.__isConfig = False
983 No newline at end of file
986
@@ -1,1153 +1,1157
1 '''
1 '''
2
2
3 $Author: dsuarez $
3 $Author: dsuarez $
4 $Id: Processor.py 1 2012-11-12 18:56:07Z dsuarez $
4 $Id: Processor.py 1 2012-11-12 18:56:07Z dsuarez $
5 '''
5 '''
6 import os
6 import os
7 import numpy
7 import numpy
8 import datetime
8 import datetime
9 import time
9 import time
10
10
11 from jrodata import *
11 from jrodata import *
12 from jrodataIO import *
12 from jrodataIO import *
13 from jroplot import *
13 from jroplot import *
14
14
15 class ProcessingUnit:
15 class ProcessingUnit:
16
16
17 """
17 """
18 Esta es la clase base para el procesamiento de datos.
18 Esta es la clase base para el procesamiento de datos.
19
19
20 Contiene el metodo "call" para llamar operaciones. Las operaciones pueden ser:
20 Contiene el metodo "call" para llamar operaciones. Las operaciones pueden ser:
21 - Metodos internos (callMethod)
21 - Metodos internos (callMethod)
22 - Objetos del tipo Operation (callObject). Antes de ser llamados, estos objetos
22 - Objetos del tipo Operation (callObject). Antes de ser llamados, estos objetos
23 tienen que ser agreagados con el metodo "add".
23 tienen que ser agreagados con el metodo "add".
24
24
25 """
25 """
26 # objeto de datos de entrada (Voltage, Spectra o Correlation)
26 # objeto de datos de entrada (Voltage, Spectra o Correlation)
27 dataIn = None
27 dataIn = None
28
28
29 # objeto de datos de entrada (Voltage, Spectra o Correlation)
29 # objeto de datos de entrada (Voltage, Spectra o Correlation)
30 dataOut = None
30 dataOut = None
31
31
32
32
33 objectDict = None
33 objectDict = None
34
34
35 def __init__(self):
35 def __init__(self):
36
36
37 self.objectDict = {}
37 self.objectDict = {}
38
38
39 def init(self):
39 def init(self):
40
40
41 raise ValueError, "Not implemented"
41 raise ValueError, "Not implemented"
42
42
43 def addOperation(self, object, objId):
43 def addOperation(self, object, objId):
44
44
45 """
45 """
46 Agrega el objeto "object" a la lista de objetos "self.objectList" y retorna el
46 Agrega el objeto "object" a la lista de objetos "self.objectList" y retorna el
47 identificador asociado a este objeto.
47 identificador asociado a este objeto.
48
48
49 Input:
49 Input:
50
50
51 object : objeto de la clase "Operation"
51 object : objeto de la clase "Operation"
52
52
53 Return:
53 Return:
54
54
55 objId : identificador del objeto, necesario para ejecutar la operacion
55 objId : identificador del objeto, necesario para ejecutar la operacion
56 """
56 """
57
57
58 self.objectDict[objId] = object
58 self.objectDict[objId] = object
59
59
60 return objId
60 return objId
61
61
62 def operation(self, **kwargs):
62 def operation(self, **kwargs):
63
63
64 """
64 """
65 Operacion directa sobre la data (dataOut.data). Es necesario actualizar los valores de los
65 Operacion directa sobre la data (dataOut.data). Es necesario actualizar los valores de los
66 atributos del objeto dataOut
66 atributos del objeto dataOut
67
67
68 Input:
68 Input:
69
69
70 **kwargs : Diccionario de argumentos de la funcion a ejecutar
70 **kwargs : Diccionario de argumentos de la funcion a ejecutar
71 """
71 """
72
72
73 raise ValueError, "ImplementedError"
73 raise ValueError, "ImplementedError"
74
74
75 def callMethod(self, name, **kwargs):
75 def callMethod(self, name, **kwargs):
76
76
77 """
77 """
78 Ejecuta el metodo con el nombre "name" y con argumentos **kwargs de la propia clase.
78 Ejecuta el metodo con el nombre "name" y con argumentos **kwargs de la propia clase.
79
79
80 Input:
80 Input:
81 name : nombre del metodo a ejecutar
81 name : nombre del metodo a ejecutar
82
82
83 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
83 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
84
84
85 """
85 """
86 if name != 'run':
86 if name != 'run':
87
87
88 if name == 'init' and self.dataIn.isEmpty():
88 if name == 'init' and self.dataIn.isEmpty():
89 self.dataOut.flagNoData = True
89 self.dataOut.flagNoData = True
90 return False
90 return False
91
91
92 if name != 'init' and self.dataOut.isEmpty():
92 if name != 'init' and self.dataOut.isEmpty():
93 return False
93 return False
94
94
95 methodToCall = getattr(self, name)
95 methodToCall = getattr(self, name)
96
96
97 methodToCall(**kwargs)
97 methodToCall(**kwargs)
98
98
99 if name != 'run':
99 if name != 'run':
100 return True
100 return True
101
101
102 if self.dataOut.isEmpty():
102 if self.dataOut.isEmpty():
103 return False
103 return False
104
104
105 return True
105 return True
106
106
107 def callObject(self, objId, **kwargs):
107 def callObject(self, objId, **kwargs):
108
108
109 """
109 """
110 Ejecuta la operacion asociada al identificador del objeto "objId"
110 Ejecuta la operacion asociada al identificador del objeto "objId"
111
111
112 Input:
112 Input:
113
113
114 objId : identificador del objeto a ejecutar
114 objId : identificador del objeto a ejecutar
115
115
116 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
116 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
117
117
118 Return:
118 Return:
119
119
120 None
120 None
121 """
121 """
122
122
123 if self.dataOut.isEmpty():
123 if self.dataOut.isEmpty():
124 return False
124 return False
125
125
126 object = self.objectDict[objId]
126 object = self.objectDict[objId]
127
127
128 object.run(self.dataOut, **kwargs)
128 object.run(self.dataOut, **kwargs)
129
129
130 return True
130 return True
131
131
132 def call(self, operationConf, **kwargs):
132 def call(self, operationConf, **kwargs):
133
133
134 """
134 """
135 Return True si ejecuta la operacion "operationConf.name" con los
135 Return True si ejecuta la operacion "operationConf.name" con los
136 argumentos "**kwargs". False si la operacion no se ha ejecutado.
136 argumentos "**kwargs". False si la operacion no se ha ejecutado.
137 La operacion puede ser de dos tipos:
137 La operacion puede ser de dos tipos:
138
138
139 1. Un metodo propio de esta clase:
139 1. Un metodo propio de esta clase:
140
140
141 operation.type = "self"
141 operation.type = "self"
142
142
143 2. El metodo "run" de un objeto del tipo Operation o de un derivado de ella:
143 2. El metodo "run" de un objeto del tipo Operation o de un derivado de ella:
144 operation.type = "other".
144 operation.type = "other".
145
145
146 Este objeto de tipo Operation debe de haber sido agregado antes con el metodo:
146 Este objeto de tipo Operation debe de haber sido agregado antes con el metodo:
147 "addOperation" e identificado con el operation.id
147 "addOperation" e identificado con el operation.id
148
148
149
149
150 con el id de la operacion.
150 con el id de la operacion.
151
151
152 Input:
152 Input:
153
153
154 Operation : Objeto del tipo operacion con los atributos: name, type y id.
154 Operation : Objeto del tipo operacion con los atributos: name, type y id.
155
155
156 """
156 """
157
157
158 if operationConf.type == 'self':
158 if operationConf.type == 'self':
159 sts = self.callMethod(operationConf.name, **kwargs)
159 sts = self.callMethod(operationConf.name, **kwargs)
160
160
161 if operationConf.type == 'other':
161 if operationConf.type == 'other':
162 sts = self.callObject(operationConf.id, **kwargs)
162 sts = self.callObject(operationConf.id, **kwargs)
163
163
164 return sts
164 return sts
165
165
166 def setInput(self, dataIn):
166 def setInput(self, dataIn):
167
167
168 self.dataIn = dataIn
168 self.dataIn = dataIn
169
169
170 def getOutput(self):
170 def getOutput(self):
171
171
172 return self.dataOut
172 return self.dataOut
173
173
174 class Operation():
174 class Operation():
175
175
176 """
176 """
177 Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit
177 Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit
178 y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de
178 y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de
179 acumulacion dentro de esta clase
179 acumulacion dentro de esta clase
180
180
181 Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer)
181 Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer)
182
182
183 """
183 """
184
184
185 __buffer = None
185 __buffer = None
186 __isConfig = False
186 __isConfig = False
187
187
188 def __init__(self):
188 def __init__(self):
189
189
190 pass
190 pass
191
191
192 def run(self, dataIn, **kwargs):
192 def run(self, dataIn, **kwargs):
193
193
194 """
194 """
195 Realiza las operaciones necesarias sobre la dataIn.data y actualiza los atributos del objeto dataIn.
195 Realiza las operaciones necesarias sobre la dataIn.data y actualiza los atributos del objeto dataIn.
196
196
197 Input:
197 Input:
198
198
199 dataIn : objeto del tipo JROData
199 dataIn : objeto del tipo JROData
200
200
201 Return:
201 Return:
202
202
203 None
203 None
204
204
205 Affected:
205 Affected:
206 __buffer : buffer de recepcion de datos.
206 __buffer : buffer de recepcion de datos.
207
207
208 """
208 """
209
209
210 raise ValueError, "ImplementedError"
210 raise ValueError, "ImplementedError"
211
211
212 class VoltageProc(ProcessingUnit):
212 class VoltageProc(ProcessingUnit):
213
213
214
214
215 def __init__(self):
215 def __init__(self):
216
216
217 self.objectDict = {}
217 self.objectDict = {}
218 self.dataOut = Voltage()
218 self.dataOut = Voltage()
219 self.flip = 1
219
220
220 def init(self):
221 def init(self):
221
222
222 self.dataOut.copy(self.dataIn)
223 self.dataOut.copy(self.dataIn)
223 # No necesita copiar en cada init() los atributos de dataIn
224 # No necesita copiar en cada init() los atributos de dataIn
224 # la copia deberia hacerse por cada nuevo bloque de datos
225 # la copia deberia hacerse por cada nuevo bloque de datos
225
226
226 def selectChannels(self, channelList):
227 def selectChannels(self, channelList):
227
228
228 channelIndexList = []
229 channelIndexList = []
229
230
230 for channel in channelList:
231 for channel in channelList:
231 index = self.dataOut.channelList.index(channel)
232 index = self.dataOut.channelList.index(channel)
232 channelIndexList.append(index)
233 channelIndexList.append(index)
233
234
234 self.selectChannelsByIndex(channelIndexList)
235 self.selectChannelsByIndex(channelIndexList)
235
236
236 def selectChannelsByIndex(self, channelIndexList):
237 def selectChannelsByIndex(self, channelIndexList):
237 """
238 """
238 Selecciona un bloque de datos en base a canales segun el channelIndexList
239 Selecciona un bloque de datos en base a canales segun el channelIndexList
239
240
240 Input:
241 Input:
241 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
242 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
242
243
243 Affected:
244 Affected:
244 self.dataOut.data
245 self.dataOut.data
245 self.dataOut.channelIndexList
246 self.dataOut.channelIndexList
246 self.dataOut.nChannels
247 self.dataOut.nChannels
247 self.dataOut.m_ProcessingHeader.totalSpectra
248 self.dataOut.m_ProcessingHeader.totalSpectra
248 self.dataOut.systemHeaderObj.numChannels
249 self.dataOut.systemHeaderObj.numChannels
249 self.dataOut.m_ProcessingHeader.blockSize
250 self.dataOut.m_ProcessingHeader.blockSize
250
251
251 Return:
252 Return:
252 None
253 None
253 """
254 """
254
255
255 for channelIndex in channelIndexList:
256 for channelIndex in channelIndexList:
256 if channelIndex not in self.dataOut.channelIndexList:
257 if channelIndex not in self.dataOut.channelIndexList:
257 print channelIndexList
258 print channelIndexList
258 raise ValueError, "The value %d in channelIndexList is not valid" %channelIndex
259 raise ValueError, "The value %d in channelIndexList is not valid" %channelIndex
259
260
260 nChannels = len(channelIndexList)
261 nChannels = len(channelIndexList)
261
262
262 data = self.dataOut.data[channelIndexList,:]
263 data = self.dataOut.data[channelIndexList,:]
263
264
264 self.dataOut.data = data
265 self.dataOut.data = data
265 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
266 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
266 # self.dataOut.nChannels = nChannels
267 # self.dataOut.nChannels = nChannels
267
268
268 return 1
269 return 1
269
270
270 def selectHeights(self, minHei, maxHei):
271 def selectHeights(self, minHei, maxHei):
271 """
272 """
272 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
273 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
273 minHei <= height <= maxHei
274 minHei <= height <= maxHei
274
275
275 Input:
276 Input:
276 minHei : valor minimo de altura a considerar
277 minHei : valor minimo de altura a considerar
277 maxHei : valor maximo de altura a considerar
278 maxHei : valor maximo de altura a considerar
278
279
279 Affected:
280 Affected:
280 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
281 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
281
282
282 Return:
283 Return:
283 1 si el metodo se ejecuto con exito caso contrario devuelve 0
284 1 si el metodo se ejecuto con exito caso contrario devuelve 0
284 """
285 """
285 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
286 if (minHei < self.dataOut.heightList[0]) or (minHei > maxHei):
286 raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
287 raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
287
288
288 if (maxHei > self.dataOut.heightList[-1]):
289 if (maxHei > self.dataOut.heightList[-1]):
289 maxHei = self.dataOut.heightList[-1]
290 maxHei = self.dataOut.heightList[-1]
290 # raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
291 # raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
291
292
292 minIndex = 0
293 minIndex = 0
293 maxIndex = 0
294 maxIndex = 0
294 data = self.dataOut.heightList
295 data = self.dataOut.heightList
295
296
296 for i,val in enumerate(data):
297 for i,val in enumerate(data):
297 if val < minHei:
298 if val < minHei:
298 continue
299 continue
299 else:
300 else:
300 minIndex = i;
301 minIndex = i;
301 break
302 break
302
303
303 for i,val in enumerate(data):
304 for i,val in enumerate(data):
304 if val <= maxHei:
305 if val <= maxHei:
305 maxIndex = i;
306 maxIndex = i;
306 else:
307 else:
307 break
308 break
308
309
309 self.selectHeightsByIndex(minIndex, maxIndex)
310 self.selectHeightsByIndex(minIndex, maxIndex)
310
311
311 return 1
312 return 1
312
313
313
314
314 def selectHeightsByIndex(self, minIndex, maxIndex):
315 def selectHeightsByIndex(self, minIndex, maxIndex):
315 """
316 """
316 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
317 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
317 minIndex <= index <= maxIndex
318 minIndex <= index <= maxIndex
318
319
319 Input:
320 Input:
320 minIndex : valor de indice minimo de altura a considerar
321 minIndex : valor de indice minimo de altura a considerar
321 maxIndex : valor de indice maximo de altura a considerar
322 maxIndex : valor de indice maximo de altura a considerar
322
323
323 Affected:
324 Affected:
324 self.dataOut.data
325 self.dataOut.data
325 self.dataOut.heightList
326 self.dataOut.heightList
326
327
327 Return:
328 Return:
328 1 si el metodo se ejecuto con exito caso contrario devuelve 0
329 1 si el metodo se ejecuto con exito caso contrario devuelve 0
329 """
330 """
330
331
331 if (minIndex < 0) or (minIndex > maxIndex):
332 if (minIndex < 0) or (minIndex > maxIndex):
332 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
333 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
333
334
334 if (maxIndex >= self.dataOut.nHeights):
335 if (maxIndex >= self.dataOut.nHeights):
335 maxIndex = self.dataOut.nHeights-1
336 maxIndex = self.dataOut.nHeights-1
336 # raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
337 # raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
337
338
338 nHeights = maxIndex - minIndex + 1
339 nHeights = maxIndex - minIndex + 1
339
340
340 #voltage
341 #voltage
341 data = self.dataOut.data[:,minIndex:maxIndex+1]
342 data = self.dataOut.data[:,minIndex:maxIndex+1]
342
343
343 firstHeight = self.dataOut.heightList[minIndex]
344 firstHeight = self.dataOut.heightList[minIndex]
344
345
345 self.dataOut.data = data
346 self.dataOut.data = data
346 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
347 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex+1]
347
348
348 return 1
349 return 1
349
350
350
351
351 def filterByHeights(self, window):
352 def filterByHeights(self, window):
352 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
353 deltaHeight = self.dataOut.heightList[1] - self.dataOut.heightList[0]
353
354
354 if window == None:
355 if window == None:
355 window = self.dataOut.radarControllerHeaderObj.txA / deltaHeight
356 window = self.dataOut.radarControllerHeaderObj.txA / deltaHeight
356
357
357 newdelta = deltaHeight * window
358 newdelta = deltaHeight * window
358 r = self.dataOut.data.shape[1] % window
359 r = self.dataOut.data.shape[1] % window
359 buffer = self.dataOut.data[:,0:self.dataOut.data.shape[1]-r]
360 buffer = self.dataOut.data[:,0:self.dataOut.data.shape[1]-r]
360 buffer = buffer.reshape(self.dataOut.data.shape[0],self.dataOut.data.shape[1]/window,window)
361 buffer = buffer.reshape(self.dataOut.data.shape[0],self.dataOut.data.shape[1]/window,window)
361 buffer = numpy.average(buffer,2)
362 buffer = numpy.average(buffer,2)
362 self.dataOut.data = buffer
363 self.dataOut.data = buffer
363 self.dataOut.heightList = numpy.arange(self.dataOut.heightList[0],newdelta*self.dataOut.nHeights/window-newdelta,newdelta)
364 self.dataOut.heightList = numpy.arange(self.dataOut.heightList[0],newdelta*self.dataOut.nHeights/window-newdelta,newdelta)
364
365
366 def deFlip(self):
367 self.dataOut.data *= self.flip
368 self.flip *= -1.
365
369
366
370
367 class CohInt(Operation):
371 class CohInt(Operation):
368
372
369 __isConfig = False
373 __isConfig = False
370
374
371 __profIndex = 0
375 __profIndex = 0
372 __withOverapping = False
376 __withOverapping = False
373
377
374 __byTime = False
378 __byTime = False
375 __initime = None
379 __initime = None
376 __lastdatatime = None
380 __lastdatatime = None
377 __integrationtime = None
381 __integrationtime = None
378
382
379 __buffer = None
383 __buffer = None
380
384
381 __dataReady = False
385 __dataReady = False
382
386
383 n = None
387 n = None
384
388
385
389
386 def __init__(self):
390 def __init__(self):
387
391
388 self.__isConfig = False
392 self.__isConfig = False
389
393
390 def setup(self, n=None, timeInterval=None, overlapping=False):
394 def setup(self, n=None, timeInterval=None, overlapping=False):
391 """
395 """
392 Set the parameters of the integration class.
396 Set the parameters of the integration class.
393
397
394 Inputs:
398 Inputs:
395
399
396 n : Number of coherent integrations
400 n : Number of coherent integrations
397 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
401 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
398 overlapping :
402 overlapping :
399
403
400 """
404 """
401
405
402 self.__initime = None
406 self.__initime = None
403 self.__lastdatatime = 0
407 self.__lastdatatime = 0
404 self.__buffer = None
408 self.__buffer = None
405 self.__dataReady = False
409 self.__dataReady = False
406
410
407
411
408 if n == None and timeInterval == None:
412 if n == None and timeInterval == None:
409 raise ValueError, "n or timeInterval should be specified ..."
413 raise ValueError, "n or timeInterval should be specified ..."
410
414
411 if n != None:
415 if n != None:
412 self.n = n
416 self.n = n
413 self.__byTime = False
417 self.__byTime = False
414 else:
418 else:
415 self.__integrationtime = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line
419 self.__integrationtime = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line
416 self.n = 9999
420 self.n = 9999
417 self.__byTime = True
421 self.__byTime = True
418
422
419 if overlapping:
423 if overlapping:
420 self.__withOverapping = True
424 self.__withOverapping = True
421 self.__buffer = None
425 self.__buffer = None
422 else:
426 else:
423 self.__withOverapping = False
427 self.__withOverapping = False
424 self.__buffer = 0
428 self.__buffer = 0
425
429
426 self.__profIndex = 0
430 self.__profIndex = 0
427
431
428 def putData(self, data):
432 def putData(self, data):
429
433
430 """
434 """
431 Add a profile to the __buffer and increase in one the __profileIndex
435 Add a profile to the __buffer and increase in one the __profileIndex
432
436
433 """
437 """
434
438
435 if not self.__withOverapping:
439 if not self.__withOverapping:
436 self.__buffer += data.copy()
440 self.__buffer += data.copy()
437 self.__profIndex += 1
441 self.__profIndex += 1
438 return
442 return
439
443
440 #Overlapping data
444 #Overlapping data
441 nChannels, nHeis = data.shape
445 nChannels, nHeis = data.shape
442 data = numpy.reshape(data, (1, nChannels, nHeis))
446 data = numpy.reshape(data, (1, nChannels, nHeis))
443
447
444 #If the buffer is empty then it takes the data value
448 #If the buffer is empty then it takes the data value
445 if self.__buffer == None:
449 if self.__buffer == None:
446 self.__buffer = data
450 self.__buffer = data
447 self.__profIndex += 1
451 self.__profIndex += 1
448 return
452 return
449
453
450 #If the buffer length is lower than n then stakcing the data value
454 #If the buffer length is lower than n then stakcing the data value
451 if self.__profIndex < self.n:
455 if self.__profIndex < self.n:
452 self.__buffer = numpy.vstack((self.__buffer, data))
456 self.__buffer = numpy.vstack((self.__buffer, data))
453 self.__profIndex += 1
457 self.__profIndex += 1
454 return
458 return
455
459
456 #If the buffer length is equal to n then replacing the last buffer value with the data value
460 #If the buffer length is equal to n then replacing the last buffer value with the data value
457 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
461 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
458 self.__buffer[self.n-1] = data
462 self.__buffer[self.n-1] = data
459 self.__profIndex = self.n
463 self.__profIndex = self.n
460 return
464 return
461
465
462
466
463 def pushData(self):
467 def pushData(self):
464 """
468 """
465 Return the sum of the last profiles and the profiles used in the sum.
469 Return the sum of the last profiles and the profiles used in the sum.
466
470
467 Affected:
471 Affected:
468
472
469 self.__profileIndex
473 self.__profileIndex
470
474
471 """
475 """
472
476
473 if not self.__withOverapping:
477 if not self.__withOverapping:
474 data = self.__buffer
478 data = self.__buffer
475 n = self.__profIndex
479 n = self.__profIndex
476
480
477 self.__buffer = 0
481 self.__buffer = 0
478 self.__profIndex = 0
482 self.__profIndex = 0
479
483
480 return data, n
484 return data, n
481
485
482 #Integration with Overlapping
486 #Integration with Overlapping
483 data = numpy.sum(self.__buffer, axis=0)
487 data = numpy.sum(self.__buffer, axis=0)
484 n = self.__profIndex
488 n = self.__profIndex
485
489
486 return data, n
490 return data, n
487
491
488 def byProfiles(self, data):
492 def byProfiles(self, data):
489
493
490 self.__dataReady = False
494 self.__dataReady = False
491 avgdata = None
495 avgdata = None
492 n = None
496 n = None
493
497
494 self.putData(data)
498 self.putData(data)
495
499
496 if self.__profIndex == self.n:
500 if self.__profIndex == self.n:
497
501
498 avgdata, n = self.pushData()
502 avgdata, n = self.pushData()
499 self.__dataReady = True
503 self.__dataReady = True
500
504
501 return avgdata
505 return avgdata
502
506
503 def byTime(self, data, datatime):
507 def byTime(self, data, datatime):
504
508
505 self.__dataReady = False
509 self.__dataReady = False
506 avgdata = None
510 avgdata = None
507 n = None
511 n = None
508
512
509 self.putData(data)
513 self.putData(data)
510
514
511 if (datatime - self.__initime) >= self.__integrationtime:
515 if (datatime - self.__initime) >= self.__integrationtime:
512 avgdata, n = self.pushData()
516 avgdata, n = self.pushData()
513 self.n = n
517 self.n = n
514 self.__dataReady = True
518 self.__dataReady = True
515
519
516 return avgdata
520 return avgdata
517
521
518 def integrate(self, data, datatime=None):
522 def integrate(self, data, datatime=None):
519
523
520 if self.__initime == None:
524 if self.__initime == None:
521 self.__initime = datatime
525 self.__initime = datatime
522
526
523 if self.__byTime:
527 if self.__byTime:
524 avgdata = self.byTime(data, datatime)
528 avgdata = self.byTime(data, datatime)
525 else:
529 else:
526 avgdata = self.byProfiles(data)
530 avgdata = self.byProfiles(data)
527
531
528
532
529 self.__lastdatatime = datatime
533 self.__lastdatatime = datatime
530
534
531 if avgdata == None:
535 if avgdata == None:
532 return None, None
536 return None, None
533
537
534 avgdatatime = self.__initime
538 avgdatatime = self.__initime
535
539
536 deltatime = datatime -self.__lastdatatime
540 deltatime = datatime -self.__lastdatatime
537
541
538 if not self.__withOverapping:
542 if not self.__withOverapping:
539 self.__initime = datatime
543 self.__initime = datatime
540 else:
544 else:
541 self.__initime += deltatime
545 self.__initime += deltatime
542
546
543 return avgdata, avgdatatime
547 return avgdata, avgdatatime
544
548
545 def run(self, dataOut, **kwargs):
549 def run(self, dataOut, **kwargs):
546
550
547 if not self.__isConfig:
551 if not self.__isConfig:
548 self.setup(**kwargs)
552 self.setup(**kwargs)
549 self.__isConfig = True
553 self.__isConfig = True
550
554
551 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
555 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
552
556
553 # dataOut.timeInterval *= n
557 # dataOut.timeInterval *= n
554 dataOut.flagNoData = True
558 dataOut.flagNoData = True
555
559
556 if self.__dataReady:
560 if self.__dataReady:
557 dataOut.data = avgdata
561 dataOut.data = avgdata
558 dataOut.nCohInt *= self.n
562 dataOut.nCohInt *= self.n
559 dataOut.utctime = avgdatatime
563 dataOut.utctime = avgdatatime
560 dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
564 dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
561 dataOut.flagNoData = False
565 dataOut.flagNoData = False
562
566
563
567
564 class Decoder(Operation):
568 class Decoder(Operation):
565
569
566 __isConfig = False
570 __isConfig = False
567 __profIndex = 0
571 __profIndex = 0
568
572
569 code = None
573 code = None
570
574
571 nCode = None
575 nCode = None
572 nBaud = None
576 nBaud = None
573
577
574 def __init__(self):
578 def __init__(self):
575
579
576 self.__isConfig = False
580 self.__isConfig = False
577
581
578 def setup(self, code):
582 def setup(self, code):
579
583
580 self.__profIndex = 0
584 self.__profIndex = 0
581
585
582 self.code = code
586 self.code = code
583
587
584 self.nCode = len(code)
588 self.nCode = len(code)
585 self.nBaud = len(code[0])
589 self.nBaud = len(code[0])
586
590
587 def convolutionInFreq(self, data):
591 def convolutionInFreq(self, data):
588
592
589 nchannel, ndata = data.shape
593 nchannel, ndata = data.shape
590 newcode = numpy.zeros(ndata)
594 newcode = numpy.zeros(ndata)
591 newcode[0:self.nBaud] = self.code[self.__profIndex]
595 newcode[0:self.nBaud] = self.code[self.__profIndex]
592
596
593 fft_data = numpy.fft.fft(data, axis=1)
597 fft_data = numpy.fft.fft(data, axis=1)
594 fft_code = numpy.conj(numpy.fft.fft(newcode))
598 fft_code = numpy.conj(numpy.fft.fft(newcode))
595 fft_code = fft_code.reshape(1,len(fft_code))
599 fft_code = fft_code.reshape(1,len(fft_code))
596
600
597 # conv = fft_data.copy()
601 # conv = fft_data.copy()
598 # conv.fill(0)
602 # conv.fill(0)
599
603
600 conv = fft_data*fft_code
604 conv = fft_data*fft_code
601
605
602 data = numpy.fft.ifft(conv,axis=1)
606 data = numpy.fft.ifft(conv,axis=1)
603
607
604 datadec = data[:,:-self.nBaud+1]
608 datadec = data[:,:-self.nBaud+1]
605 ndatadec = ndata - self.nBaud + 1
609 ndatadec = ndata - self.nBaud + 1
606
610
607 if self.__profIndex == self.nCode-1:
611 if self.__profIndex == self.nCode-1:
608 self.__profIndex = 0
612 self.__profIndex = 0
609 return ndatadec, datadec
613 return ndatadec, datadec
610
614
611 self.__profIndex += 1
615 self.__profIndex += 1
612
616
613 return ndatadec, datadec
617 return ndatadec, datadec
614
618
615
619
616 def convolutionInTime(self, data):
620 def convolutionInTime(self, data):
617
621
618 nchannel, ndata = data.shape
622 nchannel, ndata = data.shape
619 newcode = self.code[self.__profIndex]
623 newcode = self.code[self.__profIndex]
620 ndatadec = ndata - self.nBaud + 1
624 ndatadec = ndata - self.nBaud + 1
621
625
622 datadec = numpy.zeros((nchannel, ndatadec))
626 datadec = numpy.zeros((nchannel, ndatadec))
623
627
624 for i in range(nchannel):
628 for i in range(nchannel):
625 datadec[i,:] = numpy.correlate(data[i,:], newcode)
629 datadec[i,:] = numpy.correlate(data[i,:], newcode)
626
630
627 if self.__profIndex == self.nCode-1:
631 if self.__profIndex == self.nCode-1:
628 self.__profIndex = 0
632 self.__profIndex = 0
629 return ndatadec, datadec
633 return ndatadec, datadec
630
634
631 self.__profIndex += 1
635 self.__profIndex += 1
632
636
633 return ndatadec, datadec
637 return ndatadec, datadec
634
638
635 def run(self, dataOut, code=None, mode = 0):
639 def run(self, dataOut, code=None, mode = 0):
636
640
637 if not self.__isConfig:
641 if not self.__isConfig:
638
642
639 if code == None:
643 if code == None:
640 code = dataOut.code
644 code = dataOut.code
641
645
642 self.setup(code)
646 self.setup(code)
643 self.__isConfig = True
647 self.__isConfig = True
644
648
645 if mode == 0:
649 if mode == 0:
646 ndatadec, datadec = self.convolutionInFreq(dataOut.data)
650 ndatadec, datadec = self.convolutionInFreq(dataOut.data)
647
651
648 if mode == 1:
652 if mode == 1:
649 print "This function is not implemented"
653 print "This function is not implemented"
650 # ndatadec, datadec = self.convolutionInTime(dataOut.data)
654 # ndatadec, datadec = self.convolutionInTime(dataOut.data)
651
655
652 dataOut.data = datadec
656 dataOut.data = datadec
653
657
654 dataOut.heightList = dataOut.heightList[0:ndatadec]
658 dataOut.heightList = dataOut.heightList[0:ndatadec]
655
659
656 dataOut.flagDecodeData = True #asumo q la data no esta decodificada
660 dataOut.flagDecodeData = True #asumo q la data no esta decodificada
657
661
658 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
662 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
659
663
660
664
661 class SpectraProc(ProcessingUnit):
665 class SpectraProc(ProcessingUnit):
662
666
663 def __init__(self):
667 def __init__(self):
664
668
665 self.objectDict = {}
669 self.objectDict = {}
666 self.buffer = None
670 self.buffer = None
667 self.firstdatatime = None
671 self.firstdatatime = None
668 self.profIndex = 0
672 self.profIndex = 0
669 self.dataOut = Spectra()
673 self.dataOut = Spectra()
670
674
671 def __updateObjFromInput(self):
675 def __updateObjFromInput(self):
672
676
673 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
677 self.dataOut.radarControllerHeaderObj = self.dataIn.radarControllerHeaderObj.copy()
674 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
678 self.dataOut.systemHeaderObj = self.dataIn.systemHeaderObj.copy()
675 self.dataOut.channelList = self.dataIn.channelList
679 self.dataOut.channelList = self.dataIn.channelList
676 self.dataOut.heightList = self.dataIn.heightList
680 self.dataOut.heightList = self.dataIn.heightList
677 self.dataOut.dtype = self.dataIn.dtype
681 self.dataOut.dtype = self.dataIn.dtype
678 # self.dataOut.nHeights = self.dataIn.nHeights
682 # self.dataOut.nHeights = self.dataIn.nHeights
679 # self.dataOut.nChannels = self.dataIn.nChannels
683 # self.dataOut.nChannels = self.dataIn.nChannels
680 self.dataOut.nBaud = self.dataIn.nBaud
684 self.dataOut.nBaud = self.dataIn.nBaud
681 self.dataOut.nCode = self.dataIn.nCode
685 self.dataOut.nCode = self.dataIn.nCode
682 self.dataOut.code = self.dataIn.code
686 self.dataOut.code = self.dataIn.code
683 self.dataOut.nProfiles = self.dataOut.nFFTPoints
687 self.dataOut.nProfiles = self.dataOut.nFFTPoints
684 # self.dataOut.channelIndexList = self.dataIn.channelIndexList
688 # self.dataOut.channelIndexList = self.dataIn.channelIndexList
685 self.dataOut.flagTimeBlock = self.dataIn.flagTimeBlock
689 self.dataOut.flagTimeBlock = self.dataIn.flagTimeBlock
686 self.dataOut.utctime = self.firstdatatime
690 self.dataOut.utctime = self.firstdatatime
687 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData #asumo q la data esta decodificada
691 self.dataOut.flagDecodeData = self.dataIn.flagDecodeData #asumo q la data esta decodificada
688 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData #asumo q la data esta sin flip
692 self.dataOut.flagDeflipData = self.dataIn.flagDeflipData #asumo q la data esta sin flip
689 self.dataOut.flagShiftFFT = self.dataIn.flagShiftFFT
693 self.dataOut.flagShiftFFT = self.dataIn.flagShiftFFT
690 self.dataOut.nCohInt = self.dataIn.nCohInt
694 self.dataOut.nCohInt = self.dataIn.nCohInt
691 self.dataOut.nIncohInt = 1
695 self.dataOut.nIncohInt = 1
692 self.dataOut.ippSeconds = self.dataIn.ippSeconds
696 self.dataOut.ippSeconds = self.dataIn.ippSeconds
693
697
694 self.dataOut.timeInterval = self.dataIn.timeInterval*self.dataOut.nFFTPoints*self.dataOut.nIncohInt
698 self.dataOut.timeInterval = self.dataIn.timeInterval*self.dataOut.nFFTPoints*self.dataOut.nIncohInt
695
699
696 def __getFft(self):
700 def __getFft(self):
697 """
701 """
698 Convierte valores de Voltaje a Spectra
702 Convierte valores de Voltaje a Spectra
699
703
700 Affected:
704 Affected:
701 self.dataOut.data_spc
705 self.dataOut.data_spc
702 self.dataOut.data_cspc
706 self.dataOut.data_cspc
703 self.dataOut.data_dc
707 self.dataOut.data_dc
704 self.dataOut.heightList
708 self.dataOut.heightList
705 self.profIndex
709 self.profIndex
706 self.buffer
710 self.buffer
707 self.dataOut.flagNoData
711 self.dataOut.flagNoData
708 """
712 """
709 fft_volt = numpy.fft.fft(self.buffer,axis=1)
713 fft_volt = numpy.fft.fft(self.buffer,axis=1)
710 dc = fft_volt[:,0,:]
714 dc = fft_volt[:,0,:]
711
715
712 #calculo de self-spectra
716 #calculo de self-spectra
713 fft_volt = numpy.fft.fftshift(fft_volt,axes=(1,))
717 fft_volt = numpy.fft.fftshift(fft_volt,axes=(1,))
714 spc = fft_volt * numpy.conjugate(fft_volt)
718 spc = fft_volt * numpy.conjugate(fft_volt)
715 spc = spc.real
719 spc = spc.real
716
720
717 blocksize = 0
721 blocksize = 0
718 blocksize += dc.size
722 blocksize += dc.size
719 blocksize += spc.size
723 blocksize += spc.size
720
724
721 cspc = None
725 cspc = None
722 pairIndex = 0
726 pairIndex = 0
723 if self.dataOut.pairsList != None:
727 if self.dataOut.pairsList != None:
724 #calculo de cross-spectra
728 #calculo de cross-spectra
725 cspc = numpy.zeros((self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
729 cspc = numpy.zeros((self.dataOut.nPairs, self.dataOut.nFFTPoints, self.dataOut.nHeights), dtype='complex')
726 for pair in self.dataOut.pairsList:
730 for pair in self.dataOut.pairsList:
727 cspc[pairIndex,:,:] = fft_volt[pair[0],:,:] * numpy.conjugate(fft_volt[pair[1],:,:])
731 cspc[pairIndex,:,:] = fft_volt[pair[0],:,:] * numpy.conjugate(fft_volt[pair[1],:,:])
728 pairIndex += 1
732 pairIndex += 1
729 blocksize += cspc.size
733 blocksize += cspc.size
730
734
731 self.dataOut.data_spc = spc
735 self.dataOut.data_spc = spc
732 self.dataOut.data_cspc = cspc
736 self.dataOut.data_cspc = cspc
733 self.dataOut.data_dc = dc
737 self.dataOut.data_dc = dc
734 self.dataOut.blockSize = blocksize
738 self.dataOut.blockSize = blocksize
735
739
736 def init(self, nFFTPoints=None, pairsList=None):
740 def init(self, nFFTPoints=None, pairsList=None):
737
741
738 self.dataOut.flagNoData = True
742 self.dataOut.flagNoData = True
739
743
740 if self.dataIn.type == "Spectra":
744 if self.dataIn.type == "Spectra":
741 self.dataOut.copy(self.dataIn)
745 self.dataOut.copy(self.dataIn)
742 return
746 return
743
747
744 if self.dataIn.type == "Voltage":
748 if self.dataIn.type == "Voltage":
745
749
746 if nFFTPoints == None:
750 if nFFTPoints == None:
747 raise ValueError, "This SpectraProc.init() need nFFTPoints input variable"
751 raise ValueError, "This SpectraProc.init() need nFFTPoints input variable"
748
752
749 if pairsList == None:
753 if pairsList == None:
750 nPairs = 0
754 nPairs = 0
751 else:
755 else:
752 nPairs = len(pairsList)
756 nPairs = len(pairsList)
753
757
754 self.dataOut.nFFTPoints = nFFTPoints
758 self.dataOut.nFFTPoints = nFFTPoints
755 self.dataOut.pairsList = pairsList
759 self.dataOut.pairsList = pairsList
756 self.dataOut.nPairs = nPairs
760 self.dataOut.nPairs = nPairs
757
761
758 if self.buffer == None:
762 if self.buffer == None:
759 self.buffer = numpy.zeros((self.dataIn.nChannels,
763 self.buffer = numpy.zeros((self.dataIn.nChannels,
760 self.dataOut.nFFTPoints,
764 self.dataOut.nFFTPoints,
761 self.dataIn.nHeights),
765 self.dataIn.nHeights),
762 dtype='complex')
766 dtype='complex')
763
767
764
768
765 self.buffer[:,self.profIndex,:] = self.dataIn.data.copy()
769 self.buffer[:,self.profIndex,:] = self.dataIn.data.copy()
766 self.profIndex += 1
770 self.profIndex += 1
767
771
768 if self.firstdatatime == None:
772 if self.firstdatatime == None:
769 self.firstdatatime = self.dataIn.utctime
773 self.firstdatatime = self.dataIn.utctime
770
774
771 if self.profIndex == self.dataOut.nFFTPoints:
775 if self.profIndex == self.dataOut.nFFTPoints:
772 self.__updateObjFromInput()
776 self.__updateObjFromInput()
773 self.__getFft()
777 self.__getFft()
774
778
775 self.dataOut.flagNoData = False
779 self.dataOut.flagNoData = False
776
780
777 self.buffer = None
781 self.buffer = None
778 self.firstdatatime = None
782 self.firstdatatime = None
779 self.profIndex = 0
783 self.profIndex = 0
780
784
781 return
785 return
782
786
783 raise ValuError, "The type object %s is not valid"%(self.dataIn.type)
787 raise ValuError, "The type object %s is not valid"%(self.dataIn.type)
784
788
785 def selectChannels(self, channelList):
789 def selectChannels(self, channelList):
786
790
787 channelIndexList = []
791 channelIndexList = []
788
792
789 for channel in channelList:
793 for channel in channelList:
790 index = self.dataOut.channelList.index(channel)
794 index = self.dataOut.channelList.index(channel)
791 channelIndexList.append(index)
795 channelIndexList.append(index)
792
796
793 self.selectChannelsByIndex(channelIndexList)
797 self.selectChannelsByIndex(channelIndexList)
794
798
795 def selectChannelsByIndex(self, channelIndexList):
799 def selectChannelsByIndex(self, channelIndexList):
796 """
800 """
797 Selecciona un bloque de datos en base a canales segun el channelIndexList
801 Selecciona un bloque de datos en base a canales segun el channelIndexList
798
802
799 Input:
803 Input:
800 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
804 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
801
805
802 Affected:
806 Affected:
803 self.dataOut.data_spc
807 self.dataOut.data_spc
804 self.dataOut.channelIndexList
808 self.dataOut.channelIndexList
805 self.dataOut.nChannels
809 self.dataOut.nChannels
806
810
807 Return:
811 Return:
808 None
812 None
809 """
813 """
810
814
811 for channelIndex in channelIndexList:
815 for channelIndex in channelIndexList:
812 if channelIndex not in self.dataOut.channelIndexList:
816 if channelIndex not in self.dataOut.channelIndexList:
813 print channelIndexList
817 print channelIndexList
814 raise ValueError, "The value %d in channelIndexList is not valid" %channelIndex
818 raise ValueError, "The value %d in channelIndexList is not valid" %channelIndex
815
819
816 nChannels = len(channelIndexList)
820 nChannels = len(channelIndexList)
817
821
818 data_spc = self.dataOut.data_spc[channelIndexList,:]
822 data_spc = self.dataOut.data_spc[channelIndexList,:]
819
823
820 self.dataOut.data_spc = data_spc
824 self.dataOut.data_spc = data_spc
821 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
825 self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
822 # self.dataOut.nChannels = nChannels
826 # self.dataOut.nChannels = nChannels
823
827
824 return 1
828 return 1
825
829
826
830
827 class IncohInt(Operation):
831 class IncohInt(Operation):
828
832
829
833
830 __profIndex = 0
834 __profIndex = 0
831 __withOverapping = False
835 __withOverapping = False
832
836
833 __byTime = False
837 __byTime = False
834 __initime = None
838 __initime = None
835 __lastdatatime = None
839 __lastdatatime = None
836 __integrationtime = None
840 __integrationtime = None
837
841
838 __buffer_spc = None
842 __buffer_spc = None
839 __buffer_cspc = None
843 __buffer_cspc = None
840 __buffer_dc = None
844 __buffer_dc = None
841
845
842 __dataReady = False
846 __dataReady = False
843
847
844 n = None
848 n = None
845
849
846
850
847 def __init__(self):
851 def __init__(self):
848
852
849 self.__isConfig = False
853 self.__isConfig = False
850
854
851 def setup(self, n=None, timeInterval=None, overlapping=False):
855 def setup(self, n=None, timeInterval=None, overlapping=False):
852 """
856 """
853 Set the parameters of the integration class.
857 Set the parameters of the integration class.
854
858
855 Inputs:
859 Inputs:
856
860
857 n : Number of coherent integrations
861 n : Number of coherent integrations
858 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
862 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
859 overlapping :
863 overlapping :
860
864
861 """
865 """
862
866
863 self.__initime = None
867 self.__initime = None
864 self.__lastdatatime = 0
868 self.__lastdatatime = 0
865 self.__buffer_spc = None
869 self.__buffer_spc = None
866 self.__buffer_cspc = None
870 self.__buffer_cspc = None
867 self.__buffer_dc = None
871 self.__buffer_dc = None
868 self.__dataReady = False
872 self.__dataReady = False
869
873
870
874
871 if n == None and timeInterval == None:
875 if n == None and timeInterval == None:
872 raise ValueError, "n or timeInterval should be specified ..."
876 raise ValueError, "n or timeInterval should be specified ..."
873
877
874 if n != None:
878 if n != None:
875 self.n = n
879 self.n = n
876 self.__byTime = False
880 self.__byTime = False
877 else:
881 else:
878 self.__integrationtime = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line
882 self.__integrationtime = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line
879 self.n = 9999
883 self.n = 9999
880 self.__byTime = True
884 self.__byTime = True
881
885
882 if overlapping:
886 if overlapping:
883 self.__withOverapping = True
887 self.__withOverapping = True
884 else:
888 else:
885 self.__withOverapping = False
889 self.__withOverapping = False
886 self.__buffer_spc = 0
890 self.__buffer_spc = 0
887 self.__buffer_cspc = 0
891 self.__buffer_cspc = 0
888 self.__buffer_dc = 0
892 self.__buffer_dc = 0
889
893
890 self.__profIndex = 0
894 self.__profIndex = 0
891
895
892 def putData(self, data_spc, data_cspc, data_dc):
896 def putData(self, data_spc, data_cspc, data_dc):
893
897
894 """
898 """
895 Add a profile to the __buffer_spc and increase in one the __profileIndex
899 Add a profile to the __buffer_spc and increase in one the __profileIndex
896
900
897 """
901 """
898
902
899 if not self.__withOverapping:
903 if not self.__withOverapping:
900 self.__buffer_spc += data_spc
904 self.__buffer_spc += data_spc
901
905
902 if data_cspc == None:
906 if data_cspc == None:
903 self.__buffer_cspc = None
907 self.__buffer_cspc = None
904 else:
908 else:
905 self.__buffer_cspc += data_cspc
909 self.__buffer_cspc += data_cspc
906
910
907 if data_dc == None:
911 if data_dc == None:
908 self.__buffer_dc = None
912 self.__buffer_dc = None
909 else:
913 else:
910 self.__buffer_dc += data_dc
914 self.__buffer_dc += data_dc
911
915
912 self.__profIndex += 1
916 self.__profIndex += 1
913 return
917 return
914
918
915 #Overlapping data
919 #Overlapping data
916 nChannels, nFFTPoints, nHeis = data_spc.shape
920 nChannels, nFFTPoints, nHeis = data_spc.shape
917 data_spc = numpy.reshape(data_spc, (1, nChannels, nFFTPoints, nHeis))
921 data_spc = numpy.reshape(data_spc, (1, nChannels, nFFTPoints, nHeis))
918 if data_cspc != None:
922 if data_cspc != None:
919 data_cspc = numpy.reshape(data_cspc, (1, -1, nFFTPoints, nHeis))
923 data_cspc = numpy.reshape(data_cspc, (1, -1, nFFTPoints, nHeis))
920 if data_dc != None:
924 if data_dc != None:
921 data_dc = numpy.reshape(data_dc, (1, -1, nHeis))
925 data_dc = numpy.reshape(data_dc, (1, -1, nHeis))
922
926
923 #If the buffer is empty then it takes the data value
927 #If the buffer is empty then it takes the data value
924 if self.__buffer_spc == None:
928 if self.__buffer_spc == None:
925 self.__buffer_spc = data_spc
929 self.__buffer_spc = data_spc
926
930
927 if data_cspc == None:
931 if data_cspc == None:
928 self.__buffer_cspc = None
932 self.__buffer_cspc = None
929 else:
933 else:
930 self.__buffer_cspc += data_cspc
934 self.__buffer_cspc += data_cspc
931
935
932 if data_dc == None:
936 if data_dc == None:
933 self.__buffer_dc = None
937 self.__buffer_dc = None
934 else:
938 else:
935 self.__buffer_dc += data_dc
939 self.__buffer_dc += data_dc
936
940
937 self.__profIndex += 1
941 self.__profIndex += 1
938 return
942 return
939
943
940 #If the buffer length is lower than n then stakcing the data value
944 #If the buffer length is lower than n then stakcing the data value
941 if self.__profIndex < self.n:
945 if self.__profIndex < self.n:
942 self.__buffer_spc = numpy.vstack((self.__buffer_spc, data_spc))
946 self.__buffer_spc = numpy.vstack((self.__buffer_spc, data_spc))
943
947
944 if data_cspc != None:
948 if data_cspc != None:
945 self.__buffer_cspc = numpy.vstack((self.__buffer_cspc, data_cspc))
949 self.__buffer_cspc = numpy.vstack((self.__buffer_cspc, data_cspc))
946
950
947 if data_dc != None:
951 if data_dc != None:
948 self.__buffer_dc = numpy.vstack((self.__buffer_dc, data_dc))
952 self.__buffer_dc = numpy.vstack((self.__buffer_dc, data_dc))
949
953
950 self.__profIndex += 1
954 self.__profIndex += 1
951 return
955 return
952
956
953 #If the buffer length is equal to n then replacing the last buffer value with the data value
957 #If the buffer length is equal to n then replacing the last buffer value with the data value
954 self.__buffer_spc = numpy.roll(self.__buffer_spc, -1, axis=0)
958 self.__buffer_spc = numpy.roll(self.__buffer_spc, -1, axis=0)
955 self.__buffer_spc[self.n-1] = data_spc
959 self.__buffer_spc[self.n-1] = data_spc
956
960
957 if data_cspc != None:
961 if data_cspc != None:
958 self.__buffer_cspc = numpy.roll(self.__buffer_cspc, -1, axis=0)
962 self.__buffer_cspc = numpy.roll(self.__buffer_cspc, -1, axis=0)
959 self.__buffer_cspc[self.n-1] = data_cspc
963 self.__buffer_cspc[self.n-1] = data_cspc
960
964
961 if data_dc != None:
965 if data_dc != None:
962 self.__buffer_dc = numpy.roll(self.__buffer_dc, -1, axis=0)
966 self.__buffer_dc = numpy.roll(self.__buffer_dc, -1, axis=0)
963 self.__buffer_dc[self.n-1] = data_dc
967 self.__buffer_dc[self.n-1] = data_dc
964
968
965 self.__profIndex = self.n
969 self.__profIndex = self.n
966 return
970 return
967
971
968
972
969 def pushData(self):
973 def pushData(self):
970 """
974 """
971 Return the sum of the last profiles and the profiles used in the sum.
975 Return the sum of the last profiles and the profiles used in the sum.
972
976
973 Affected:
977 Affected:
974
978
975 self.__profileIndex
979 self.__profileIndex
976
980
977 """
981 """
978 data_spc = None
982 data_spc = None
979 data_cspc = None
983 data_cspc = None
980 data_dc = None
984 data_dc = None
981
985
982 if not self.__withOverapping:
986 if not self.__withOverapping:
983 data_spc = self.__buffer_spc
987 data_spc = self.__buffer_spc
984 data_cspc = self.__buffer_cspc
988 data_cspc = self.__buffer_cspc
985 data_dc = self.__buffer_dc
989 data_dc = self.__buffer_dc
986
990
987 n = self.__profIndex
991 n = self.__profIndex
988
992
989 self.__buffer_spc = 0
993 self.__buffer_spc = 0
990 self.__buffer_cspc = 0
994 self.__buffer_cspc = 0
991 self.__buffer_dc = 0
995 self.__buffer_dc = 0
992 self.__profIndex = 0
996 self.__profIndex = 0
993
997
994 return data_spc, data_cspc, data_dc, n
998 return data_spc, data_cspc, data_dc, n
995
999
996 #Integration with Overlapping
1000 #Integration with Overlapping
997 data_spc = numpy.sum(self.__buffer_spc, axis=0)
1001 data_spc = numpy.sum(self.__buffer_spc, axis=0)
998
1002
999 if self.__buffer_cspc != None:
1003 if self.__buffer_cspc != None:
1000 data_cspc = numpy.sum(self.__buffer_cspc, axis=0)
1004 data_cspc = numpy.sum(self.__buffer_cspc, axis=0)
1001
1005
1002 if self.__buffer_dc != None:
1006 if self.__buffer_dc != None:
1003 data_dc = numpy.sum(self.__buffer_dc, axis=0)
1007 data_dc = numpy.sum(self.__buffer_dc, axis=0)
1004
1008
1005 n = self.__profIndex
1009 n = self.__profIndex
1006
1010
1007 return data_spc, data_cspc, data_dc, n
1011 return data_spc, data_cspc, data_dc, n
1008
1012
1009 def byProfiles(self, *args):
1013 def byProfiles(self, *args):
1010
1014
1011 self.__dataReady = False
1015 self.__dataReady = False
1012 avgdata_spc = None
1016 avgdata_spc = None
1013 avgdata_cspc = None
1017 avgdata_cspc = None
1014 avgdata_dc = None
1018 avgdata_dc = None
1015 n = None
1019 n = None
1016
1020
1017 self.putData(*args)
1021 self.putData(*args)
1018
1022
1019 if self.__profIndex == self.n:
1023 if self.__profIndex == self.n:
1020
1024
1021 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1025 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1022 self.__dataReady = True
1026 self.__dataReady = True
1023
1027
1024 return avgdata_spc, avgdata_cspc, avgdata_dc
1028 return avgdata_spc, avgdata_cspc, avgdata_dc
1025
1029
1026 def byTime(self, datatime, *args):
1030 def byTime(self, datatime, *args):
1027
1031
1028 self.__dataReady = False
1032 self.__dataReady = False
1029 avgdata_spc = None
1033 avgdata_spc = None
1030 avgdata_cspc = None
1034 avgdata_cspc = None
1031 avgdata_dc = None
1035 avgdata_dc = None
1032 n = None
1036 n = None
1033
1037
1034 self.putData(*args)
1038 self.putData(*args)
1035
1039
1036 if (datatime - self.__initime) >= self.__integrationtime:
1040 if (datatime - self.__initime) >= self.__integrationtime:
1037 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1041 avgdata_spc, avgdata_cspc, avgdata_dc, n = self.pushData()
1038 self.n = n
1042 self.n = n
1039 self.__dataReady = True
1043 self.__dataReady = True
1040
1044
1041 return avgdata_spc, avgdata_cspc, avgdata_dc
1045 return avgdata_spc, avgdata_cspc, avgdata_dc
1042
1046
1043 def integrate(self, datatime, *args):
1047 def integrate(self, datatime, *args):
1044
1048
1045 if self.__initime == None:
1049 if self.__initime == None:
1046 self.__initime = datatime
1050 self.__initime = datatime
1047
1051
1048 if self.__byTime:
1052 if self.__byTime:
1049 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(datatime, *args)
1053 avgdata_spc, avgdata_cspc, avgdata_dc = self.byTime(datatime, *args)
1050 else:
1054 else:
1051 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
1055 avgdata_spc, avgdata_cspc, avgdata_dc = self.byProfiles(*args)
1052
1056
1053 self.__lastdatatime = datatime
1057 self.__lastdatatime = datatime
1054
1058
1055 if avgdata_spc == None:
1059 if avgdata_spc == None:
1056 return None, None, None, None
1060 return None, None, None, None
1057
1061
1058 avgdatatime = self.__initime
1062 avgdatatime = self.__initime
1059
1063
1060 deltatime = datatime -self.__lastdatatime
1064 deltatime = datatime -self.__lastdatatime
1061
1065
1062 if not self.__withOverapping:
1066 if not self.__withOverapping:
1063 self.__initime = datatime
1067 self.__initime = datatime
1064 else:
1068 else:
1065 self.__initime += deltatime
1069 self.__initime += deltatime
1066
1070
1067 return avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc
1071 return avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc
1068
1072
1069 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
1073 def run(self, dataOut, n=None, timeInterval=None, overlapping=False):
1070
1074
1071 if not self.__isConfig:
1075 if not self.__isConfig:
1072 self.setup(n, timeInterval, overlapping)
1076 self.setup(n, timeInterval, overlapping)
1073 self.__isConfig = True
1077 self.__isConfig = True
1074
1078
1075 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
1079 avgdatatime, avgdata_spc, avgdata_cspc, avgdata_dc = self.integrate(dataOut.utctime,
1076 dataOut.data_spc,
1080 dataOut.data_spc,
1077 dataOut.data_cspc,
1081 dataOut.data_cspc,
1078 dataOut.data_dc)
1082 dataOut.data_dc)
1079
1083
1080 # dataOut.timeInterval *= n
1084 # dataOut.timeInterval *= n
1081 dataOut.flagNoData = True
1085 dataOut.flagNoData = True
1082
1086
1083 if self.__dataReady:
1087 if self.__dataReady:
1084
1088
1085 dataOut.data_spc = avgdata_spc / self.n
1089 dataOut.data_spc = avgdata_spc / self.n
1086 dataOut.data_cspc = avgdata_cspc / self.n
1090 dataOut.data_cspc = avgdata_cspc / self.n
1087 dataOut.data_dc = avgdata_dc / self.n
1091 dataOut.data_dc = avgdata_dc / self.n
1088
1092
1089 dataOut.nIncohInt *= self.n
1093 dataOut.nIncohInt *= self.n
1090 dataOut.utctime = avgdatatime
1094 dataOut.utctime = avgdatatime
1091 dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt * dataOut.nIncohInt * dataOut.nFFTPoints
1095 dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt * dataOut.nIncohInt * dataOut.nFFTPoints
1092 dataOut.flagNoData = False
1096 dataOut.flagNoData = False
1093
1097
1094 class ProfileSelector(Operation):
1098 class ProfileSelector(Operation):
1095
1099
1096 profileIndex = None
1100 profileIndex = None
1097 # Tamanho total de los perfiles
1101 # Tamanho total de los perfiles
1098 nProfiles = None
1102 nProfiles = None
1099
1103
1100 def __init__(self):
1104 def __init__(self):
1101
1105
1102 self.profileIndex = 0
1106 self.profileIndex = 0
1103
1107
1104 def incIndex(self):
1108 def incIndex(self):
1105 self.profileIndex += 1
1109 self.profileIndex += 1
1106
1110
1107 if self.profileIndex >= self.nProfiles:
1111 if self.profileIndex >= self.nProfiles:
1108 self.profileIndex = 0
1112 self.profileIndex = 0
1109
1113
1110 def isProfileInRange(self, minIndex, maxIndex):
1114 def isProfileInRange(self, minIndex, maxIndex):
1111
1115
1112 if self.profileIndex < minIndex:
1116 if self.profileIndex < minIndex:
1113 return False
1117 return False
1114
1118
1115 if self.profileIndex > maxIndex:
1119 if self.profileIndex > maxIndex:
1116 return False
1120 return False
1117
1121
1118 return True
1122 return True
1119
1123
1120 def isProfileInList(self, profileList):
1124 def isProfileInList(self, profileList):
1121
1125
1122 if self.profileIndex not in profileList:
1126 if self.profileIndex not in profileList:
1123 return False
1127 return False
1124
1128
1125 return True
1129 return True
1126
1130
1127 def run(self, dataOut, profileList=None, profileRangeList=None):
1131 def run(self, dataOut, profileList=None, profileRangeList=None):
1128
1132
1129 dataOut.flagNoData = True
1133 dataOut.flagNoData = True
1130 self.nProfiles = dataOut.nProfiles
1134 self.nProfiles = dataOut.nProfiles
1131
1135
1132 if profileList != None:
1136 if profileList != None:
1133 if self.isProfileInList(profileList):
1137 if self.isProfileInList(profileList):
1134 dataOut.flagNoData = False
1138 dataOut.flagNoData = False
1135
1139
1136 self.incIndex()
1140 self.incIndex()
1137 return 1
1141 return 1
1138
1142
1139
1143
1140 elif profileRangeList != None:
1144 elif profileRangeList != None:
1141 minIndex = profileRangeList[0]
1145 minIndex = profileRangeList[0]
1142 maxIndex = profileRangeList[1]
1146 maxIndex = profileRangeList[1]
1143 if self.isProfileInRange(minIndex, maxIndex):
1147 if self.isProfileInRange(minIndex, maxIndex):
1144 dataOut.flagNoData = False
1148 dataOut.flagNoData = False
1145
1149
1146 self.incIndex()
1150 self.incIndex()
1147 return 1
1151 return 1
1148
1152
1149 else:
1153 else:
1150 raise ValueError, "ProfileSelector needs profileList or profileRangeList"
1154 raise ValueError, "ProfileSelector needs profileList or profileRangeList"
1151
1155
1152 return 0
1156 return 0
1153
1157
General Comments 0
You need to be logged in to leave comments. Login now