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