##// END OF EJS Templates
Agregando funciones para guardar graficos del tipo Voltage
Daniel Valdez -
r113:1c6a8ba2204a
parent child
Show More
@@ -1,1010 +1,1018
1 """
1 """
2 Created on Feb 7, 2012
2 Created on Feb 7, 2012
3
3
4 @autor $Author$
4 @autor $Author$
5 @version $Id$
5 @version $Id$
6
6
7 """
7 """
8 import os
8 import os
9 import numpy
9 import numpy
10 import sys
10 import sys
11 import time
11 import time
12 import datetime
12 import datetime
13 import time
13 import time
14 import plplot
14 import plplot
15
15
16
16
17 def cmap1_init(colormap="gray"):
17 def cmap1_init(colormap="gray"):
18
18
19 if colormap == None:
19 if colormap == None:
20 return
20 return
21
21
22 ncolor = None
22 ncolor = None
23 rgb_lvl = None
23 rgb_lvl = None
24
24
25 # Routine for defining a specific color map 1 in HLS space.
25 # Routine for defining a specific color map 1 in HLS space.
26 # if gray is true, use basic grayscale variation from half-dark to light.
26 # if gray is true, use basic grayscale variation from half-dark to light.
27 # otherwise use false color variation from blue (240 deg) to red (360 deg).
27 # otherwise use false color variation from blue (240 deg) to red (360 deg).
28
28
29 # Independent variable of control points.
29 # Independent variable of control points.
30 i = numpy.array((0., 1.))
30 i = numpy.array((0., 1.))
31 if colormap=="gray":
31 if colormap=="gray":
32 ncolor = 256
32 ncolor = 256
33 # Hue for control points. Doesn't matter since saturation is zero.
33 # Hue for control points. Doesn't matter since saturation is zero.
34 h = numpy.array((0., 0.))
34 h = numpy.array((0., 0.))
35 # Lightness ranging from half-dark (for interest) to light.
35 # Lightness ranging from half-dark (for interest) to light.
36 l = numpy.array((0.5, 1.))
36 l = numpy.array((0.5, 1.))
37 # Gray scale has zero saturation
37 # Gray scale has zero saturation
38 s = numpy.array((0., 0.))
38 s = numpy.array((0., 0.))
39
39
40 # number of cmap1 colours is 256 in this case.
40 # number of cmap1 colours is 256 in this case.
41 plplot.plscmap1n(ncolor)
41 plplot.plscmap1n(ncolor)
42 # Interpolate between control points to set up cmap1.
42 # Interpolate between control points to set up cmap1.
43 plplot.plscmap1l(0, i, h, l, s)
43 plplot.plscmap1l(0, i, h, l, s)
44
44
45 return None
45 return None
46
46
47 if colormap == 'jet':
47 if colormap == 'jet':
48 ncolor = 256
48 ncolor = 256
49 pos = numpy.zeros((ncolor))
49 pos = numpy.zeros((ncolor))
50 r = numpy.zeros((ncolor))
50 r = numpy.zeros((ncolor))
51 g = numpy.zeros((ncolor))
51 g = numpy.zeros((ncolor))
52 b = numpy.zeros((ncolor))
52 b = numpy.zeros((ncolor))
53
53
54 for i in range(ncolor):
54 for i in range(ncolor):
55 if(i <= 35.0/100*(ncolor-1)): rf = 0.0
55 if(i <= 35.0/100*(ncolor-1)): rf = 0.0
56 elif (i <= 66.0/100*(ncolor-1)): rf = (100.0/31)*i/(ncolor-1) - 35.0/31
56 elif (i <= 66.0/100*(ncolor-1)): rf = (100.0/31)*i/(ncolor-1) - 35.0/31
57 elif (i <= 89.0/100*(ncolor-1)): rf = 1.0
57 elif (i <= 89.0/100*(ncolor-1)): rf = 1.0
58 else: rf = (-100.0/22)*i/(ncolor-1) + 111.0/22
58 else: rf = (-100.0/22)*i/(ncolor-1) + 111.0/22
59
59
60 if(i <= 12.0/100*(ncolor-1)): gf = 0.0
60 if(i <= 12.0/100*(ncolor-1)): gf = 0.0
61 elif(i <= 38.0/100*(ncolor-1)): gf = (100.0/26)*i/(ncolor-1) - 12.0/26
61 elif(i <= 38.0/100*(ncolor-1)): gf = (100.0/26)*i/(ncolor-1) - 12.0/26
62 elif(i <= 64.0/100*(ncolor-1)): gf = 1.0
62 elif(i <= 64.0/100*(ncolor-1)): gf = 1.0
63 elif(i <= 91.0/100*(ncolor-1)): gf = (-100.0/27)*i/(ncolor-1) + 91.0/27
63 elif(i <= 91.0/100*(ncolor-1)): gf = (-100.0/27)*i/(ncolor-1) + 91.0/27
64 else: gf = 0.0
64 else: gf = 0.0
65
65
66 if(i <= 11.0/100*(ncolor-1)): bf = (50.0/11)*i/(ncolor-1) + 0.5
66 if(i <= 11.0/100*(ncolor-1)): bf = (50.0/11)*i/(ncolor-1) + 0.5
67 elif(i <= 34.0/100*(ncolor-1)): bf = 1.0
67 elif(i <= 34.0/100*(ncolor-1)): bf = 1.0
68 elif(i <= 65.0/100*(ncolor-1)): bf = (-100.0/31)*i/(ncolor-1) + 65.0/31
68 elif(i <= 65.0/100*(ncolor-1)): bf = (-100.0/31)*i/(ncolor-1) + 65.0/31
69 else: bf = 0
69 else: bf = 0
70
70
71 r[i] = rf
71 r[i] = rf
72 g[i] = gf
72 g[i] = gf
73 b[i] = bf
73 b[i] = bf
74
74
75 pos[i] = float(i)/float(ncolor-1)
75 pos[i] = float(i)/float(ncolor-1)
76
76
77
77
78 plplot.plscmap1n(ncolor)
78 plplot.plscmap1n(ncolor)
79 plplot.plscmap1l(1, pos, r, g, b)
79 plplot.plscmap1l(1, pos, r, g, b)
80
80
81
81
82
82
83 if colormap=="br_green":
83 if colormap=="br_green":
84 ncolor = 256
84 ncolor = 256
85 # Hue ranges from blue (240 deg) to red (0 or 360 deg)
85 # Hue ranges from blue (240 deg) to red (0 or 360 deg)
86 h = numpy.array((240., 0.))
86 h = numpy.array((240., 0.))
87 # Lightness and saturation are constant (values taken from C example).
87 # Lightness and saturation are constant (values taken from C example).
88 l = numpy.array((0.6, 0.6))
88 l = numpy.array((0.6, 0.6))
89 s = numpy.array((0.8, 0.8))
89 s = numpy.array((0.8, 0.8))
90
90
91 # number of cmap1 colours is 256 in this case.
91 # number of cmap1 colours is 256 in this case.
92 plplot.plscmap1n(ncolor)
92 plplot.plscmap1n(ncolor)
93 # Interpolate between control points to set up cmap1.
93 # Interpolate between control points to set up cmap1.
94 plplot.plscmap1l(0, i, h, l, s)
94 plplot.plscmap1l(0, i, h, l, s)
95
95
96 return None
96 return None
97
97
98 if colormap=="tricolor":
98 if colormap=="tricolor":
99 ncolor = 3
99 ncolor = 3
100 # Hue ranges from blue (240 deg) to red (0 or 360 deg)
100 # Hue ranges from blue (240 deg) to red (0 or 360 deg)
101 h = numpy.array((240., 0.))
101 h = numpy.array((240., 0.))
102 # Lightness and saturation are constant (values taken from C example).
102 # Lightness and saturation are constant (values taken from C example).
103 l = numpy.array((0.6, 0.6))
103 l = numpy.array((0.6, 0.6))
104 s = numpy.array((0.8, 0.8))
104 s = numpy.array((0.8, 0.8))
105
105
106 # number of cmap1 colours is 256 in this case.
106 # number of cmap1 colours is 256 in this case.
107 plplot.plscmap1n(ncolor)
107 plplot.plscmap1n(ncolor)
108 # Interpolate between control points to set up cmap1.
108 # Interpolate between control points to set up cmap1.
109 plplot.plscmap1l(0, i, h, l, s)
109 plplot.plscmap1l(0, i, h, l, s)
110
110
111 return None
111 return None
112
112
113 if colormap == 'rgb' or colormap == 'rgb666':
113 if colormap == 'rgb' or colormap == 'rgb666':
114
114
115 color_sz = 6
115 color_sz = 6
116 ncolor = color_sz*color_sz*color_sz
116 ncolor = color_sz*color_sz*color_sz
117 pos = numpy.zeros((ncolor))
117 pos = numpy.zeros((ncolor))
118 r = numpy.zeros((ncolor))
118 r = numpy.zeros((ncolor))
119 g = numpy.zeros((ncolor))
119 g = numpy.zeros((ncolor))
120 b = numpy.zeros((ncolor))
120 b = numpy.zeros((ncolor))
121 ind = 0
121 ind = 0
122 for ri in range(color_sz):
122 for ri in range(color_sz):
123 for gi in range(color_sz):
123 for gi in range(color_sz):
124 for bi in range(color_sz):
124 for bi in range(color_sz):
125 r[ind] = ri/(color_sz-1.0)
125 r[ind] = ri/(color_sz-1.0)
126 g[ind] = gi/(color_sz-1.0)
126 g[ind] = gi/(color_sz-1.0)
127 b[ind] = bi/(color_sz-1.0)
127 b[ind] = bi/(color_sz-1.0)
128 pos[ind] = ind/(ncolor-1.0)
128 pos[ind] = ind/(ncolor-1.0)
129 ind += 1
129 ind += 1
130 rgb_lvl = [6,6,6] #Levels for RGB colors
130 rgb_lvl = [6,6,6] #Levels for RGB colors
131
131
132 if colormap == 'rgb676':
132 if colormap == 'rgb676':
133 ncolor = 6*7*6
133 ncolor = 6*7*6
134 pos = numpy.zeros((ncolor))
134 pos = numpy.zeros((ncolor))
135 r = numpy.zeros((ncolor))
135 r = numpy.zeros((ncolor))
136 g = numpy.zeros((ncolor))
136 g = numpy.zeros((ncolor))
137 b = numpy.zeros((ncolor))
137 b = numpy.zeros((ncolor))
138 ind = 0
138 ind = 0
139 for ri in range(8):
139 for ri in range(8):
140 for gi in range(8):
140 for gi in range(8):
141 for bi in range(4):
141 for bi in range(4):
142 r[ind] = ri/(6-1.0)
142 r[ind] = ri/(6-1.0)
143 g[ind] = gi/(7-1.0)
143 g[ind] = gi/(7-1.0)
144 b[ind] = bi/(6-1.0)
144 b[ind] = bi/(6-1.0)
145 pos[ind] = ind/(ncolor-1.0)
145 pos[ind] = ind/(ncolor-1.0)
146 ind += 1
146 ind += 1
147 rgb_lvl = [6,7,6] #Levels for RGB colors
147 rgb_lvl = [6,7,6] #Levels for RGB colors
148
148
149 if colormap == 'rgb685':
149 if colormap == 'rgb685':
150 ncolor = 6*8*5
150 ncolor = 6*8*5
151 pos = numpy.zeros((ncolor))
151 pos = numpy.zeros((ncolor))
152 r = numpy.zeros((ncolor))
152 r = numpy.zeros((ncolor))
153 g = numpy.zeros((ncolor))
153 g = numpy.zeros((ncolor))
154 b = numpy.zeros((ncolor))
154 b = numpy.zeros((ncolor))
155 ind = 0
155 ind = 0
156 for ri in range(8):
156 for ri in range(8):
157 for gi in range(8):
157 for gi in range(8):
158 for bi in range(4):
158 for bi in range(4):
159 r[ind] = ri/(6-1.0)
159 r[ind] = ri/(6-1.0)
160 g[ind] = gi/(8-1.0)
160 g[ind] = gi/(8-1.0)
161 b[ind] = bi/(5-1.0)
161 b[ind] = bi/(5-1.0)
162 pos[ind] = ind/(ncolor-1.0)
162 pos[ind] = ind/(ncolor-1.0)
163 ind += 1
163 ind += 1
164 rgb_lvl = [6,8,5] #Levels for RGB colors
164 rgb_lvl = [6,8,5] #Levels for RGB colors
165
165
166 if colormap == 'rgb884':
166 if colormap == 'rgb884':
167 ncolor = 8*8*4
167 ncolor = 8*8*4
168 pos = numpy.zeros((ncolor))
168 pos = numpy.zeros((ncolor))
169 r = numpy.zeros((ncolor))
169 r = numpy.zeros((ncolor))
170 g = numpy.zeros((ncolor))
170 g = numpy.zeros((ncolor))
171 b = numpy.zeros((ncolor))
171 b = numpy.zeros((ncolor))
172 ind = 0
172 ind = 0
173 for ri in range(8):
173 for ri in range(8):
174 for gi in range(8):
174 for gi in range(8):
175 for bi in range(4):
175 for bi in range(4):
176 r[ind] = ri/(8-1.0)
176 r[ind] = ri/(8-1.0)
177 g[ind] = gi/(8-1.0)
177 g[ind] = gi/(8-1.0)
178 b[ind] = bi/(4-1.0)
178 b[ind] = bi/(4-1.0)
179 pos[ind] = ind/(ncolor-1.0)
179 pos[ind] = ind/(ncolor-1.0)
180 ind += 1
180 ind += 1
181 rgb_lvl = [8,8,4] #Levels for RGB colors
181 rgb_lvl = [8,8,4] #Levels for RGB colors
182
182
183 if ncolor == None:
183 if ncolor == None:
184 raise ValueError, "The colormap selected is not valid"
184 raise ValueError, "The colormap selected is not valid"
185
185
186 plplot.plscmap1n(ncolor)
186 plplot.plscmap1n(ncolor)
187 plplot.plscmap1l(1, pos, r, g, b)
187 plplot.plscmap1l(1, pos, r, g, b)
188
188
189 return rgb_lvl
189 return rgb_lvl
190
190
191 def setColormap(colormap="jet"):
191 def setColormap(colormap="jet"):
192 cmap1_init(colormap)
192 cmap1_init(colormap)
193
193
194 def savePlplot(filename,width,height):
194 def savePlplot(filename,width,height):
195 curr_strm = plplot.plgstrm()
195 curr_strm = plplot.plgstrm()
196 save_strm = plplot.plmkstrm()
196 save_strm = plplot.plmkstrm()
197 plplot.plsetopt("geometry", "%dx%d"%(width,height))
197 plplot.plsetopt("geometry", "%dx%d"%(width,height))
198 plplot.plsdev("png")
198 plplot.plsdev("png")
199 plplot.plsfnam(filename)
199 plplot.plsfnam(filename)
200 plplot.plcpstrm(curr_strm,0)
200 plplot.plcpstrm(curr_strm,0)
201 plplot.plreplot()
201 plplot.plreplot()
202 plplot.plend1()
202 plplot.plend1()
203 plplot.plsstrm(curr_strm)
203 plplot.plsstrm(curr_strm)
204
204
205
205
206 def initPlplot(indexPlot,ncol,nrow,winTitle,width,height):
206 def initPlplot(indexPlot,ncol,nrow,winTitle,width,height):
207 plplot.plsstrm(indexPlot)
207 plplot.plsstrm(indexPlot)
208 plplot.plparseopts([winTitle],plplot.PL_PARSE_FULL)
208 plplot.plparseopts([winTitle],plplot.PL_PARSE_FULL)
209 plplot.plsetopt("geometry", "%dx%d"%(width*ncol,height*nrow))
209 plplot.plsetopt("geometry", "%dx%d"%(width*ncol,height*nrow))
210 plplot.plsdev("xwin")
210 plplot.plsdev("xwin")
211 plplot.plscolbg(255,255,255)
211 plplot.plscolbg(255,255,255)
212 plplot.plscol0(1,0,0,0)
212 plplot.plscol0(1,0,0,0)
213 plplot.plinit()
213 plplot.plinit()
214 plplot.plspause(False)
214 plplot.plspause(False)
215 plplot.plssub(ncol,nrow)
215 plplot.plssub(ncol,nrow)
216
216
217 def setNewPage():
217 def setNewPage():
218 plplot.plbop()
218 plplot.plbop()
219 plplot.pladv(0)
219 plplot.pladv(0)
220
220
221 def closePage():
221 def closePage():
222 plplot.pleop()
222 plplot.pleop()
223
223
224 def clearData(objGraph):
224 def clearData(objGraph):
225 objGraph.plotBox(objGraph.xrange[0], objGraph.xrange[1], objGraph.yrange[0], objGraph.yrange[1], "bc", "bc")
225 objGraph.plotBox(objGraph.xrange[0], objGraph.xrange[1], objGraph.yrange[0], objGraph.yrange[1], "bc", "bc")
226
226
227 objGraph.setColor(15) #Setting Line Color to White
227 objGraph.setColor(15) #Setting Line Color to White
228
228
229 if objGraph.datatype == "complex":
229 if objGraph.datatype == "complex":
230 objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata.real)
230 objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata.real)
231 objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata.imag)
231 objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata.imag)
232
232
233 if objGraph.datatype == "real":
233 if objGraph.datatype == "real":
234 objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata)
234 objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata)
235
235
236 objGraph.setColor(1) #Setting Line Color to Black
236 objGraph.setColor(1) #Setting Line Color to Black
237 # objGraph.setLineStyle(2)
237 # objGraph.setLineStyle(2)
238 # objGraph.plotBox(objGraph.xrange[0], objGraph.xrange[1], objGraph.yrange[0], objGraph.yrange[1], "bcntg", "bc")
238 # objGraph.plotBox(objGraph.xrange[0], objGraph.xrange[1], objGraph.yrange[0], objGraph.yrange[1], "bcntg", "bc")
239 # objGraph.setLineStyle(1)
239 # objGraph.setLineStyle(1)
240
240
241 def setStrm(indexPlot):
241 def setStrm(indexPlot):
242 plplot.plsstrm(indexPlot)
242 plplot.plsstrm(indexPlot)
243
243
244 def plFlush():
244 def plFlush():
245 plplot.plflush()
245 plplot.plflush()
246
246
247 def setPlTitle(pltitle,color, szchar=0.7):
247 def setPlTitle(pltitle,color, szchar=0.7):
248 setSubpages(1, 0)
248 setSubpages(1, 0)
249 plplot.pladv(0)
249 plplot.pladv(0)
250 plplot.plvpor(0., 1., 0., 1.)
250 plplot.plvpor(0., 1., 0., 1.)
251
251
252 if color == "black":
252 if color == "black":
253 plplot.plcol0(1)
253 plplot.plcol0(1)
254 if color == "white":
254 if color == "white":
255 plplot.plcol0(15)
255 plplot.plcol0(15)
256
256
257 plplot.plschr(0.0,szchar)
257 plplot.plschr(0.0,szchar)
258 plplot.plmtex("t",-1., 0.5, 0.5, pltitle)
258 plplot.plmtex("t",-1., 0.5, 0.5, pltitle)
259
259
260 def setSubpages(ncol,nrow):
260 def setSubpages(ncol,nrow):
261 plplot.plssub(ncol,nrow)
261 plplot.plssub(ncol,nrow)
262
262
263 class BaseGraph:
263 class BaseGraph:
264
264
265 __name = None
265 __name = None
266 __xpos = None
266 __xpos = None
267 __ypos = None
267 __ypos = None
268 __subplot = None
268 __subplot = None
269 __xg = None
269 __xg = None
270 __yg = None
270 __yg = None
271 xdata = None
271 xdata = None
272 ydata = None
272 ydata = None
273 getGrid = True
273 getGrid = True
274 xaxisIsTime = False
274 xaxisIsTime = False
275 deltax = None
275 deltax = None
276 xmin = None
276 xmin = None
277 xmax = None
277 xmax = None
278
278
279 def __init__(self,name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange=None,deltax=1.0):
279 def __init__(self,name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange=None,deltax=1.0):
280
280
281 self.setName(name)
281 self.setName(name)
282 self.setScreenPos(xpos, ypos)
282 self.setScreenPos(xpos, ypos)
283 self.setLabels(xlabel,ylabel,title)
283 self.setLabels(xlabel,ylabel,title)
284 self.setSubPlot(subplot)
284 self.setSubPlot(subplot)
285 self.setSizeOfChar(szchar)
285 self.setSizeOfChar(szchar)
286 self.setXYZrange(xrange,yrange,zrange)
286 self.setXYZrange(xrange,yrange,zrange)
287 self.getGrid = True
287 self.getGrid = True
288 self.xaxisIsTime = False
288 self.xaxisIsTime = False
289 self.deltax = deltax
289 self.deltax = deltax
290
290
291 def setXYZrange(self,xrange,yrange,zrange):
291 def setXYZrange(self,xrange,yrange,zrange):
292 self.xrange = xrange
292 self.xrange = xrange
293 self.yrange = yrange
293 self.yrange = yrange
294 self.zrange = zrange
294 self.zrange = zrange
295
295
296 def setName(self, name):
296 def setName(self, name):
297 self.__name = name
297 self.__name = name
298
298
299 def setScreenPos(self,xpos,ypos):
299 def setScreenPos(self,xpos,ypos):
300 self.__xpos = xpos
300 self.__xpos = xpos
301 self.__ypos = ypos
301 self.__ypos = ypos
302
302
303 def setXYData(self,xdata=None,ydata=None,datatype="real"):
303 def setXYData(self,xdata=None,ydata=None,datatype="real"):
304 if((xdata != None) and (ydata != None)):
304 if((xdata != None) and (ydata != None)):
305 self.xdata = xdata
305 self.xdata = xdata
306 self.ydata = ydata
306 self.ydata = ydata
307 self.datatype = datatype
307 self.datatype = datatype
308
308
309 if((self.xdata == None) and (self.ydata == None)):
309 if((self.xdata == None) and (self.ydata == None)):
310 return None
310 return None
311
311
312 return 1
312 return 1
313
313
314
314
315 def setLabels(self,xlabel=None,ylabel=None,title=None):
315 def setLabels(self,xlabel=None,ylabel=None,title=None):
316 if xlabel != None: self.xlabel = xlabel
316 if xlabel != None: self.xlabel = xlabel
317 if ylabel != None: self.ylabel = ylabel
317 if ylabel != None: self.ylabel = ylabel
318 if title != None: self.title = title
318 if title != None: self.title = title
319
319
320 def setSubPlot(self,subplot):
320 def setSubPlot(self,subplot):
321 self.__subplot = subplot
321 self.__subplot = subplot
322
322
323 def setSizeOfChar(self,szchar):
323 def setSizeOfChar(self,szchar):
324 self.__szchar = szchar
324 self.__szchar = szchar
325
325
326 def setLineStyle(self,style):
326 def setLineStyle(self,style):
327 plplot.pllsty(style)
327 plplot.pllsty(style)
328
328
329 def setColor(self,color):
329 def setColor(self,color):
330 plplot.plcol0(color)
330 plplot.plcol0(color)
331
331
332 def setXAxisAsTime(self,value=False):
332 def setXAxisAsTime(self,value=False):
333 self.xaxisIsTime = value
333 self.xaxisIsTime = value
334
334
335 def basicLineTimePlot(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None, colline=1):
335 def basicLineTimePlot(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None, colline=1):
336
336
337 if xmin == None: xmin = x[0]
337 if xmin == None: xmin = x[0]
338 if xmax == None: xmax = x[-1]
338 if xmax == None: xmax = x[-1]
339 if ymin == None: ymin = y[0]
339 if ymin == None: ymin = y[0]
340 if ymax == None: ymax = y[-1]
340 if ymax == None: ymax = y[-1]
341
341
342 plplot.plcol0(colline)
342 plplot.plcol0(colline)
343 plplot.plline(x, y)
343 plplot.plline(x, y)
344 plplot.plcol0(1)
344 plplot.plcol0(1)
345
345
346 def basicXYPlot(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None):
346 def basicXYPlot(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None):
347
347
348 if xmin == None: xmin = x[0]
348 if xmin == None: xmin = x[0]
349 if xmax == None: xmax = x[-1]
349 if xmax == None: xmax = x[-1]
350 if ymin == None: ymin = y[0]
350 if ymin == None: ymin = y[0]
351 if ymax == None: ymax = y[-1]
351 if ymax == None: ymax = y[-1]
352
352
353 plplot.plline(x, y)
353 plplot.plline(x, y)
354
354
355 def basicPcolorPlot(self, data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None):
355 def basicPcolorPlot(self, data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None):
356 """
356 """
357 """
357 """
358 if xmin == None: xmin = x[0]
358 if xmin == None: xmin = x[0]
359 if xmax == None: xmax = x[-1]
359 if xmax == None: xmax = x[-1]
360 if ymin == None: ymin = y[0]
360 if ymin == None: ymin = y[0]
361 if ymax == None: ymax = y[-1]
361 if ymax == None: ymax = y[-1]
362 if zmin == None: zmin = numpy.nanmin(data)
362 if zmin == None: zmin = numpy.nanmin(data)
363 if zmax == None: zmax = numpy.nanmax(data)
363 if zmax == None: zmax = numpy.nanmax(data)
364
364
365 plplot.plimage(data,
365 plplot.plimage(data,
366 float(x[0]),
366 float(x[0]),
367 float(x[-1]),
367 float(x[-1]),
368 float(y[0]),
368 float(y[0]),
369 float(y[-1]),
369 float(y[-1]),
370 float(zmin),
370 float(zmin),
371 float(zmax),
371 float(zmax),
372 float(xmin),
372 float(xmin),
373 float(xmax),
373 float(xmax),
374 float(ymin),
374 float(ymin),
375 float(ymax)
375 float(ymax)
376 )
376 )
377
377
378 def __getBoxpltr(self, x, y, deltax=None, deltay=None):
378 def __getBoxpltr(self, x, y, deltax=None, deltay=None):
379
379
380 if not(len(x)>0 and len(y)>0):
380 if not(len(x)>0 and len(y)>0):
381 raise ValueError, "x axis and y axis are empty"
381 raise ValueError, "x axis and y axis are empty"
382
382
383 if deltax == None: deltax = x[-1] - x[-2]
383 if deltax == None: deltax = x[-1] - x[-2]
384 if deltay == None: deltay = y[-1] - y[-2]
384 if deltay == None: deltay = y[-1] - y[-2]
385
385
386 x1 = numpy.append(x, x[-1] + deltax)
386 x1 = numpy.append(x, x[-1] + deltax)
387 y1 = numpy.append(y, y[-1] + deltay)
387 y1 = numpy.append(y, y[-1] + deltay)
388
388
389 xg = (numpy.multiply.outer(x1, numpy.ones(len(y1))))
389 xg = (numpy.multiply.outer(x1, numpy.ones(len(y1))))
390 yg = (numpy.multiply.outer(numpy.ones(len(x1)), y1))
390 yg = (numpy.multiply.outer(numpy.ones(len(x1)), y1))
391
391
392 self.__xg = xg
392 self.__xg = xg
393 self.__yg = yg
393 self.__yg = yg
394
394
395 return xg, yg
395 return xg, yg
396
396
397
397
398 def advPcolorPlot(self, data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=0., zmax=0., deltax=1.0, deltay=None, getGrid = True):
398 def advPcolorPlot(self, data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=0., zmax=0., deltax=1.0, deltay=None, getGrid = True):
399 if getGrid:
399 if getGrid:
400 xg, yg = self.__getBoxpltr(x, y, deltax, deltay)
400 xg, yg = self.__getBoxpltr(x, y, deltax, deltay)
401 else:
401 else:
402 xg = self.__xg
402 xg = self.__xg
403 yg = self.__yg
403 yg = self.__yg
404
404
405 plplot.plimagefr(data,
405 plplot.plimagefr(data,
406 float(xmin),
406 float(xmin),
407 float(xmax),
407 float(xmax),
408 float(ymin),
408 float(ymin),
409 float(ymax),
409 float(ymax),
410 0.,
410 0.,
411 0.,
411 0.,
412 float(zmin),
412 float(zmin),
413 float(zmax),
413 float(zmax),
414 plplot.pltr2,
414 plplot.pltr2,
415 xg,
415 xg,
416 yg)
416 yg)
417
417
418
418
419 def colorbarPlot(self, xmin=0., xmax=1., ymin=0., ymax=1.):
419 def colorbarPlot(self, xmin=0., xmax=1., ymin=0., ymax=1.):
420 data = numpy.arange(256)
420 data = numpy.arange(256)
421 data = numpy.reshape(data, (1,-1))
421 data = numpy.reshape(data, (1,-1))
422
422
423 plplot.plimage(data,
423 plplot.plimage(data,
424 float(xmin),
424 float(xmin),
425 float(xmax),
425 float(xmax),
426 float(ymin),
426 float(ymin),
427 float(ymax),
427 float(ymax),
428 0.,
428 0.,
429 255.,
429 255.,
430 float(xmin),
430 float(xmin),
431 float(xmax),
431 float(xmax),
432 float(ymin),
432 float(ymin),
433 float(ymax))
433 float(ymax))
434
434
435 def plotBox(self, xmin, xmax, ymin, ymax, xopt, yopt, nolabels=False):
435 def plotBox(self, xmin, xmax, ymin, ymax, xopt, yopt, nolabels=False):
436
436
437 plplot.plschr(0.0,self.__szchar-0.05)
437 plplot.plschr(0.0,self.__szchar-0.05)
438 plplot.pladv(self.__subplot)
438 plplot.pladv(self.__subplot)
439 plplot.plvpor(self.__xpos[0], self.__xpos[1], self.__ypos[0], self.__ypos[1])
439 plplot.plvpor(self.__xpos[0], self.__xpos[1], self.__ypos[0], self.__ypos[1])
440 plplot.plwind(float(xmin), # self.xrange[0]
440 plplot.plwind(float(xmin), # self.xrange[0]
441 float(xmax), # self.xrange[1]
441 float(xmax), # self.xrange[1]
442 float(ymin), # self.yrange[0]
442 float(ymin), # self.yrange[0]
443 float(ymax) # self.yrange[1]
443 float(ymax) # self.yrange[1]
444 )
444 )
445
445
446
446
447
447
448 if self.xaxisIsTime:
448 if self.xaxisIsTime:
449 plplot.pltimefmt("%H:%M")
449 plplot.pltimefmt("%H:%M")
450 timedelta = (xmax - xmin + 1)/8.
450 timedelta = (xmax - xmin + 1)/8.
451 plplot.plbox(xopt, timedelta, 3, yopt, 0.0, 0)
451 plplot.plbox(xopt, timedelta, 3, yopt, 0.0, 0)
452 else:
452 else:
453 plplot.plbox(xopt, 0.0, 0, yopt, 0.0, 0)
453 plplot.plbox(xopt, 0.0, 0, yopt, 0.0, 0)
454
454
455
455
456 if not(nolabels):
456 if not(nolabels):
457 plplot.pllab(self.xlabel, self.ylabel, self.title)
457 plplot.pllab(self.xlabel, self.ylabel, self.title)
458
458
459
459
460 def delLabels(self):
460 def delLabels(self):
461 self.setColor(15) #Setting Line Color to White
461 self.setColor(15) #Setting Line Color to White
462 plplot.pllab(self.xlabel, self.ylabel, self.title)
462 plplot.pllab(self.xlabel, self.ylabel, self.title)
463 self.setColor(1) #Setting Line Color to Black
463 self.setColor(1) #Setting Line Color to Black
464
464
465
465
466
466
467 def plotImage(self,x,y,z,xrange,yrange,zrange):
467 def plotImage(self,x,y,z,xrange,yrange,zrange):
468 xi = x[0]
468 xi = x[0]
469 xf = x[-1]
469 xf = x[-1]
470 yi = y[0]
470 yi = y[0]
471 yf = y[-1]
471 yf = y[-1]
472
472
473 plplot.plimage(z,
473 plplot.plimage(z,
474 float(xi),
474 float(xi),
475 float(xf),
475 float(xf),
476 float(yi),
476 float(yi),
477 float(yf),
477 float(yf),
478 float(zrange[0]),
478 float(zrange[0]),
479 float(zrange[1]),
479 float(zrange[1]),
480 float(xi),
480 float(xi),
481 float(xf),
481 float(xf),
482 float(yrange[0]),
482 float(yrange[0]),
483 yrange[1])
483 yrange[1])
484
484
485 class LinearPlot:
485 class LinearPlot:
486 linearObjDic = {}
486 linearObjDic = {}
487 __xpos = None
487 __xpos = None
488 __ypos = None
488 __ypos = None
489 def __init__(self,indexPlot,nsubplot,winTitle):
489 def __init__(self,indexPlot,nsubplot,winTitle):
490 self.width = 700
490 self.width = 700
491 self.height = 150
491 self.height = 150
492 ncol = 1
492 ncol = 1
493 nrow = nsubplot
493 nrow = nsubplot
494 initPlplot(indexPlot,ncol,nrow,winTitle,self.width,self.height)
494 initPlplot(indexPlot,ncol,nrow,winTitle,self.width,self.height)
495
495
496
496
497 def setFigure(self,indexPlot):
497 def setFigure(self,indexPlot):
498 setStrm(indexPlot)
498 setStrm(indexPlot)
499
499
500 def setPosition(self):
500 def setPosition(self):
501
501
502 xi = 0.07; xf = 0.9 #0.8,0.7,0.5
502 xi = 0.07; xf = 0.9 #0.8,0.7,0.5
503 yi = 0.15; yf = 0.8
503 yi = 0.15; yf = 0.8
504
504
505 xpos = [xi,xf]
505 xpos = [xi,xf]
506 ypos = [yi,yf]
506 ypos = [yi,yf]
507
507
508 self.__xpos = xpos
508 self.__xpos = xpos
509 self.__ypos = ypos
509 self.__ypos = ypos
510
510
511 return xpos,ypos
511 return xpos,ypos
512
512
513 def refresh(self):
513 def refresh(self):
514 plFlush()
514 plFlush()
515
515
516 def setup(self,subplot,xmin,xmax,ymin,ymax,title,xlabel,ylabel):
516 def setup(self,subplot,xmin,xmax,ymin,ymax,title,xlabel,ylabel):
517 szchar = 1.10
517 szchar = 1.10
518 name = "linear"
518 name = "linear"
519 key = name + "%d"%subplot
519 key = name + "%d"%subplot
520 xrange = [xmin,xmax]
520 xrange = [xmin,xmax]
521 yrange = [ymin,ymax]
521 yrange = [ymin,ymax]
522
522
523 xpos,ypos = self.setPosition()
523 xpos,ypos = self.setPosition()
524 linearObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange)
524 linearObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange)
525 linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bcnst", "bcnstv")
525 linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bcnst", "bcnstv")
526 self.linearObjDic[key] = linearObj
526 self.linearObjDic[key] = linearObj
527
527
528 def plot(self,subplot,x,y,type="power"):
528 def plot(self,subplot,x,y,type="power"):
529 name = "linear"
529 name = "linear"
530 key = name + "%d"%subplot
530 key = name + "%d"%subplot
531
531
532 linearObj = self.linearObjDic[key]
532 linearObj = self.linearObjDic[key]
533 linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bcst", "bcst")
533 linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bcst", "bcst")
534
534
535 if linearObj.setXYData() != None:
535 if linearObj.setXYData() != None:
536 clearData(linearObj)
536 clearData(linearObj)
537
537
538 else:
538 else:
539 if type.lower() == 'power':
539 if type.lower() == 'power':
540 linearObj.setXYData(x,abs(y),"real")
540 linearObj.setXYData(x,abs(y),"real")
541 if type.lower() == 'iq':
541 if type.lower() == 'iq':
542 linearObj.setXYData(x,y,"complex")
542 linearObj.setXYData(x,y,"complex")
543
543
544 if type.lower() == 'power':
544 if type.lower() == 'power':
545 colline = 9
545 colline = 9
546 linearObj.basicLineTimePlot(x, abs(y), xmin, xmax, ymin, ymax, colline)
546 linearObj.basicLineTimePlot(x, abs(y), xmin, xmax, ymin, ymax, colline)
547 linearObj.setXYData(x,abs(y),"real")
547 linearObj.setXYData(x,abs(y),"real")
548
548
549 if type.lower() == 'iq':
549 if type.lower() == 'iq':
550 colline = 9
550 colline = 9
551 linearObj.basicLineTimePlot(x=x, y=y.real, colline=colline)
551 linearObj.basicLineTimePlot(x=x, y=y.real, colline=colline)
552 colline = 13
552 colline = 13
553 linearObj.basicLineTimePlot(x=x, y=y.imag, colline=colline)
553 linearObj.basicLineTimePlot(x=x, y=y.imag, colline=colline)
554
554
555 linearObj.setXYData(x,y,"complex")
555 linearObj.setXYData(x,y,"complex")
556
556
557 linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bcst", "bcst")
557 linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bcst", "bcst")
558
558
559
559
560 # linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bc", "bc")
560 # linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bc", "bc")
561 # linearObj.basicXYPlot(data,y)
561 # linearObj.basicXYPlot(data,y)
562 # linearObj.setXYData(data,y)
562 # linearObj.setXYData(data,y)
563
563
564
564
565
565
566 class PcolorPlot:
566 class PcolorPlot:
567 pcolorObjDic = {}
567 pcolorObjDic = {}
568 colorbarObjDic = {}
568 colorbarObjDic = {}
569 pwprofileObjDic = {}
569 pwprofileObjDic = {}
570 showColorbar = None
570 showColorbar = None
571 showPowerProfile = None
571 showPowerProfile = None
572 XAxisAsTime = None
572 XAxisAsTime = None
573 width = None
573 width = None
574 height = None
574 height = None
575 __spcxpos = None
575 __spcxpos = None
576 __spcypos = None
576 __spcypos = None
577 __cmapxpos = None
577 __cmapxpos = None
578 __cmapypos = None
578 __cmapypos = None
579 __profxpos = None
579 __profxpos = None
580 __profypos = None
580 __profypos = None
581 __lastTitle = None
581 __lastTitle = None
582
582
583 def __init__(self,indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime):
583 def __init__(self,indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime):
584 self.width = 460
584 self.width = 460
585 self.height = 300
585 self.height = 300
586 self.showColorbar = showColorbar
586 self.showColorbar = showColorbar
587 self.showPowerProfile = showPowerProfile
587 self.showPowerProfile = showPowerProfile
588 self.XAxisAsTime = XAxisAsTime
588 self.XAxisAsTime = XAxisAsTime
589
589
590
590
591 ncol = int(numpy.sqrt(nsubplot)+0.9)
591 ncol = int(numpy.sqrt(nsubplot)+0.9)
592 nrow = int(nsubplot*1./ncol + 0.9)
592 nrow = int(nsubplot*1./ncol + 0.9)
593
593
594 initPlplot(indexPlot,ncol,nrow,winTitle,self.width,self.height)
594 initPlplot(indexPlot,ncol,nrow,winTitle,self.width,self.height)
595 setColormap(colormap)
595 setColormap(colormap)
596 self.ncol = ncol
596 self.ncol = ncol
597 self.nrow = nrow
597 self.nrow = nrow
598
598
599 def setFigure(self,indexPlot):
599 def setFigure(self,indexPlot):
600 setStrm(indexPlot)
600 setStrm(indexPlot)
601
601
602 def setSpectraPos(self): #modificar valores de acuerdo al colorbar y pwprofile
602 def setSpectraPos(self): #modificar valores de acuerdo al colorbar y pwprofile
603 if self.showPowerProfile: xi = 0.09; xf = 0.6 #0.075
603 if self.showPowerProfile: xi = 0.09; xf = 0.6 #0.075
604 else: xi = 0.15; xf = 0.8 #0.8,0.7,0.5
604 else: xi = 0.15; xf = 0.8 #0.8,0.7,0.5
605 yi = 0.15; yf = 0.80
605 yi = 0.15; yf = 0.80
606
606
607 xpos = [xi,xf]
607 xpos = [xi,xf]
608 ypos = [yi,yf]
608 ypos = [yi,yf]
609
609
610 self.__spcxpos = xpos
610 self.__spcxpos = xpos
611 self.__spcypos = ypos
611 self.__spcypos = ypos
612
612
613 return xpos,ypos
613 return xpos,ypos
614
614
615 def setColorbarScreenPos(self):
615 def setColorbarScreenPos(self):
616
616
617 xi = self.__spcxpos[1] + 0.03; xf = xi + 0.03
617 xi = self.__spcxpos[1] + 0.03; xf = xi + 0.03
618 yi = self.__spcypos[0]; yf = self.__spcypos[1]
618 yi = self.__spcypos[0]; yf = self.__spcypos[1]
619
619
620 xpos = [xi,xf]
620 xpos = [xi,xf]
621 ypos = [yi,yf]
621 ypos = [yi,yf]
622
622
623 self.__cmapxpos = xpos
623 self.__cmapxpos = xpos
624 self.__cmapypos = ypos
624 self.__cmapypos = ypos
625
625
626 return xpos,ypos
626 return xpos,ypos
627
627
628 def setPowerprofileScreenPos(self):
628 def setPowerprofileScreenPos(self):
629
629
630 xi = self.__cmapxpos[1] + 0.07; xf = xi + 0.25
630 xi = self.__cmapxpos[1] + 0.07; xf = xi + 0.25
631 yi = self.__spcypos[0]; yf = self.__spcypos[1]
631 yi = self.__spcypos[0]; yf = self.__spcypos[1]
632
632
633 xpos = [xi,xf]
633 xpos = [xi,xf]
634 ypos = [yi,yf]
634 ypos = [yi,yf]
635
635
636 self.__profxpos = [xi,xf]
636 self.__profxpos = [xi,xf]
637 self.__profypos = [yi,yf]
637 self.__profypos = [yi,yf]
638
638
639 return xpos,ypos
639 return xpos,ypos
640
640
641 def createObjects(self,subplot,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel):
641 def createObjects(self,subplot,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel):
642 """
642 """
643 Crea los objetos necesarios para un subplot
643 Crea los objetos necesarios para un subplot
644 """
644 """
645
645
646 # Config Spectra plot
646 # Config Spectra plot
647
647
648 szchar = 0.7
648 szchar = 0.7
649 name = "spc"
649 name = "spc"
650 key = name + "%d"%subplot
650 key = name + "%d"%subplot
651 xrange = [xmin,xmax]
651 xrange = [xmin,xmax]
652 yrange = [ymin,ymax]
652 yrange = [ymin,ymax]
653 zrange = [zmin,zmax]
653 zrange = [zmin,zmax]
654
654
655 xpos,ypos = self.setSpectraPos()
655 xpos,ypos = self.setSpectraPos()
656 pcolorObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange)
656 pcolorObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange)
657 self.pcolorObjDic[key] = pcolorObj
657 self.pcolorObjDic[key] = pcolorObj
658
658
659 # Config Colorbar
659 # Config Colorbar
660 if self.showColorbar:
660 if self.showColorbar:
661 szchar = 0.65
661 szchar = 0.65
662 name = "colorbar"
662 name = "colorbar"
663 key = name + "%d"%subplot
663 key = name + "%d"%subplot
664
664
665 xpos,ypos = self.setColorbarScreenPos()
665 xpos,ypos = self.setColorbarScreenPos()
666 xrange = [0.,1.]
666 xrange = [0.,1.]
667 yrange = [zmin,zmax]
667 yrange = [zmin,zmax]
668 cmapObj = BaseGraph(name,subplot,xpos,ypos,"","","dB",szchar,xrange,yrange)
668 cmapObj = BaseGraph(name,subplot,xpos,ypos,"","","dB",szchar,xrange,yrange)
669 self.colorbarObjDic[key] = cmapObj
669 self.colorbarObjDic[key] = cmapObj
670
670
671 # Config Power profile
671 # Config Power profile
672 if self.showPowerProfile:
672 if self.showPowerProfile:
673 szchar = 0.55
673 szchar = 0.55
674 name = "pwprofile"
674 name = "pwprofile"
675 key = name + "%d"%subplot
675 key = name + "%d"%subplot
676
676
677 xpos,ypos = self.setPowerprofileScreenPos()
677 xpos,ypos = self.setPowerprofileScreenPos()
678 xrange = [zmin,zmax]
678 xrange = [zmin,zmax]
679 yrange = [ymin,ymax]
679 yrange = [ymin,ymax]
680 powObj = BaseGraph(name,subplot,xpos,ypos,"dB","","Power Profile",szchar,xrange,yrange)
680 powObj = BaseGraph(name,subplot,xpos,ypos,"dB","","Power Profile",szchar,xrange,yrange)
681 self.pwprofileObjDic[key] = powObj
681 self.pwprofileObjDic[key] = powObj
682
682
683 def setNewPage(self, pltitle='No title'):
683 def setNewPage(self, pltitle='No title'):
684 szchar = 0.7
684 szchar = 0.7
685 setNewPage()
685 setNewPage()
686 setPlTitle(pltitle,"black", szchar=szchar)
686 setPlTitle(pltitle,"black", szchar=szchar)
687 setSubpages(self.ncol, self.nrow)
687 setSubpages(self.ncol, self.nrow)
688
688
689 def closePage(self):
689 def closePage(self):
690 closePage()
690 closePage()
691
691
692 def iniPlot(self,subplot):
692 def iniPlot(self,subplot):
693 """
693 """
694 Inicializa los subplots con su frame, titulo, etc
694 Inicializa los subplots con su frame, titulo, etc
695 """
695 """
696
696
697 # Config Spectra plot
697 # Config Spectra plot
698 name = "spc"
698 name = "spc"
699 key = name + "%d"%subplot
699 key = name + "%d"%subplot
700
700
701 pcolorObj = self.pcolorObjDic[key]
701 pcolorObj = self.pcolorObjDic[key]
702 pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], "bcnst", "bcnstv")
702 pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], "bcnst", "bcnstv")
703
703
704 # Config Colorbar
704 # Config Colorbar
705 if self.showColorbar:
705 if self.showColorbar:
706 name = "colorbar"
706 name = "colorbar"
707 key = name + "%d"%subplot
707 key = name + "%d"%subplot
708
708
709 cmapObj = self.colorbarObjDic[key]
709 cmapObj = self.colorbarObjDic[key]
710 cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcmtsv")
710 cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcmtsv")
711 cmapObj.colorbarPlot(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1])
711 cmapObj.colorbarPlot(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1])
712 # cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcmtsv")
712 # cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcmtsv")
713
713
714 # Config Power profile
714 # Config Power profile
715 if self.showPowerProfile:
715 if self.showPowerProfile:
716 name = "pwprofile"
716 name = "pwprofile"
717 key = name + "%d"%subplot
717 key = name + "%d"%subplot
718
718
719 powObj = self.pwprofileObjDic[key]
719 powObj = self.pwprofileObjDic[key]
720 powObj.setLineStyle(2)
720 powObj.setLineStyle(2)
721 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc")
721 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc")
722 powObj.setLineStyle(1)
722 powObj.setLineStyle(1)
723 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc")
723 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc")
724
724
725 def printTitle(self,pltitle):
725 def printTitle(self,pltitle):
726 # if self.__lastTitle != None:
726 # if self.__lastTitle != None:
727 # setPlTitle(self.__lastTitle,"white")
727 # setPlTitle(self.__lastTitle,"white")
728 #
728 #
729 # self.__lastTitle = pltitle
729 # self.__lastTitle = pltitle
730
730
731 setPlTitle(pltitle,"black")
731 setPlTitle(pltitle,"black")
732
732
733 # setSubpages(self.ncol,self.nrow)
733 # setSubpages(self.ncol,self.nrow)
734
734
735 def plot(self,subplot,x,y,z,subtitle):
735 def plot(self,subplot,x,y,z,subtitle):
736 # Spectra plot
736 # Spectra plot
737
737
738 name = "spc"
738 name = "spc"
739 key = name + "%d"%subplot
739 key = name + "%d"%subplot
740
740
741 # newx = [x[0],x[-1]]
741 # newx = [x[0],x[-1]]
742 pcolorObj = self.pcolorObjDic[key]
742 pcolorObj = self.pcolorObjDic[key]
743
743
744 pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], "bcst", "bcst")
744 pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], "bcst", "bcst")
745
745
746 #pcolorObj.delLabels()
746 #pcolorObj.delLabels()
747 pcolorObj.setLabels(title=subtitle)
747 pcolorObj.setLabels(title=subtitle)
748
748
749 deltax = None; deltay = None
749 deltax = None; deltay = None
750
750
751 pcolorObj.advPcolorPlot(z,
751 pcolorObj.advPcolorPlot(z,
752 x,
752 x,
753 y,
753 y,
754 xmin=pcolorObj.xrange[0],
754 xmin=pcolorObj.xrange[0],
755 xmax=pcolorObj.xrange[1],
755 xmax=pcolorObj.xrange[1],
756 ymin=pcolorObj.yrange[0],
756 ymin=pcolorObj.yrange[0],
757 ymax=pcolorObj.yrange[1],
757 ymax=pcolorObj.yrange[1],
758 zmin=pcolorObj.zrange[0],
758 zmin=pcolorObj.zrange[0],
759 zmax=pcolorObj.zrange[1],
759 zmax=pcolorObj.zrange[1],
760 deltax=deltax,
760 deltax=deltax,
761 deltay=deltay,
761 deltay=deltay,
762 getGrid=pcolorObj.getGrid)
762 getGrid=pcolorObj.getGrid)
763
763
764 #Solo se calcula la primera vez que se ingresa a la funcion
764 #Solo se calcula la primera vez que se ingresa a la funcion
765 pcolorObj.getGrid = False
765 pcolorObj.getGrid = False
766
766
767 pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], "bcst", "bcst", nolabels=True)
767 pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], "bcst", "bcst", nolabels=True)
768
768
769 # Power Profile
769 # Power Profile
770 if self.showPowerProfile:
770 if self.showPowerProfile:
771 power = numpy.average(z, axis=0)
771 power = numpy.average(z, axis=0)
772 name = "pwprofile"
772 name = "pwprofile"
773 key = name + "%d"%subplot
773 key = name + "%d"%subplot
774 powObj = self.pwprofileObjDic[key]
774 powObj = self.pwprofileObjDic[key]
775
775
776 if powObj.setXYData() != None:
776 if powObj.setXYData() != None:
777 #clearData(powObj)
777 #clearData(powObj)
778 powObj.setLineStyle(2)
778 powObj.setLineStyle(2)
779 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc")
779 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc")
780 powObj.setLineStyle(1)
780 powObj.setLineStyle(1)
781 else:
781 else:
782 powObj.setXYData(power,y)
782 powObj.setXYData(power,y)
783
783
784 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc")
784 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc")
785 powObj.basicXYPlot(power,y)
785 powObj.basicXYPlot(power,y)
786 powObj.setXYData(power,y)
786 powObj.setXYData(power,y)
787
787
788 def savePlot(self,indexPlot,filename):
788 def savePlot(self,indexPlot,filename):
789
789
790 width = self.width*self.ncol
790 width = self.width*self.ncol
791 hei = self.height*self.nrow
791 hei = self.height*self.nrow
792 savePlplot(filename,width,hei)
792 savePlplot(filename,width,hei)
793
793
794 def refresh(self):
794 def refresh(self):
795 plFlush()
795 plFlush()
796
796
797 class RtiPlot:
797 class RtiPlot:
798
798
799 pcolorObjDic = {}
799 pcolorObjDic = {}
800 colorbarObjDic = {}
800 colorbarObjDic = {}
801 pwprofileObjDic = {}
801 pwprofileObjDic = {}
802 showColorbar = None
802 showColorbar = None
803 showPowerProfile = None
803 showPowerProfile = None
804 XAxisAsTime = None
804 XAxisAsTime = None
805 widht = None
805 widht = None
806 height = None
806 height = None
807 __rtixpos = None
807 __rtixpos = None
808 __rtiypos = None
808 __rtiypos = None
809 __cmapxpos = None
809 __cmapxpos = None
810 __cmapypos = None
810 __cmapypos = None
811 __profxpos = None
811 __profxpos = None
812 __profypos = None
812 __profypos = None
813
813
814 def __init__(self,indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime):
814 def __init__(self,indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime):
815 self.width = 700
815 self.width = 700
816 self.height = 150
816 self.height = 150
817 self.showColorbar = showColorbar
817 self.showColorbar = showColorbar
818 self.showPowerProfile = showPowerProfile
818 self.showPowerProfile = showPowerProfile
819 self.XAxisAsTime = XAxisAsTime
819 self.XAxisAsTime = XAxisAsTime
820
820
821 ncol = 1
821 ncol = 1
822 nrow = nsubplot
822 nrow = nsubplot
823 initPlplot(indexPlot,ncol,nrow,winTitle,self.width,self.height)
823 initPlplot(indexPlot,ncol,nrow,winTitle,self.width,self.height)
824 setColormap(colormap)
824 setColormap(colormap)
825 self.ncol = ncol
826 self.nrow = nrow
825
827
826 def setFigure(self,indexPlot):
828 def setFigure(self,indexPlot):
827 setStrm(indexPlot)
829 setStrm(indexPlot)
828
830
829 def setRtiScreenPos(self):
831 def setRtiScreenPos(self):
830
832
831 if self.showPowerProfile: xi = 0.07; xf = 0.65
833 if self.showPowerProfile: xi = 0.07; xf = 0.65
832 else: xi = 0.07; xf = 0.9
834 else: xi = 0.07; xf = 0.9
833 yi = 0.15; yf = 0.80
835 yi = 0.15; yf = 0.80
834
836
835 xpos = [xi,xf]
837 xpos = [xi,xf]
836 ypos = [yi,yf]
838 ypos = [yi,yf]
837
839
838 self.__rtixpos = xpos
840 self.__rtixpos = xpos
839 self.__rtiypos = ypos
841 self.__rtiypos = ypos
840
842
841 return xpos,ypos
843 return xpos,ypos
842
844
843 def setColorbarScreenPos(self):
845 def setColorbarScreenPos(self):
844
846
845 xi = self.__rtixpos[1] + 0.03; xf = xi + 0.03
847 xi = self.__rtixpos[1] + 0.03; xf = xi + 0.03
846
848
847 yi = self.__rtiypos[0]; yf = self.__rtiypos[1]
849 yi = self.__rtiypos[0]; yf = self.__rtiypos[1]
848
850
849 xpos = [xi,xf]
851 xpos = [xi,xf]
850 ypos = [yi,yf]
852 ypos = [yi,yf]
851
853
852 self.__cmapxpos = xpos
854 self.__cmapxpos = xpos
853 self.__cmapypos = ypos
855 self.__cmapypos = ypos
854
856
855 return xpos,ypos
857 return xpos,ypos
856
858
857 def setPowerprofileScreenPos(self):
859 def setPowerprofileScreenPos(self):
858
860
859 xi = self.__cmapxpos[1] + 0.05; xf = xi + 0.20
861 xi = self.__cmapxpos[1] + 0.05; xf = xi + 0.20
860
862
861 yi = self.__rtiypos[0]; yf = self.__rtiypos[1]
863 yi = self.__rtiypos[0]; yf = self.__rtiypos[1]
862
864
863 xpos = [xi,xf]
865 xpos = [xi,xf]
864 ypos = [yi,yf]
866 ypos = [yi,yf]
865
867
866 self.__profxpos = [xi,xf]
868 self.__profxpos = [xi,xf]
867 self.__profypos = [yi,yf]
869 self.__profypos = [yi,yf]
868
870
869 return xpos,ypos
871 return xpos,ypos
870
872
871 def setup(self,subplot,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel,timedata,timezone="lt",npoints=100):
873 def setup(self,subplot,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel,timedata,timezone="lt",npoints=100):
872 # Config Rti plot
874 # Config Rti plot
873 szchar = 1.10
875 szchar = 1.10
874 name = "rti"
876 name = "rti"
875 key = name + "%d"%subplot
877 key = name + "%d"%subplot
876
878
877 # xmin, xmax --> minHour, max Hour : valores que definen el ejex x=[horaInicio,horaFinal]
879 # xmin, xmax --> minHour, max Hour : valores que definen el ejex x=[horaInicio,horaFinal]
878 thisDateTime = datetime.datetime.fromtimestamp(timedata)
880 thisDateTime = datetime.datetime.fromtimestamp(timedata)
879 startDateTime = datetime.datetime(thisDateTime.year,thisDateTime.month,thisDateTime.day,xmin,0,0)
881 startDateTime = datetime.datetime(thisDateTime.year,thisDateTime.month,thisDateTime.day,xmin,0,0)
880 endDateTime = datetime.datetime(thisDateTime.year,thisDateTime.month,thisDateTime.day,xmax,59,59)
882 endDateTime = datetime.datetime(thisDateTime.year,thisDateTime.month,thisDateTime.day,xmax,59,59)
881 deltaTime = 0
883 deltaTime = 0
882 if timezone == "lt":
884 if timezone == "lt":
883 deltaTime = time.timezone
885 deltaTime = time.timezone
884 startTimeInSecs = time.mktime(startDateTime.timetuple()) - deltaTime
886 startTimeInSecs = time.mktime(startDateTime.timetuple()) - deltaTime
885 endTimeInSecs = time.mktime(endDateTime.timetuple()) - deltaTime
887 endTimeInSecs = time.mktime(endDateTime.timetuple()) - deltaTime
886
888
887 xrange = [startTimeInSecs,endTimeInSecs]
889 xrange = [startTimeInSecs,endTimeInSecs]
888 totalTimeInXrange = endTimeInSecs - startTimeInSecs + 1.
890 totalTimeInXrange = endTimeInSecs - startTimeInSecs + 1.
889 deltax = totalTimeInXrange / npoints
891 deltax = totalTimeInXrange / npoints
890
892
891 yrange = [ymin,ymax]
893 yrange = [ymin,ymax]
892 zrange = [zmin,zmax]
894 zrange = [zmin,zmax]
893
895
894 xpos,ypos = self.setRtiScreenPos()
896 xpos,ypos = self.setRtiScreenPos()
895 pcolorObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange,deltax)
897 pcolorObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange,deltax)
896 if self.XAxisAsTime:
898 if self.XAxisAsTime:
897 pcolorObj.setXAxisAsTime(self.XAxisAsTime)
899 pcolorObj.setXAxisAsTime(self.XAxisAsTime)
898 xopt = "bcnstd"
900 xopt = "bcnstd"
899 yopt = "bcnstv"
901 yopt = "bcnstv"
900 else:
902 else:
901 xopt = "bcnst"
903 xopt = "bcnst"
902 yopt = "bcnstv"
904 yopt = "bcnstv"
903
905
904 pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], xopt, yopt)
906 pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], xopt, yopt)
905 self.pcolorObjDic[key] = pcolorObj
907 self.pcolorObjDic[key] = pcolorObj
906
908
907
909
908 # Config Colorbar
910 # Config Colorbar
909 if self.showColorbar:
911 if self.showColorbar:
910 szchar = 0.9
912 szchar = 0.9
911 name = "colorbar"
913 name = "colorbar"
912 key = name + "%d"%subplot
914 key = name + "%d"%subplot
913
915
914 xpos,ypos = self.setColorbarScreenPos()
916 xpos,ypos = self.setColorbarScreenPos()
915 xrange = [0.,1.]
917 xrange = [0.,1.]
916 yrange = [zmin,zmax]
918 yrange = [zmin,zmax]
917 cmapObj = BaseGraph(name,subplot,xpos,ypos,"","","dB",szchar,xrange,yrange)
919 cmapObj = BaseGraph(name,subplot,xpos,ypos,"","","dB",szchar,xrange,yrange)
918 cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcm")
920 cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcm")
919 cmapObj.colorbarPlot(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1])
921 cmapObj.colorbarPlot(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1])
920 cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcmtsv")
922 cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcmtsv")
921 self.colorbarObjDic[key] = cmapObj
923 self.colorbarObjDic[key] = cmapObj
922
924
923
925
924 # Config Power profile
926 # Config Power profile
925 if self.showPowerProfile:
927 if self.showPowerProfile:
926 szchar = 0.8
928 szchar = 0.8
927 name = "pwprofile"
929 name = "pwprofile"
928 key = name + "%d"%subplot
930 key = name + "%d"%subplot
929
931
930 xpos,ypos = self.setPowerprofileScreenPos()
932 xpos,ypos = self.setPowerprofileScreenPos()
931 xrange = [zmin,zmax]
933 xrange = [zmin,zmax]
932 yrange = [ymin,ymax]
934 yrange = [ymin,ymax]
933 powObj = BaseGraph(name,subplot,xpos,ypos,"dB","","Power Profile",szchar,xrange,yrange)
935 powObj = BaseGraph(name,subplot,xpos,ypos,"dB","","Power Profile",szchar,xrange,yrange)
934 powObj.setLineStyle(2)
936 powObj.setLineStyle(2)
935 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc")
937 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc")
936 powObj.setLineStyle(1)
938 powObj.setLineStyle(1)
937 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc")
939 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc")
938 self.pwprofileObjDic[key] = powObj
940 self.pwprofileObjDic[key] = powObj
939
941
940
942
941 def plot(self,subplot,x,y,z):
943 def plot(self,subplot,x,y,z):
942 # RTI plot
944 # RTI plot
943 name = "rti"
945 name = "rti"
944 key = name + "%d"%subplot
946 key = name + "%d"%subplot
945
947
946 data = numpy.reshape(z, (1,-1))
948 data = numpy.reshape(z, (1,-1))
947 data = numpy.abs(data)
949 data = numpy.abs(data)
948 data = 10*numpy.log10(data)
950 data = 10*numpy.log10(data)
949 newx = [x,x+1]
951 newx = [x,x+1]
950
952
951 pcolorObj = self.pcolorObjDic[key]
953 pcolorObj = self.pcolorObjDic[key]
952
954
953 if pcolorObj.xaxisIsTime:
955 if pcolorObj.xaxisIsTime:
954 xopt = "bcstd"
956 xopt = "bcstd"
955 yopt = "bcst"
957 yopt = "bcst"
956 else:
958 else:
957 xopt = "bcst"
959 xopt = "bcst"
958 yopt = "bcst"
960 yopt = "bcst"
959
961
960 pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], xopt, yopt)
962 pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], xopt, yopt)
961
963
962 deltax = pcolorObj.deltax
964 deltax = pcolorObj.deltax
963 deltay = None
965 deltay = None
964
966
965 if pcolorObj.xmin == None and pcolorObj.xmax == None:
967 if pcolorObj.xmin == None and pcolorObj.xmax == None:
966 pcolorObj.xmin = x
968 pcolorObj.xmin = x
967 pcolorObj.xmax = x
969 pcolorObj.xmax = x
968
970
969 if x >= pcolorObj.xmax:
971 if x >= pcolorObj.xmax:
970 xmin = x
972 xmin = x
971 xmax = x + deltax
973 xmax = x + deltax
972 x = [x]
974 x = [x]
973 pcolorObj.advPcolorPlot(data,
975 pcolorObj.advPcolorPlot(data,
974 x,
976 x,
975 y,
977 y,
976 xmin=xmin,
978 xmin=xmin,
977 xmax=xmax,
979 xmax=xmax,
978 ymin=pcolorObj.yrange[0],
980 ymin=pcolorObj.yrange[0],
979 ymax=pcolorObj.yrange[1],
981 ymax=pcolorObj.yrange[1],
980 zmin=pcolorObj.zrange[0],
982 zmin=pcolorObj.zrange[0],
981 zmax=pcolorObj.zrange[1],
983 zmax=pcolorObj.zrange[1],
982 deltax=deltax,
984 deltax=deltax,
983 deltay=deltay,
985 deltay=deltay,
984 getGrid=pcolorObj.getGrid)
986 getGrid=pcolorObj.getGrid)
985
987
986 pcolorObj.xmin = xmin
988 pcolorObj.xmin = xmin
987 pcolorObj.xmax = xmax
989 pcolorObj.xmax = xmax
988
990
989
991
990 # Power Profile
992 # Power Profile
991 if self.showPowerProfile:
993 if self.showPowerProfile:
992 data = numpy.reshape(data,(numpy.size(data)))
994 data = numpy.reshape(data,(numpy.size(data)))
993 name = "pwprofile"
995 name = "pwprofile"
994 key = name + "%d"%subplot
996 key = name + "%d"%subplot
995 powObj = self.pwprofileObjDic[key]
997 powObj = self.pwprofileObjDic[key]
996
998
997 if powObj.setXYData() != None:
999 if powObj.setXYData() != None:
998 clearData(powObj)
1000 clearData(powObj)
999 powObj.setLineStyle(2)
1001 powObj.setLineStyle(2)
1000 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc")
1002 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc")
1001 powObj.setLineStyle(1)
1003 powObj.setLineStyle(1)
1002 else:
1004 else:
1003 powObj.setXYData(data,y)
1005 powObj.setXYData(data,y)
1004
1006
1005 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc")
1007 powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc")
1006 powObj.basicXYPlot(data,y)
1008 powObj.basicXYPlot(data,y)
1007 powObj.setXYData(data,y)
1009 powObj.setXYData(data,y)
1008
1010
1011 def savePlot(self,indexPlot,filename):
1012
1013 width = self.width*self.ncol
1014 hei = self.height*self.nrow
1015 savePlplot(filename,width,hei)
1016
1009 def refresh(self):
1017 def refresh(self):
1010 plFlush() No newline at end of file
1018 plFlush()
@@ -1,190 +1,199
1 '''
1 '''
2 Created on Feb 7, 2012
2 Created on Feb 7, 2012
3
3
4 @author $Author$
4 @author $Author$
5 @version $Id$
5 @version $Id$
6 '''
6 '''
7 import numpy
7 import numpy
8 import os
8 import os
9 import sys
9 import sys
10
10
11 path = os.path.split(os.getcwd())[0]
11 path = os.path.split(os.getcwd())[0]
12 sys.path.append(path)
12 sys.path.append(path)
13
13
14 from Graphics.BaseGraph import *
14 from Graphics.BaseGraph import *
15 from Model.Voltage import Voltage
15 from Model.Voltage import Voltage
16
16
17 class Osciloscope:
17 class Osciloscope:
18 linearplotObj = None
18 linearplotObj = None
19
19
20 def __init__(self, Voltage, index):
20 def __init__(self, Voltage, index):
21 self.__isPlotConfig = False
21 self.__isPlotConfig = False
22 self.__isPlotIni = False
22 self.__isPlotIni = False
23 self.__xrange = None
23 self.__xrange = None
24 self.__yrange = None
24 self.__yrange = None
25 self.indexPlot = index
25 self.indexPlot = index
26 self.voltageObj = Voltage
26 self.voltageObj = Voltage
27
27
28 def setup(self,indexPlot,nsubplot,winTitle=''):
28 def setup(self,indexPlot,nsubplot,winTitle=''):
29 self.linearplotObj = LinearPlot(indexPlot,nsubplot,winTitle)
29 self.linearplotObj = LinearPlot(indexPlot,nsubplot,winTitle)
30
30
31 def initPlot(self,xmin,xmax,ymin,ymax,titleList,xlabelList,ylabelList):
31 def initPlot(self,xmin,xmax,ymin,ymax,titleList,xlabelList,ylabelList):
32 nsubplot = self.voltageObj.nChannels
32 nsubplot = self.voltageObj.nChannels
33
33
34 for index in range(nsubplot):
34 for index in range(nsubplot):
35 title = titleList[index]
35 title = titleList[index]
36 xlabel = xlabelList[index]
36 xlabel = xlabelList[index]
37 ylabel = ylabelList[index]
37 ylabel = ylabelList[index]
38 subplot = index
38 subplot = index
39 self.linearplotObj.setup(subplot+1,xmin,xmax,ymin,ymax,title,xlabel,ylabel)
39 self.linearplotObj.setup(subplot+1,xmin,xmax,ymin,ymax,title,xlabel,ylabel)
40
40
41 def plotData(self,
41 def plotData(self,
42 xmin=None,
42 xmin=None,
43 xmax=None,
43 xmax=None,
44 ymin=None,
44 ymin=None,
45 ymax=None,
45 ymax=None,
46 titleList=None,
46 titleList=None,
47 xlabelList=None,
47 xlabelList=None,
48 ylabelList=None,
48 ylabelList=None,
49 winTitle='',
49 winTitle='',
50 type="power"):
50 type="power"):
51
51
52 databuffer = self.voltageObj.data
52 databuffer = self.voltageObj.data
53
53
54 height = self.voltageObj.heightList
54 height = self.voltageObj.heightList
55 nsubplot = self.voltageObj.nChannels
55 nsubplot = self.voltageObj.nChannels
56 indexPlot = self.indexPlot
56 indexPlot = self.indexPlot
57
57
58
58
59 if not(self.__isPlotConfig):
59 if not(self.__isPlotConfig):
60 self.setup(indexPlot,nsubplot,winTitle)
60 self.setup(indexPlot,nsubplot,winTitle)
61 self.__isPlotConfig = True
61 self.__isPlotConfig = True
62
62
63 if not(self.__isPlotIni):
63 if not(self.__isPlotIni):
64 if titleList == None:
64 if titleList == None:
65 titleList = []
65 titleList = []
66 thisDatetime = datetime.datetime.fromtimestamp(self.voltageObj.m_BasicHeader.utc)
66 thisDatetime = datetime.datetime.fromtimestamp(self.voltageObj.m_BasicHeader.utc)
67 txtdate = "Date: %s" %(thisDatetime.strftime("%d-%b-%Y"))
67 txtdate = "Date: %s" %(thisDatetime.strftime("%d-%b-%Y"))
68 for i in range(nsubplot):
68 for i in range(nsubplot):
69 titleList.append("Channel: %d %s" %(i, txtdate))
69 titleList.append("Channel: %d %s" %(i, txtdate))
70
70
71 if xlabelList == None:
71 if xlabelList == None:
72 xlabelList = []
72 xlabelList = []
73 for i in range(nsubplot):
73 for i in range(nsubplot):
74 xlabelList.append("")
74 xlabelList.append("")
75
75
76 if ylabelList == None:
76 if ylabelList == None:
77 ylabelList = []
77 ylabelList = []
78 for i in range(nsubplot):
78 for i in range(nsubplot):
79 ylabelList.append("")
79 ylabelList.append("")
80
80
81 if xmin == None: xmin = height[0]
81 if xmin == None: xmin = height[0]
82 if xmax == None: xmax = height[-1]
82 if xmax == None: xmax = height[-1]
83 if ymin == None: ymin = numpy.nanmin(abs(databuffer))
83 if ymin == None: ymin = numpy.nanmin(abs(databuffer))
84 if ymax == None: ymax = numpy.nanmax(abs(databuffer))
84 if ymax == None: ymax = numpy.nanmax(abs(databuffer))
85
85
86 self.initPlot(xmin,xmax,ymin,ymax,titleList,xlabelList,ylabelList)
86 self.initPlot(xmin,xmax,ymin,ymax,titleList,xlabelList,ylabelList)
87 self.__isPlotIni = True
87 self.__isPlotIni = True
88
88
89 self.linearplotObj.setFigure(indexPlot)
89 self.linearplotObj.setFigure(indexPlot)
90
90
91 for index in range(nsubplot):
91 for index in range(nsubplot):
92 data = databuffer[index,:]
92 data = databuffer[index,:]
93 self.linearplotObj.plot(subplot=index+1,x=height,y=data,type=type)
93 self.linearplotObj.plot(subplot=index+1,x=height,y=data,type=type)
94
94
95 self.linearplotObj.refresh()
95 self.linearplotObj.refresh()
96
96
97 class RTI:
97 class RTI:
98 colorplotObj = None
98 colorplotObj = None
99
99
100 def __init__(self, Voltage, index):
100 def __init__(self, Voltage, index):
101 self.__isPlotConfig = False
101 self.__isPlotConfig = False
102 self.__isPlotIni = False
102 self.__isPlotIni = False
103 self.__xrange = None
103 self.__xrange = None
104 self.__yrange = None
104 self.__yrange = None
105 self.indexPlot = index
105 self.indexPlot = index
106 self.voltageObj = Voltage
106 self.voltageObj = Voltage
107
107
108 def setup(self,indexPlot,nsubplot,winTitle='',colormap="br_green",showColorbar=False,showPowerProfile=False,XAxisAsTime=False):
108 def setup(self,indexPlot,nsubplot,winTitle='',colormap="br_green",showColorbar=False,showPowerProfile=False,XAxisAsTime=False):
109 self.colorplotObj = RtiPlot(indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime)
109 self.colorplotObj = RtiPlot(indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime)
110
110
111 def initPlot(self,xmin,xmax,ymin,ymax,zmin,zmax,titleList,xlabelList,ylabelList,timezone,npoints):
111 def initPlot(self,xmin,xmax,ymin,ymax,zmin,zmax,titleList,xlabelList,ylabelList,timezone,npoints):
112
112
113 nsubplot = self.voltageObj.nChannels
113 nsubplot = self.voltageObj.nChannels
114 timedata = self.voltageObj.m_BasicHeader.utc
114 timedata = self.voltageObj.m_BasicHeader.utc
115
115
116 for index in range(nsubplot):
116 for index in range(nsubplot):
117 title = titleList[index]
117 title = titleList[index]
118 xlabel = xlabelList[index]
118 xlabel = xlabelList[index]
119 ylabel = ylabelList[index]
119 ylabel = ylabelList[index]
120 subplot = index
120 subplot = index
121 self.colorplotObj.setup(subplot+1,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel,timedata,timezone,npoints)
121 self.colorplotObj.setup(subplot+1,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel,timedata,timezone,npoints)
122
122
123 def plotData(self,
123 def plotData(self,
124 xmin=None,
124 xmin=None,
125 xmax=None,
125 xmax=None,
126 ymin=None,
126 ymin=None,
127 ymax=None,
127 ymax=None,
128 zmin=None,
128 zmin=None,
129 zmax=None,
129 zmax=None,
130 titleList=None,
130 titleList=None,
131 xlabelList=None,
131 xlabelList=None,
132 ylabelList=None,
132 ylabelList=None,
133 winTitle='',
133 winTitle='',
134 timezone='lt',
134 timezone='lt',
135 npoints=1000.0,
135 npoints=1000.0,
136 colormap="br_green",
136 colormap="br_green",
137 showColorbar=True,
137 showColorbar=True,
138 showPowerProfile=True,
138 showPowerProfile=True,
139 XAxisAsTime=True):
139 XAxisAsTime=True,
140 save = False):
140
141
141 databuffer = self.voltageObj.data
142 databuffer = self.voltageObj.data
142 timedata = self.voltageObj.m_BasicHeader.utc
143 timedata = self.voltageObj.m_BasicHeader.utc
143 height = self.voltageObj.heightList
144 height = self.voltageObj.heightList
144 nsubplot = self.voltageObj.nChannels
145 nsubplot = self.voltageObj.nChannels
145 indexPlot = self.indexPlot
146 indexPlot = self.indexPlot
146
147
147 if not(self.__isPlotConfig):
148 if not(self.__isPlotConfig):
148 self.setup(indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime)
149 self.setup(indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime)
149 self.__isPlotConfig = True
150 self.__isPlotConfig = True
150
151
151 if not(self.__isPlotIni):
152 if not(self.__isPlotIni):
152 if titleList == None:
153 if titleList == None:
153 titleList = []
154 titleList = []
154 thisDatetime = datetime.datetime.fromtimestamp(timedata)
155 thisDatetime = datetime.datetime.fromtimestamp(timedata)
155 txtdate = "Date: %s" %(thisDatetime.strftime("%d-%b-%Y"))
156 txtdate = "Date: %s" %(thisDatetime.strftime("%d-%b-%Y"))
156 for i in range(nsubplot):
157 for i in range(nsubplot):
157 titleList.append("Channel: %d %s" %(i, txtdate))
158 titleList.append("Channel: %d %s" %(i, txtdate))
158
159
159 if xlabelList == None:
160 if xlabelList == None:
160 xlabelList = []
161 xlabelList = []
161 for i in range(nsubplot):
162 for i in range(nsubplot):
162 xlabelList.append("")
163 xlabelList.append("")
163
164
164 if ylabelList == None:
165 if ylabelList == None:
165 ylabelList = []
166 ylabelList = []
166 for i in range(nsubplot):
167 for i in range(nsubplot):
167 ylabelList.append("")
168 ylabelList.append("")
168
169
169 if xmin == None: xmin = 0
170 if xmin == None: xmin = 0
170 if xmax == None: xmax = 23
171 if xmax == None: xmax = 23
171 if ymin == None: ymin = min(self.voltageObj.heightList)
172 if ymin == None: ymin = min(self.voltageObj.heightList)
172 if ymax == None: ymax = max(self.voltageObj.heightList)
173 if ymax == None: ymax = max(self.voltageObj.heightList)
173 if zmin == None: zmin = 0
174 if zmin == None: zmin = 0
174 if zmax == None: zmax = 50
175 if zmax == None: zmax = 50
175
176
176
177
177 self.initPlot(xmin,xmax,ymin,ymax,zmin,zmax,titleList,xlabelList,ylabelList,timezone,npoints)
178 self.initPlot(xmin,xmax,ymin,ymax,zmin,zmax,titleList,xlabelList,ylabelList,timezone,npoints)
178 self.__isPlotIni = True
179 self.__isPlotIni = True
179
180
180
181
181 self.colorplotObj.setFigure(indexPlot)
182 self.colorplotObj.setFigure(indexPlot)
182
183
183 if timezone == 'lt':
184 if timezone == 'lt':
184 timedata = timedata - time.timezone
185 timedata = timedata - time.timezone
185
186
186 for index in range(nsubplot):
187 for index in range(nsubplot):
187 data = databuffer[index,:]
188 data = databuffer[index,:]
188 self.colorplotObj.plot(subplot=index+1,x=timedata,y=height,z=data)
189 self.colorplotObj.plot(subplot=index+1,x=timedata,y=height,z=data)
189
190
190 self.colorplotObj.refresh()
191 self.colorplotObj.refresh()
192
193 if save:
194 self.colorplotObj.setFigure(indexPlot)
195 path = "/Users/jro/Pictures"
196 now = datetime.datetime.now().timetuple()
197 file = "rti_img%02d_%03d_%02d%02d%02d.png"%(indexPlot,now[7],now[3],now[4],now[5])
198 filename = os.path.join(path,file)
199 self.colorplotObj.savePlot(indexPlot, filename)
@@ -1,1235 +1,1236
1 '''
1 '''
2 Created on 23/01/2012
2 Created on 23/01/2012
3
3
4 @author $Author$
4 @author $Author$
5 @version $Id$
5 @version $Id$
6 @version $Id$
6 @version $Id$
7 '''
7 '''
8
8
9 import os, sys
9 import os, sys
10 import glob
10 import glob
11 import time
11 import time
12 import numpy
12 import numpy
13 import fnmatch
13 import fnmatch
14 import time, datetime
14 import time, datetime
15
15
16 path = os.path.split(os.getcwd())[0]
16 path = os.path.split(os.getcwd())[0]
17 sys.path.append(path)
17 sys.path.append(path)
18
18
19 from Model.JROHeader import *
19 from Model.JROHeader import *
20 from Model.JROData import JROData
20 from Model.JROData import JROData
21
21
22 def checkForRealPath(path, year, doy, set, ext):
22 def checkForRealPath(path, year, doy, set, ext):
23 """
23 """
24 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
24 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
25 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
25 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
26 el path exacto de un determinado file.
26 el path exacto de un determinado file.
27
27
28 Example :
28 Example :
29 nombre correcto del file es .../.../D2009307/P2009307367.ext
29 nombre correcto del file es .../.../D2009307/P2009307367.ext
30
30
31 Entonces la funcion prueba con las siguientes combinaciones
31 Entonces la funcion prueba con las siguientes combinaciones
32 .../.../x2009307/y2009307367.ext
32 .../.../x2009307/y2009307367.ext
33 .../.../x2009307/Y2009307367.ext
33 .../.../x2009307/Y2009307367.ext
34 .../.../X2009307/y2009307367.ext
34 .../.../X2009307/y2009307367.ext
35 .../.../X2009307/Y2009307367.ext
35 .../.../X2009307/Y2009307367.ext
36 siendo para este caso, la ultima combinacion de letras, identica al file buscado
36 siendo para este caso, la ultima combinacion de letras, identica al file buscado
37
37
38 Return:
38 Return:
39 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
39 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
40 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
40 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
41 para el filename
41 para el filename
42 """
42 """
43 filepath = None
43 filepath = None
44 find_flag = False
44 find_flag = False
45 filename = None
45 filename = None
46
46
47 if ext.lower() == ".r": #voltage
47 if ext.lower() == ".r": #voltage
48 header1 = "dD"
48 header1 = "dD"
49 header2 = "dD"
49 header2 = "dD"
50 elif ext.lower() == ".pdata": #spectra
50 elif ext.lower() == ".pdata": #spectra
51 header1 = "dD"
51 header1 = "dD"
52 header2 = "pP"
52 header2 = "pP"
53 else:
53 else:
54 return None, filename
54 return None, filename
55
55
56 for dir in header1: #barrido por las dos combinaciones posibles de "D"
56 for dir in header1: #barrido por las dos combinaciones posibles de "D"
57 for fil in header2: #barrido por las dos combinaciones posibles de "D"
57 for fil in header2: #barrido por las dos combinaciones posibles de "D"
58 doypath = "%s%04d%03d" % ( dir, year, doy ) #formo el nombre del directorio xYYYYDDD (x=d o x=D)
58 doypath = "%s%04d%03d" % ( dir, year, doy ) #formo el nombre del directorio xYYYYDDD (x=d o x=D)
59 filename = "%s%04d%03d%03d%s" % ( fil, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
59 filename = "%s%04d%03d%03d%s" % ( fil, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
60 filepath = os.path.join( path, doypath, filename ) #formo el path completo
60 filepath = os.path.join( path, doypath, filename ) #formo el path completo
61 if os.path.exists( filepath ): #verifico que exista
61 if os.path.exists( filepath ): #verifico que exista
62 find_flag = True
62 find_flag = True
63 break
63 break
64 if find_flag:
64 if find_flag:
65 break
65 break
66
66
67 if not(find_flag):
67 if not(find_flag):
68 return None, filename
68 return None, filename
69
69
70 return filepath, filename
70 return filepath, filename
71
71
72
72
73 def isNumber(str):
73 def isNumber(str):
74 """
74 """
75 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
75 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
76
76
77 Excepciones:
77 Excepciones:
78 Si un determinado string no puede ser convertido a numero
78 Si un determinado string no puede ser convertido a numero
79 Input:
79 Input:
80 str, string al cual se le analiza para determinar si convertible a un numero o no
80 str, string al cual se le analiza para determinar si convertible a un numero o no
81
81
82 Return:
82 Return:
83 True : si el string es uno numerico
83 True : si el string es uno numerico
84 False : no es un string numerico
84 False : no es un string numerico
85 """
85 """
86 try:
86 try:
87 float( str )
87 float( str )
88 return True
88 return True
89 except:
89 except:
90 return False
90 return False
91
91
92
92
93 def isThisFileinRange(filename, startUTSeconds, endUTSeconds):
93 def isThisFileinRange(filename, startUTSeconds, endUTSeconds):
94 """
94 """
95 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
95 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
96
96
97 Inputs:
97 Inputs:
98 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
98 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
99
99
100 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
100 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
101 segundos contados desde 01/01/1970.
101 segundos contados desde 01/01/1970.
102 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
102 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
103 segundos contados desde 01/01/1970.
103 segundos contados desde 01/01/1970.
104
104
105 Return:
105 Return:
106 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
106 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
107 fecha especificado, de lo contrario retorna False.
107 fecha especificado, de lo contrario retorna False.
108
108
109 Excepciones:
109 Excepciones:
110 Si el archivo no existe o no puede ser abierto
110 Si el archivo no existe o no puede ser abierto
111 Si la cabecera no puede ser leida.
111 Si la cabecera no puede ser leida.
112
112
113 """
113 """
114 m_BasicHeader = BasicHeader()
114 m_BasicHeader = BasicHeader()
115
115
116 try:
116 try:
117 fp = open(filename,'rb')
117 fp = open(filename,'rb')
118 except:
118 except:
119 raise IOError, "The file %s can't be opened" %(filename)
119 raise IOError, "The file %s can't be opened" %(filename)
120
120
121 sts = m_BasicHeader.read(fp)
121 sts = m_BasicHeader.read(fp)
122 fp.close()
122 fp.close()
123
123
124 if not(sts):
124 if not(sts):
125 print "Skipping the file %s because it has not a valid header" %(filename)
125 print "Skipping the file %s because it has not a valid header" %(filename)
126 return 0
126 return 0
127
127
128 if not ((startUTSeconds <= m_BasicHeader.utc) and (endUTSeconds > m_BasicHeader.utc)):
128 if not ((startUTSeconds <= m_BasicHeader.utc) and (endUTSeconds > m_BasicHeader.utc)):
129 return 0
129 return 0
130
130
131 return 1
131 return 1
132
132
133
133
134 def getlastFileFromPath(path, ext):
134 def getlastFileFromPath(path, ext):
135 """
135 """
136 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
136 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
137 al final de la depuracion devuelve el ultimo file de la lista que quedo.
137 al final de la depuracion devuelve el ultimo file de la lista que quedo.
138
138
139 Input:
139 Input:
140 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
140 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
141 ext : extension de los files contenidos en una carpeta
141 ext : extension de los files contenidos en una carpeta
142
142
143 Return:
143 Return:
144 El ultimo file de una determinada carpeta, no se considera el path.
144 El ultimo file de una determinada carpeta, no se considera el path.
145 """
145 """
146 validFilelist = []
146 validFilelist = []
147 fileList = os.listdir(path)
147 fileList = os.listdir(path)
148
148
149 # 0 1234 567 89A BCDE
149 # 0 1234 567 89A BCDE
150 # H YYYY DDD SSS .ext
150 # H YYYY DDD SSS .ext
151
151
152 for file in fileList:
152 for file in fileList:
153 try:
153 try:
154 year = int(file[1:5])
154 year = int(file[1:5])
155 doy = int(file[5:8])
155 doy = int(file[5:8])
156
156
157 if (os.path.splitext(file)[-1].upper() != ext.upper()) : continue
157 if (os.path.splitext(file)[-1].upper() != ext.upper()) : continue
158 except:
158 except:
159 continue
159 continue
160
160
161 validFilelist.append(file)
161 validFilelist.append(file)
162
162
163 if validFilelist:
163 if validFilelist:
164 validFilelist = sorted( validFilelist, key=str.lower )
164 validFilelist = sorted( validFilelist, key=str.lower )
165 return validFilelist[-1]
165 return validFilelist[-1]
166
166
167 return None
167 return None
168
168
169 class JRODataIO:
169 class JRODataIO:
170
170
171 #speed of light
171 #speed of light
172 c = 3E8
172 c = 3E8
173
173
174 m_BasicHeader = BasicHeader()
174 m_BasicHeader = BasicHeader()
175
175
176 m_SystemHeader = SystemHeader()
176 m_SystemHeader = SystemHeader()
177
177
178 m_RadarControllerHeader = RadarControllerHeader()
178 m_RadarControllerHeader = RadarControllerHeader()
179
179
180 m_ProcessingHeader = ProcessingHeader()
180 m_ProcessingHeader = ProcessingHeader()
181
181
182 dataOutObj = None
182 dataOutObj = None
183
183
184 online = 0
184 online = 0
185
185
186 fp = None
186 fp = None
187
187
188 dataType = None
188 dataType = None
189
189
190 fileSizeByHeader = None
190 fileSizeByHeader = None
191
191
192 filenameList = []
192 filenameList = []
193
193
194 filename = None
194 filename = None
195
195
196 fileSize = None
196 fileSize = None
197
197
198 firstHeaderSize = 0
198 firstHeaderSize = 0
199
199
200 basicHeaderSize = 24
200 basicHeaderSize = 24
201
201
202 nTotalBlocks = 0
202 nTotalBlocks = 0
203
203
204 ippSeconds = 0
204 ippSeconds = 0
205
205
206 blocksize = 0
206 blocksize = 0
207
207
208 set = 0
208 set = 0
209
209
210 ext = None
210 ext = None
211
211
212 path = None
212 path = None
213
213
214 maxTimeStep = 30
214 maxTimeStep = 30
215
215
216
216
217 delay = 3 #seconds
217 delay = 3 #seconds
218
218
219 nTries = 3 #quantity tries
219 nTries = 3 #quantity tries
220
220
221 nFiles = 3 #number of files for searching
221 nFiles = 3 #number of files for searching
222
222
223
223
224 flagNoMoreFiles = 0
224 flagNoMoreFiles = 0
225
225
226 flagIsNewFile = 1
226 flagIsNewFile = 1
227
227
228 flagResetProcessing = 0
228 flagResetProcessing = 0
229
229
230 flagIsNewBlock = 0
230 flagIsNewBlock = 0
231
231
232 def __init__(self):
232 def __init__(self):
233 pass
233 pass
234
234
235 class JRODataReader(JRODataIO):
235 class JRODataReader(JRODataIO):
236
236
237 """
237 """
238 Esta clase es usada como la clase padre de las clases VoltageReader y SpectraReader.
238 Esta clase es usada como la clase padre de las clases VoltageReader y SpectraReader.
239 Contiene todos lo metodos necesarios para leer datos desde archivos en formato
239 Contiene todos lo metodos necesarios para leer datos desde archivos en formato
240 jicamarca o pdata (.r o .pdata). La lectura de los datos siempre se realiza por bloques. Los datos
240 jicamarca o pdata (.r o .pdata). La lectura de los datos siempre se realiza por bloques. Los datos
241 leidos son array de 3 dimensiones:
241 leidos son array de 3 dimensiones:
242
242
243 Para Voltajes - perfiles * alturas * canales
243 Para Voltajes - perfiles * alturas * canales
244
244
245 Para Spectra - paresCanalesIguales * alturas * perfiles (Self Spectra)
245 Para Spectra - paresCanalesIguales * alturas * perfiles (Self Spectra)
246 paresCanalesDiferentes * alturas * perfiles (Cross Spectra)
246 paresCanalesDiferentes * alturas * perfiles (Cross Spectra)
247 canales * alturas (DC Channels)
247 canales * alturas (DC Channels)
248
248
249 y son almacenados en su buffer respectivo.
249 y son almacenados en su buffer respectivo.
250
250
251 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
251 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
252 RadarControllerHeader y DataObj. Los tres primeros se usan para almacenar informacion de la
252 RadarControllerHeader y DataObj. Los tres primeros se usan para almacenar informacion de la
253 cabecera de datos (metadata), y el cuarto (DataObj) para obtener y almacenar los datos desde
253 cabecera de datos (metadata), y el cuarto (DataObj) para obtener y almacenar los datos desde
254 el buffer de datos cada vez que se ejecute el metodo "getData".
254 el buffer de datos cada vez que se ejecute el metodo "getData".
255 """
255 """
256
256
257 nReadBlocks = 0
257 nReadBlocks = 0
258
258
259 def __init__(self, dataOutObj=None):
259 def __init__(self, dataOutObj=None):
260
260
261 raise ValueError, "This class can't be instanced"
261 raise ValueError, "This class can't be instanced"
262
262
263
263
264 def hasNotDataInBuffer(self):
264 def hasNotDataInBuffer(self):
265
265
266 raise ValueError, "Not implemented"
266 raise ValueError, "Not implemented"
267
267
268 def getBlockDimension(self):
268 def getBlockDimension(self):
269
269
270 raise ValueError, "No implemented"
270 raise ValueError, "No implemented"
271
271
272 def readBlock(self):
272 def readBlock(self):
273
273
274 self.nTotalBlocks += 1
274 self.nTotalBlocks += 1
275 self.nReadBlocks += 1
275 self.nReadBlocks += 1
276
276
277 raise ValueError, "This method has not been implemented"
277 raise ValueError, "This method has not been implemented"
278
278
279 def getData( self ):
279 def getData( self ):
280
280
281 raise ValueError, "This method has not been implemented"
281 raise ValueError, "This method has not been implemented"
282
282
283 def createObjByDefault(self):
283 def createObjByDefault(self):
284 """
284 """
285 Los objetos creados por defecto por cada clase (Voltaje o Espectro) difieren en el tipo
285 Los objetos creados por defecto por cada clase (Voltaje o Espectro) difieren en el tipo
286 raise ValueError, "This method has not been implemented
286 raise ValueError, "This method has not been implemented
287 """
287 """
288 raise ValueError, "This method has not been implemented"
288 raise ValueError, "This method has not been implemented"
289
289
290 # def setup(self, dataOutObj=None, path=None, startDateTime=None, endDateTime=None, set=0, expLabel = "", ext = None, online = 0):
290 def setup(self, dataOutObj=None, path=None, startDateTime=None, endDateTime=None, set=0, expLabel = "", ext = None, online = 0):
291 def setup(self, dataOutObj=None, path=None, startDateTime=None, endDateTime=None, set=0, expLabel = "", ext = None, online = 0):
291 """
292 """
292 setup configura los parametros de lectura de la clase DataReader.
293 setup configura los parametros de lectura de la clase DataReader.
293
294
294 Si el modo de lectura es offline, primero se realiza una busqueda de todos los archivos
295 Si el modo de lectura es offline, primero se realiza una busqueda de todos los archivos
295 que coincidan con los parametros especificados; esta lista de archivos son almacenados en
296 que coincidan con los parametros especificados; esta lista de archivos son almacenados en
296 self.filenameList.
297 self.filenameList.
297
298
298 Input:
299 Input:
299 path : Directorios donde se ubican los datos a leer. Dentro de este
300 path : Directorios donde se ubican los datos a leer. Dentro de este
300 directorio deberia de estar subdirectorios de la forma:
301 directorio deberia de estar subdirectorios de la forma:
301
302
302 path/D[yyyy][ddd]/expLabel/P[yyyy][ddd][sss][ext]
303 path/D[yyyy][ddd]/expLabel/P[yyyy][ddd][sss][ext]
303
304
304 startDateTime : Fecha inicial. Rechaza todos los archivos donde
305 startDateTime : Fecha inicial. Rechaza todos los archivos donde
305 file end time < startDatetime (obejto datetime.datetime)
306 file end time < startDatetime (obejto datetime.datetime)
306
307
307 endDateTime : Fecha final. Si no es None, rechaza todos los archivos donde
308 endDateTime : Fecha final. Si no es None, rechaza todos los archivos donde
308 file end time < startDatetime (obejto datetime.datetime)
309 file end time < startDatetime (obejto datetime.datetime)
309
310
310 set : Set del primer archivo a leer. Por defecto None
311 set : Set del primer archivo a leer. Por defecto None
311
312
312 expLabel : Nombre del subdirectorio de datos. Por defecto ""
313 expLabel : Nombre del subdirectorio de datos. Por defecto ""
313
314
314 ext : Extension de los archivos a leer. Por defecto .r
315 ext : Extension de los archivos a leer. Por defecto .r
315
316
316 online : Si es == a 0 entonces busca files que cumplan con las condiciones dadas
317 online : Si es == a 0 entonces busca files que cumplan con las condiciones dadas
317
318
318 Return:
319 Return:
319 0 : Si no encuentra files que cumplan con las condiciones dadas
320 0 : Si no encuentra files que cumplan con las condiciones dadas
320 1 : Si encuentra files que cumplan con las condiciones dadas
321 1 : Si encuentra files que cumplan con las condiciones dadas
321
322
322 Affected:
323 Affected:
323 self.startUTCSeconds
324 self.startUTCSeconds
324 self.endUTCSeconds
325 self.endUTCSeconds
325 self.startYear
326 self.startYear
326 self.endYear
327 self.endYear
327 self.startDoy
328 self.startDoy
328 self.endDoy
329 self.endDoy
329 self.pathList
330 self.pathList
330 self.filenameList
331 self.filenameList
331 self.online
332 self.online
332 """
333 """
333 if path == None:
334 if path == None:
334 raise ValueError, "The path is not valid"
335 raise ValueError, "The path is not valid"
335
336
336 if ext == None:
337 if ext == None:
337 ext = self.ext
338 ext = self.ext
338
339
339 if dataOutObj == None:
340 if dataOutObj == None:
340 dataOutObj = self.createObjByDefault()
341 dataOutObj = self.createObjByDefault()
341
342
342 self.dataOutObj = dataOutObj
343 self.dataOutObj = dataOutObj
343
344
344 if online:
345 if online:
345 print "Searching files ..."
346 print "Searching files ..."
346 doypath, file, year, doy, set = self.__searchFilesOnLine(path, startDateTime, endDateTime, expLabel, ext)
347 doypath, file, year, doy, set = self.__searchFilesOnLine(path, startDateTime, endDateTime, expLabel, ext)
347
348
348 if not(doypath):
349 if not(doypath):
349 for nTries in range( self.nTries ):
350 for nTries in range( self.nTries ):
350 print '\tWaiting %0.2f sec for valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
351 print '\tWaiting %0.2f sec for valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
351 time.sleep( self.delay )
352 time.sleep( self.delay )
352 doypath, file, year, doy, set = self.__searchFilesOnLine(path, startDateTime, endDateTime, expLabel, ext)
353 doypath, file, year, doy, set = self.__searchFilesOnLine(path, startDateTime, endDateTime, expLabel, ext)
353 if doypath:
354 if doypath:
354 break
355 break
355
356
356 if not(doypath):
357 if not(doypath):
357 print "There 'isn't valied files in %s" % path
358 print "There 'isn't valied files in %s" % path
358 return None
359 return None
359
360
360 self.year = year
361 self.year = year
361 self.doy = doy
362 self.doy = doy
362 self.set = set - 1
363 self.set = set - 1
363 self.path = path
364 self.path = path
364
365
365 else: # offline
366 else: # offline
366 pathList, filenameList = self.__searchFilesOffLine(path, startDateTime, endDateTime, set, expLabel, ext)
367 pathList, filenameList = self.__searchFilesOffLine(path, startDateTime, endDateTime, set, expLabel, ext)
367 if not(pathList):
368 if not(pathList):
368 print "No files in range: %s - %s" %(startDateTime.ctime(), endDateTime.ctime())
369 print "No files in range: %s - %s" %(startDateTime.ctime(), endDateTime.ctime())
369 return None
370 return None
370
371
371 self.fileIndex = -1
372 self.fileIndex = -1
372 self.pathList = pathList
373 self.pathList = pathList
373 self.filenameList = filenameList
374 self.filenameList = filenameList
374
375
375 self.online = online
376 self.online = online
376 self.ext = ext
377 self.ext = ext
377
378
378 ext = ext.lower()
379 ext = ext.lower()
379
380
380 if not( self.setNextFile() ):
381 if not( self.setNextFile() ):
381 if (startDateTime != None) and (endDateTime != None):
382 if (startDateTime != None) and (endDateTime != None):
382 print "No files in range: %s - %s" %(startDateTime.ctime(), endDateTime.ctime())
383 print "No files in range: %s - %s" %(startDateTime.ctime(), endDateTime.ctime())
383 elif startDateTime != None:
384 elif startDateTime != None:
384 print "No files in : %s" % startDateTime.ctime()
385 print "No files in : %s" % startDateTime.ctime()
385 else:
386 else:
386 print "No files"
387 print "No files"
387 return None
388 return None
388
389
389 if startDateTime != None:
390 if startDateTime != None:
390 self.startUTCSeconds = time.mktime(startDateTime.timetuple())
391 self.startUTCSeconds = time.mktime(startDateTime.timetuple())
391 self.startYear = startDateTime.timetuple().tm_year
392 self.startYear = startDateTime.timetuple().tm_year
392 self.startDoy = startDateTime.timetuple().tm_yday
393 self.startDoy = startDateTime.timetuple().tm_yday
393
394
394 if endDateTime != None:
395 if endDateTime != None:
395 self.endUTCSeconds = time.mktime(endDateTime.timetuple())
396 self.endUTCSeconds = time.mktime(endDateTime.timetuple())
396 self.endYear = endDateTime.timetuple().tm_year
397 self.endYear = endDateTime.timetuple().tm_year
397 self.endDoy = endDateTime.timetuple().tm_yday
398 self.endDoy = endDateTime.timetuple().tm_yday
398 #call fillHeaderValues() - to Data Object
399 #call fillHeaderValues() - to Data Object
399
400
400 self.updateDataHeader()
401 self.updateDataHeader()
401
402
402 return self.dataOutObj
403 return self.dataOutObj
403
404
404 def __rdSystemHeader(self, fp=None):
405 def __rdSystemHeader(self, fp=None):
405
406
406 if fp == None:
407 if fp == None:
407 fp = self.fp
408 fp = self.fp
408
409
409 self.m_SystemHeader.read(fp)
410 self.m_SystemHeader.read(fp)
410
411
411
412
412 def __rdRadarControllerHeader(self, fp=None):
413 def __rdRadarControllerHeader(self, fp=None):
413 if fp == None:
414 if fp == None:
414 fp = self.fp
415 fp = self.fp
415
416
416 self.m_RadarControllerHeader.read(fp)
417 self.m_RadarControllerHeader.read(fp)
417
418
418
419
419 def __rdProcessingHeader(self, fp=None):
420 def __rdProcessingHeader(self, fp=None):
420 if fp == None:
421 if fp == None:
421 fp = self.fp
422 fp = self.fp
422
423
423 self.m_ProcessingHeader.read(fp)
424 self.m_ProcessingHeader.read(fp)
424
425
425
426
426 def __rdBasicHeader(self, fp=None):
427 def __rdBasicHeader(self, fp=None):
427
428
428 if fp == None:
429 if fp == None:
429 fp = self.fp
430 fp = self.fp
430
431
431 self.m_BasicHeader.read(fp)
432 self.m_BasicHeader.read(fp)
432
433
433 def __readFirstHeader(self):
434 def __readFirstHeader(self):
434 """
435 """
435 Lectura del First Header, es decir el Basic Header y el Long Header
436 Lectura del First Header, es decir el Basic Header y el Long Header
436
437
437 Affected:
438 Affected:
438 self.m_BasicHeader
439 self.m_BasicHeader
439 self.m_SystemHeader
440 self.m_SystemHeader
440 self.m_RadarControllerHeader
441 self.m_RadarControllerHeader
441 self.m_ProcessingHeader
442 self.m_ProcessingHeader
442 self.firstHeaderSize
443 self.firstHeaderSize
443 self.dataType
444 self.dataType
444 self.fileSizeByHeader
445 self.fileSizeByHeader
445 self.ippSeconds
446 self.ippSeconds
446
447
447 Return:
448 Return:
448 None
449 None
449 """
450 """
450 self.__rdBasicHeader()
451 self.__rdBasicHeader()
451 self.__rdSystemHeader()
452 self.__rdSystemHeader()
452 self.__rdRadarControllerHeader()
453 self.__rdRadarControllerHeader()
453 self.__rdProcessingHeader()
454 self.__rdProcessingHeader()
454 self.firstHeaderSize = self.m_BasicHeader.size
455 self.firstHeaderSize = self.m_BasicHeader.size
455
456
456 datatype = int(numpy.log2((self.m_ProcessingHeader.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
457 datatype = int(numpy.log2((self.m_ProcessingHeader.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
457 if datatype == 0:
458 if datatype == 0:
458 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
459 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
459
460
460 elif datatype == 1:
461 elif datatype == 1:
461 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
462 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
462
463
463 elif datatype == 2:
464 elif datatype == 2:
464 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
465 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
465
466
466 elif datatype == 3:
467 elif datatype == 3:
467 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
468 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
468
469
469 elif datatype == 4:
470 elif datatype == 4:
470 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
471 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
471
472
472 elif datatype == 5:
473 elif datatype == 5:
473 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
474 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
474
475
475 else:
476 else:
476 raise ValueError, 'Data type was not defined'
477 raise ValueError, 'Data type was not defined'
477
478
478 self.dataType = datatype_str
479 self.dataType = datatype_str
479 self.ippSeconds = 2 * 1000 * self.m_RadarControllerHeader.ipp / self.c
480 self.ippSeconds = 2 * 1000 * self.m_RadarControllerHeader.ipp / self.c
480
481
481 self.fileSizeByHeader = self.m_ProcessingHeader.dataBlocksPerFile * self.m_ProcessingHeader.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.m_ProcessingHeader.dataBlocksPerFile - 1)
482 self.fileSizeByHeader = self.m_ProcessingHeader.dataBlocksPerFile * self.m_ProcessingHeader.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.m_ProcessingHeader.dataBlocksPerFile - 1)
482 self.dataOutObj.channelList = numpy.arange(self.m_SystemHeader.numChannels)
483 self.dataOutObj.channelList = numpy.arange(self.m_SystemHeader.numChannels)
483 self.dataOutObj.channelIndexList = numpy.arange(self.m_SystemHeader.numChannels)
484 self.dataOutObj.channelIndexList = numpy.arange(self.m_SystemHeader.numChannels)
484
485
485 self.getBlockDimension()
486 self.getBlockDimension()
486
487
487
488
488 def __setNewBlock(self):
489 def __setNewBlock(self):
489 """
490 """
490 Lee el Basic Header y posiciona le file pointer en la posicion inicial del bloque a leer
491 Lee el Basic Header y posiciona le file pointer en la posicion inicial del bloque a leer
491
492
492 Affected:
493 Affected:
493 self.m_BasicHeader
494 self.m_BasicHeader
494 self.flagNoContinuousBlock
495 self.flagNoContinuousBlock
495 self.ns
496 self.ns
496
497
497 Return:
498 Return:
498 0 : Si el file no tiene un Basic Header que pueda ser leido
499 0 : Si el file no tiene un Basic Header que pueda ser leido
499 1 : Si se pudo leer el Basic Header
500 1 : Si se pudo leer el Basic Header
500 """
501 """
501 if self.fp == None:
502 if self.fp == None:
502 return 0
503 return 0
503
504
504 if self.flagIsNewFile:
505 if self.flagIsNewFile:
505 return 1
506 return 1
506
507
507 self.lastUTTime = self.m_BasicHeader.utc
508 self.lastUTTime = self.m_BasicHeader.utc
508
509
509 currentSize = self.fileSize - self.fp.tell()
510 currentSize = self.fileSize - self.fp.tell()
510 neededSize = self.m_ProcessingHeader.blockSize + self.basicHeaderSize
511 neededSize = self.m_ProcessingHeader.blockSize + self.basicHeaderSize
511
512
512 #If there is enough data setting new data block
513 #If there is enough data setting new data block
513 if ( currentSize >= neededSize ):
514 if ( currentSize >= neededSize ):
514 self.__rdBasicHeader()
515 self.__rdBasicHeader()
515 return 1
516 return 1
516
517
517 #si es OnLine y ademas aun no se han leido un bloque completo entonces se espera por uno valido
518 #si es OnLine y ademas aun no se han leido un bloque completo entonces se espera por uno valido
518 if self.online and (self.nReadBlocks < self.m_ProcessingHeader.dataBlocksPerFile):
519 if self.online and (self.nReadBlocks < self.m_ProcessingHeader.dataBlocksPerFile):
519
520
520 fpointer = self.fp.tell()
521 fpointer = self.fp.tell()
521
522
522 for nTries in range( self.nTries ):
523 for nTries in range( self.nTries ):
523 #self.fp.close()
524 #self.fp.close()
524
525
525 print "\tWaiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
526 print "\tWaiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
526 time.sleep( self.delay )
527 time.sleep( self.delay )
527
528
528 #self.fp = open( self.filename, 'rb' )
529 #self.fp = open( self.filename, 'rb' )
529 #self.fp.seek( fpointer )
530 #self.fp.seek( fpointer )
530
531
531 self.fileSize = os.path.getsize( self.filename )
532 self.fileSize = os.path.getsize( self.filename )
532 currentSize = self.fileSize - fpointer
533 currentSize = self.fileSize - fpointer
533
534
534 if ( currentSize >= neededSize ):
535 if ( currentSize >= neededSize ):
535 self.__rdBasicHeader()
536 self.__rdBasicHeader()
536 return 1
537 return 1
537
538
538 #Setting new file
539 #Setting new file
539 if not( self.setNextFile() ):
540 if not( self.setNextFile() ):
540 return 0
541 return 0
541
542
542 deltaTime = self.m_BasicHeader.utc - self.lastUTTime # check this
543 deltaTime = self.m_BasicHeader.utc - self.lastUTTime # check this
543
544
544 self.flagResetProcessing = 0
545 self.flagResetProcessing = 0
545
546
546 if deltaTime > self.maxTimeStep:
547 if deltaTime > self.maxTimeStep:
547 self.flagResetProcessing = 1
548 self.flagResetProcessing = 1
548
549
549 return 1
550 return 1
550
551
551 def readNextBlock(self):
552 def readNextBlock(self):
552 """
553 """
553 Establece un nuevo bloque de datos a leer y los lee, si es que no existiese
554 Establece un nuevo bloque de datos a leer y los lee, si es que no existiese
554 mas bloques disponibles en el archivo actual salta al siguiente.
555 mas bloques disponibles en el archivo actual salta al siguiente.
555
556
556 Affected:
557 Affected:
557 self.lastUTTime
558 self.lastUTTime
558
559
559 Return: None
560 Return: None
560 """
561 """
561
562
562 if not(self.__setNewBlock()):
563 if not(self.__setNewBlock()):
563 return 0
564 return 0
564
565
565 if not(self.readBlock()):
566 if not(self.readBlock()):
566 return 0
567 return 0
567
568
568 return 1
569 return 1
569
570
570 def __setNextFileOnline(self):
571 def __setNextFileOnline(self):
571 """
572 """
572 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
573 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
573 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
574 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
574 siguientes.
575 siguientes.
575
576
576 Affected:
577 Affected:
577 self.flagIsNewFile
578 self.flagIsNewFile
578 self.filename
579 self.filename
579 self.fileSize
580 self.fileSize
580 self.fp
581 self.fp
581 self.set
582 self.set
582 self.flagNoMoreFiles
583 self.flagNoMoreFiles
583
584
584 Return:
585 Return:
585 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
586 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
586 1 : si el file fue abierto con exito y esta listo a ser leido
587 1 : si el file fue abierto con exito y esta listo a ser leido
587
588
588 Excepciones:
589 Excepciones:
589 Si un determinado file no puede ser abierto
590 Si un determinado file no puede ser abierto
590 """
591 """
591 nFiles = 0
592 nFiles = 0
592 fileOk_flag = False
593 fileOk_flag = False
593 firstTime_flag = True
594 firstTime_flag = True
594
595
595 self.set += 1
596 self.set += 1
596
597
597 #busca el 1er file disponible
598 #busca el 1er file disponible
598 file, filename = checkForRealPath( self.path, self.year, self.doy, self.set, self.ext )
599 file, filename = checkForRealPath( self.path, self.year, self.doy, self.set, self.ext )
599 if file:
600 if file:
600 if self.__verifyFile(file, False):
601 if self.__verifyFile(file, False):
601 fileOk_flag = True
602 fileOk_flag = True
602
603
603 #si no encuentra un file entonces espera y vuelve a buscar
604 #si no encuentra un file entonces espera y vuelve a buscar
604 if not(fileOk_flag):
605 if not(fileOk_flag):
605 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
606 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
606
607
607 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
608 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
608 tries = self.nTries
609 tries = self.nTries
609 else:
610 else:
610 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
611 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
611
612
612 for nTries in range( tries ):
613 for nTries in range( tries ):
613 if firstTime_flag:
614 if firstTime_flag:
614 print "\tWaiting %0.2f sec for new \"%s\" file, try %03d ..." % ( self.delay, filename, nTries+1 )
615 print "\tWaiting %0.2f sec for new \"%s\" file, try %03d ..." % ( self.delay, filename, nTries+1 )
615 time.sleep( self.delay )
616 time.sleep( self.delay )
616 else:
617 else:
617 print "\tSearching next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
618 print "\tSearching next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
618
619
619 file, filename = checkForRealPath( self.path, self.year, self.doy, self.set, self.ext )
620 file, filename = checkForRealPath( self.path, self.year, self.doy, self.set, self.ext )
620 if file:
621 if file:
621 if self.__verifyFile(file):
622 if self.__verifyFile(file):
622 fileOk_flag = True
623 fileOk_flag = True
623 break
624 break
624
625
625 if fileOk_flag:
626 if fileOk_flag:
626 break
627 break
627
628
628 firstTime_flag = False
629 firstTime_flag = False
629
630
630 print "\tSkipping the file \"%s\" due to this file doesn't exist yet" % filename
631 print "\tSkipping the file \"%s\" due to this file doesn't exist yet" % filename
631 self.set += 1
632 self.set += 1
632
633
633 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
634 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
634 self.set = 0
635 self.set = 0
635 self.doy += 1
636 self.doy += 1
636
637
637 if fileOk_flag:
638 if fileOk_flag:
638 self.fileSize = os.path.getsize( file )
639 self.fileSize = os.path.getsize( file )
639 self.filename = file
640 self.filename = file
640 self.flagIsNewFile = 1
641 self.flagIsNewFile = 1
641 if self.fp != None: self.fp.close()
642 if self.fp != None: self.fp.close()
642 self.fp = open(file)
643 self.fp = open(file)
643 self.flagNoMoreFiles = 0
644 self.flagNoMoreFiles = 0
644 print 'Setting the file: %s' % file
645 print 'Setting the file: %s' % file
645 else:
646 else:
646 self.fileSize = 0
647 self.fileSize = 0
647 self.filename = None
648 self.filename = None
648 self.flagIsNewFile = 0
649 self.flagIsNewFile = 0
649 self.fp = None
650 self.fp = None
650 self.flagNoMoreFiles = 1
651 self.flagNoMoreFiles = 1
651 print 'No more Files'
652 print 'No more Files'
652
653
653 return fileOk_flag
654 return fileOk_flag
654
655
655
656
656 def __setNextFileOffline(self):
657 def __setNextFileOffline(self):
657 """
658 """
658 Busca el siguiente file dentro de un folder que tenga suficiente data para ser leida
659 Busca el siguiente file dentro de un folder que tenga suficiente data para ser leida
659
660
660 Affected:
661 Affected:
661 self.flagIsNewFile
662 self.flagIsNewFile
662 self.fileIndex
663 self.fileIndex
663 self.filename
664 self.filename
664 self.fileSize
665 self.fileSize
665 self.fp
666 self.fp
666
667
667 Return:
668 Return:
668 0 : si un determinado file no puede ser abierto
669 0 : si un determinado file no puede ser abierto
669 1 : si el file fue abierto con exito
670 1 : si el file fue abierto con exito
670
671
671 Excepciones:
672 Excepciones:
672 Si un determinado file no puede ser abierto
673 Si un determinado file no puede ser abierto
673 """
674 """
674 idFile = self.fileIndex
675 idFile = self.fileIndex
675
676
676 while(True):
677 while(True):
677
678
678 idFile += 1
679 idFile += 1
679
680
680 if not(idFile < len(self.filenameList)):
681 if not(idFile < len(self.filenameList)):
681 self.flagNoMoreFiles = 1
682 self.flagNoMoreFiles = 1
682 print 'No more Files'
683 print 'No more Files'
683 return 0
684 return 0
684
685
685 filename = self.filenameList[idFile]
686 filename = self.filenameList[idFile]
686
687
687 if not(self.__verifyFile(filename)):
688 if not(self.__verifyFile(filename)):
688 continue
689 continue
689
690
690 fileSize = os.path.getsize(filename)
691 fileSize = os.path.getsize(filename)
691 fp = open(filename,'rb')
692 fp = open(filename,'rb')
692 break
693 break
693
694
694 self.flagIsNewFile = 1
695 self.flagIsNewFile = 1
695 self.fileIndex = idFile
696 self.fileIndex = idFile
696 self.filename = filename
697 self.filename = filename
697 self.fileSize = fileSize
698 self.fileSize = fileSize
698 self.fp = fp
699 self.fp = fp
699
700
700 print 'Setting the file: %s'%self.filename
701 print 'Setting the file: %s'%self.filename
701
702
702 return 1
703 return 1
703
704
704
705
705 def setNextFile(self):
706 def setNextFile(self):
706 """
707 """
707 Determina el siguiente file a leer y si hay uno disponible lee el First Header
708 Determina el siguiente file a leer y si hay uno disponible lee el First Header
708
709
709 Affected:
710 Affected:
710 self.m_BasicHeader
711 self.m_BasicHeader
711 self.m_SystemHeader
712 self.m_SystemHeader
712 self.m_RadarControllerHeader
713 self.m_RadarControllerHeader
713 self.m_ProcessingHeader
714 self.m_ProcessingHeader
714 self.firstHeaderSize
715 self.firstHeaderSize
715
716
716 Return:
717 Return:
717 0 : Si no hay files disponibles
718 0 : Si no hay files disponibles
718 1 : Si hay mas files disponibles
719 1 : Si hay mas files disponibles
719 """
720 """
720 if self.fp != None:
721 if self.fp != None:
721 self.fp.close()
722 self.fp.close()
722
723
723 if self.online:
724 if self.online:
724 newFile = self.__setNextFileOnline()
725 newFile = self.__setNextFileOnline()
725 else:
726 else:
726 newFile = self.__setNextFileOffline()
727 newFile = self.__setNextFileOffline()
727
728
728 if not(newFile):
729 if not(newFile):
729 return 0
730 return 0
730
731
731 self.__readFirstHeader()
732 self.__readFirstHeader()
732 self.nReadBlocks = 0
733 self.nReadBlocks = 0
733 return 1
734 return 1
734
735
735 def __searchFilesOnLine(self, path, startDateTime=None, endDateTime=None, expLabel = "", ext = None):
736 def __searchFilesOnLine(self, path, startDateTime=None, endDateTime=None, expLabel = "", ext = None):
736 """
737 """
737 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
738 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
738 devuelve el archivo encontrado ademas de otros datos.
739 devuelve el archivo encontrado ademas de otros datos.
739
740
740 Input:
741 Input:
741 path : carpeta donde estan contenidos los files que contiene data
742 path : carpeta donde estan contenidos los files que contiene data
742 startDateTime : punto especifico en el tiempo del cual se requiere la data
743 startDateTime : punto especifico en el tiempo del cual se requiere la data
743 ext : extension de los files
744 ext : extension de los files
744
745
745 Return:
746 Return:
746 year : el anho
747 year : el anho
747 doy : el numero de dia del anho
748 doy : el numero de dia del anho
748 set : el set del archivo
749 set : el set del archivo
749 filename : el ultimo file de una determinada carpeta
750 filename : el ultimo file de una determinada carpeta
750 directory : eL directorio donde esta el file encontrado
751 directory : eL directorio donde esta el file encontrado
751 """
752 """
752 dirList = []
753 dirList = []
753 pathList = []
754 pathList = []
754 directory = None
755 directory = None
755
756
756 for thisPath in os.listdir(path):
757 for thisPath in os.listdir(path):
757 if os.path.isdir(os.path.join(path,thisPath)):
758 if os.path.isdir(os.path.join(path,thisPath)):
758 dirList.append(thisPath)
759 dirList.append(thisPath)
759
760
760 if not(dirList):
761 if not(dirList):
761 return None, None, None, None, None
762 return None, None, None, None, None
762
763
763 dirList = sorted( dirList, key=str.lower )
764 dirList = sorted( dirList, key=str.lower )
764
765
765 if startDateTime:
766 if startDateTime:
766 thisDateTime = startDateTime
767 thisDateTime = startDateTime
767 if endDateTime == None: endDateTime = startDateTime
768 if endDateTime == None: endDateTime = startDateTime
768
769
769 while(thisDateTime <= endDateTime):
770 while(thisDateTime <= endDateTime):
770 year = thisDateTime.timetuple().tm_year
771 year = thisDateTime.timetuple().tm_year
771 doy = thisDateTime.timetuple().tm_yday
772 doy = thisDateTime.timetuple().tm_yday
772
773
773 match = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy))
774 match = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy))
774 if len(match) == 0:
775 if len(match) == 0:
775 thisDateTime += datetime.timedelta(1)
776 thisDateTime += datetime.timedelta(1)
776 continue
777 continue
777
778
778 pathList.append(os.path.join(path,match[0], expLabel))
779 pathList.append(os.path.join(path,match[0], expLabel))
779 thisDateTime += datetime.timedelta(1)
780 thisDateTime += datetime.timedelta(1)
780
781
781 if not(pathList):
782 if not(pathList):
782 print "\tNo files in range: %s - %s" %(startDateTime.ctime(), endDateTime.ctime())
783 print "\tNo files in range: %s - %s" %(startDateTime.ctime(), endDateTime.ctime())
783 return None, None, None, None, None
784 return None, None, None, None, None
784
785
785 directory = pathList[0]
786 directory = pathList[0]
786
787
787 else:
788 else:
788 directory = dirList[-1]
789 directory = dirList[-1]
789 directory = os.path.join(path,directory)
790 directory = os.path.join(path,directory)
790
791
791 filename = getlastFileFromPath(directory, ext)
792 filename = getlastFileFromPath(directory, ext)
792
793
793 if not(filename):
794 if not(filename):
794 return None, None, None, None, None
795 return None, None, None, None, None
795
796
796 if not(self.__verifyFile(os.path.join(directory, filename))):
797 if not(self.__verifyFile(os.path.join(directory, filename))):
797 return None, None, None, None, None
798 return None, None, None, None, None
798
799
799 year = int( filename[1:5] )
800 year = int( filename[1:5] )
800 doy = int( filename[5:8] )
801 doy = int( filename[5:8] )
801 set = int( filename[8:11] )
802 set = int( filename[8:11] )
802
803
803 return directory, filename, year, doy, set
804 return directory, filename, year, doy, set
804
805
805
806
806 def __searchFilesOffLine(self, path, startDateTime, endDateTime, set=None, expLabel = "", ext = ".r"):
807 def __searchFilesOffLine(self, path, startDateTime, endDateTime, set=None, expLabel = "", ext = ".r"):
807 """
808 """
808 Realiza una busqueda de los archivos que coincidan con los parametros
809 Realiza una busqueda de los archivos que coincidan con los parametros
809 especificados y se encuentren ubicados en el path indicado. Para realizar una busqueda
810 especificados y se encuentren ubicados en el path indicado. Para realizar una busqueda
810 correcta la estructura de directorios debe ser la siguiente:
811 correcta la estructura de directorios debe ser la siguiente:
811
812
812 ...path/D[yyyy][ddd]/expLabel/D[yyyy][ddd][sss].ext
813 ...path/D[yyyy][ddd]/expLabel/D[yyyy][ddd][sss].ext
813
814
814 [yyyy]: anio
815 [yyyy]: anio
815 [ddd] : dia del anio
816 [ddd] : dia del anio
816 [sss] : set del archivo
817 [sss] : set del archivo
817
818
818 Inputs:
819 Inputs:
819 path : Directorio de datos donde se realizara la busqueda. Todos los
820 path : Directorio de datos donde se realizara la busqueda. Todos los
820 ficheros que concidan con el criterio de busqueda seran
821 ficheros que concidan con el criterio de busqueda seran
821 almacenados en una lista y luego retornados.
822 almacenados en una lista y luego retornados.
822 startDateTime : Fecha inicial. Rechaza todos los archivos donde
823 startDateTime : Fecha inicial. Rechaza todos los archivos donde
823 file end time < startDateTime (obejto datetime.datetime)
824 file end time < startDateTime (obejto datetime.datetime)
824
825
825 endDateTime : Fecha final. Rechaza todos los archivos donde
826 endDateTime : Fecha final. Rechaza todos los archivos donde
826 file start time > endDateTime (obejto datetime.datetime)
827 file start time > endDateTime (obejto datetime.datetime)
827
828
828 set : Set del primer archivo a leer. Por defecto None
829 set : Set del primer archivo a leer. Por defecto None
829
830
830 expLabel : Nombre del subdirectorio de datos. Por defecto ""
831 expLabel : Nombre del subdirectorio de datos. Por defecto ""
831
832
832 ext : Extension de los archivos a leer. Por defecto .r
833 ext : Extension de los archivos a leer. Por defecto .r
833
834
834 Return:
835 Return:
835
836
836 (pathList, filenameList)
837 (pathList, filenameList)
837
838
838 pathList : Lista de directorios donde se encontraron archivos dentro
839 pathList : Lista de directorios donde se encontraron archivos dentro
839 de los parametros especificados
840 de los parametros especificados
840 filenameList : Lista de archivos (ruta completa) que coincidieron con los
841 filenameList : Lista de archivos (ruta completa) que coincidieron con los
841 parametros especificados.
842 parametros especificados.
842
843
843 Variables afectadas:
844 Variables afectadas:
844
845
845 self.filenameList: Lista de archivos (ruta completa) que la clase utiliza
846 self.filenameList: Lista de archivos (ruta completa) que la clase utiliza
846 como fuente para leer los bloque de datos, si se termina
847 como fuente para leer los bloque de datos, si se termina
847 de leer todos los bloques de datos de un determinado
848 de leer todos los bloques de datos de un determinado
848 archivo se pasa al siguiente archivo de la lista.
849 archivo se pasa al siguiente archivo de la lista.
849
850
850 Excepciones:
851 Excepciones:
851
852
852 """
853 """
853
854
854 print "Searching files ..."
855 print "Searching files ..."
855
856
856 dirList = []
857 dirList = []
857 for thisPath in os.listdir(path):
858 for thisPath in os.listdir(path):
858 if os.path.isdir(os.path.join(path,thisPath)):
859 if os.path.isdir(os.path.join(path,thisPath)):
859 dirList.append(thisPath)
860 dirList.append(thisPath)
860
861
861 if not(dirList):
862 if not(dirList):
862 return None, None
863 return None, None
863
864
864 pathList = []
865 pathList = []
865
866
866 thisDateTime = startDateTime
867 thisDateTime = startDateTime
867
868
868 while(thisDateTime <= endDateTime):
869 while(thisDateTime <= endDateTime):
869 year = thisDateTime.timetuple().tm_year
870 year = thisDateTime.timetuple().tm_year
870 doy = thisDateTime.timetuple().tm_yday
871 doy = thisDateTime.timetuple().tm_yday
871
872
872 match = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy))
873 match = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy))
873 if len(match) == 0:
874 if len(match) == 0:
874 thisDateTime += datetime.timedelta(1)
875 thisDateTime += datetime.timedelta(1)
875 continue
876 continue
876
877
877 pathList.append(os.path.join(path,match[0],expLabel))
878 pathList.append(os.path.join(path,match[0],expLabel))
878 thisDateTime += datetime.timedelta(1)
879 thisDateTime += datetime.timedelta(1)
879
880
880 startUtSeconds = time.mktime(startDateTime.timetuple())
881 startUtSeconds = time.mktime(startDateTime.timetuple())
881 endUtSeconds = time.mktime(endDateTime.timetuple())
882 endUtSeconds = time.mktime(endDateTime.timetuple())
882
883
883 filenameList = []
884 filenameList = []
884 for thisPath in pathList:
885 for thisPath in pathList:
885 fileList = glob.glob1(thisPath, "*%s" %ext)
886 fileList = glob.glob1(thisPath, "*%s" %ext)
886 fileList.sort()
887 fileList.sort()
887 for file in fileList:
888 for file in fileList:
888 filename = os.path.join(thisPath,file)
889 filename = os.path.join(thisPath,file)
889 if isThisFileinRange(filename, startUtSeconds, endUtSeconds):
890 if isThisFileinRange(filename, startUtSeconds, endUtSeconds):
890 filenameList.append(filename)
891 filenameList.append(filename)
891
892
892 if not(filenameList):
893 if not(filenameList):
893 return None, None
894 return None, None
894
895
895 self.filenameList = filenameList
896 self.filenameList = filenameList
896
897
897 return pathList, filenameList
898 return pathList, filenameList
898
899
899 def __verifyFile(self, filename, msgFlag=True):
900 def __verifyFile(self, filename, msgFlag=True):
900 """
901 """
901 Verifica que el filename tenga data valida, para ello leo el FirstHeader del file
902 Verifica que el filename tenga data valida, para ello leo el FirstHeader del file
902
903
903 Return:
904 Return:
904 0 : file no valido para ser leido
905 0 : file no valido para ser leido
905 1 : file valido para ser leido
906 1 : file valido para ser leido
906 """
907 """
907 msg = None
908 msg = None
908
909
909 try:
910 try:
910 fp = open( filename,'rb' ) #lectura binaria
911 fp = open( filename,'rb' ) #lectura binaria
911 currentPosition = fp.tell()
912 currentPosition = fp.tell()
912 except:
913 except:
913 if msgFlag:
914 if msgFlag:
914 print "The file %s can't be opened" % (filename)
915 print "The file %s can't be opened" % (filename)
915 return False
916 return False
916
917
917 neededSize = self.m_ProcessingHeader.blockSize + self.firstHeaderSize
918 neededSize = self.m_ProcessingHeader.blockSize + self.firstHeaderSize
918
919
919 if neededSize == 0:
920 if neededSize == 0:
920
921
921 m_BasicHeader = BasicHeader()
922 m_BasicHeader = BasicHeader()
922 m_SystemHeader = SystemHeader()
923 m_SystemHeader = SystemHeader()
923 m_RadarControllerHeader = RadarControllerHeader()
924 m_RadarControllerHeader = RadarControllerHeader()
924 m_ProcessingHeader = ProcessingHeader()
925 m_ProcessingHeader = ProcessingHeader()
925
926
926 try:
927 try:
927 if not( m_BasicHeader.read(fp) ): raise ValueError
928 if not( m_BasicHeader.read(fp) ): raise ValueError
928 if not( m_SystemHeader.read(fp) ): raise ValueError
929 if not( m_SystemHeader.read(fp) ): raise ValueError
929 if not( m_RadarControllerHeader.read(fp) ): raise ValueError
930 if not( m_RadarControllerHeader.read(fp) ): raise ValueError
930 if not( m_ProcessingHeader.read(fp) ): raise ValueError
931 if not( m_ProcessingHeader.read(fp) ): raise ValueError
931 data_type = int(numpy.log2((m_ProcessingHeader.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
932 data_type = int(numpy.log2((m_ProcessingHeader.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
932
933
933 neededSize = m_ProcessingHeader.blockSize + m_BasicHeader.size
934 neededSize = m_ProcessingHeader.blockSize + m_BasicHeader.size
934
935
935 except:
936 except:
936 if msgFlag:
937 if msgFlag:
937 print "\tThe file %s is empty or it hasn't enough data" % filename
938 print "\tThe file %s is empty or it hasn't enough data" % filename
938
939
939 fp.close()
940 fp.close()
940 return False
941 return False
941
942
942 else:
943 else:
943 msg = "\tSkipping the file %s due to it hasn't enough data" %filename
944 msg = "\tSkipping the file %s due to it hasn't enough data" %filename
944
945
945 fp.close()
946 fp.close()
946 fileSize = os.path.getsize(filename)
947 fileSize = os.path.getsize(filename)
947 currentSize = fileSize - currentPosition
948 currentSize = fileSize - currentPosition
948
949
949 if currentSize < neededSize:
950 if currentSize < neededSize:
950 if msgFlag and (msg != None):
951 if msgFlag and (msg != None):
951 print msg #print"\tSkipping the file %s due to it hasn't enough data" %filename
952 print msg #print"\tSkipping the file %s due to it hasn't enough data" %filename
952 return False
953 return False
953
954
954 return True
955 return True
955
956
956 def updateDataHeader(self):
957 def updateDataHeader(self):
957
958
958 self.dataOutObj.m_BasicHeader = self.m_BasicHeader.copy()
959 self.dataOutObj.m_BasicHeader = self.m_BasicHeader.copy()
959 self.dataOutObj.m_ProcessingHeader = self.m_ProcessingHeader.copy()
960 self.dataOutObj.m_ProcessingHeader = self.m_ProcessingHeader.copy()
960 self.dataOutObj.m_RadarControllerHeader = self.m_RadarControllerHeader.copy()
961 self.dataOutObj.m_RadarControllerHeader = self.m_RadarControllerHeader.copy()
961 self.dataOutObj.m_SystemHeader = self.m_SystemHeader.copy()
962 self.dataOutObj.m_SystemHeader = self.m_SystemHeader.copy()
962
963
963 self.dataOutObj.dataType = self.dataType
964 self.dataOutObj.dataType = self.dataType
964 self.dataOutObj.updateObjFromHeader()
965 self.dataOutObj.updateObjFromHeader()
965
966
966
967
967 class JRODataWriter(JRODataIO):
968 class JRODataWriter(JRODataIO):
968
969
969 """
970 """
970 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
971 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
971 de los datos siempre se realiza por bloques.
972 de los datos siempre se realiza por bloques.
972 """
973 """
973
974
974 nWriteBlocks = 0
975 nWriteBlocks = 0
975
976
976 setFile = None
977 setFile = None
977
978
978
979
979 def __init__(self, dataOutObj=None):
980 def __init__(self, dataOutObj=None):
980 raise ValueError, "Not implemented"
981 raise ValueError, "Not implemented"
981
982
982
983
983 def hasAllDataInBuffer(self):
984 def hasAllDataInBuffer(self):
984 raise ValueError, "Not implemented"
985 raise ValueError, "Not implemented"
985
986
986
987
987 def setBlockDimension(self):
988 def setBlockDimension(self):
988 raise ValueError, "Not implemented"
989 raise ValueError, "Not implemented"
989
990
990
991
991 def writeBlock(self):
992 def writeBlock(self):
992 raise ValueError, "No implemented"
993 raise ValueError, "No implemented"
993
994
994
995
995 def putData(self):
996 def putData(self):
996 raise ValueError, "No implemented"
997 raise ValueError, "No implemented"
997
998
998
999
999 def __writeFirstHeader(self):
1000 def __writeFirstHeader(self):
1000 """
1001 """
1001 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1002 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1002
1003
1003 Affected:
1004 Affected:
1004 __dataType
1005 __dataType
1005
1006
1006 Return:
1007 Return:
1007 None
1008 None
1008 """
1009 """
1009 self.__writeBasicHeader()
1010 self.__writeBasicHeader()
1010 self.__wrSystemHeader()
1011 self.__wrSystemHeader()
1011 self.__wrRadarControllerHeader()
1012 self.__wrRadarControllerHeader()
1012 self.__wrProcessingHeader()
1013 self.__wrProcessingHeader()
1013 self.dataType = self.dataOutObj.dataType
1014 self.dataType = self.dataOutObj.dataType
1014
1015
1015
1016
1016 def __writeBasicHeader(self, fp=None):
1017 def __writeBasicHeader(self, fp=None):
1017 """
1018 """
1018 Escribe solo el Basic header en el file creado
1019 Escribe solo el Basic header en el file creado
1019
1020
1020 Return:
1021 Return:
1021 None
1022 None
1022 """
1023 """
1023 if fp == None:
1024 if fp == None:
1024 fp = self.fp
1025 fp = self.fp
1025
1026
1026 self.dataOutObj.m_BasicHeader.write(fp)
1027 self.dataOutObj.m_BasicHeader.write(fp)
1027
1028
1028
1029
1029 def __wrSystemHeader(self, fp=None):
1030 def __wrSystemHeader(self, fp=None):
1030 """
1031 """
1031 Escribe solo el System header en el file creado
1032 Escribe solo el System header en el file creado
1032
1033
1033 Return:
1034 Return:
1034 None
1035 None
1035 """
1036 """
1036 if fp == None:
1037 if fp == None:
1037 fp = self.fp
1038 fp = self.fp
1038
1039
1039 self.dataOutObj.m_SystemHeader.write(fp)
1040 self.dataOutObj.m_SystemHeader.write(fp)
1040
1041
1041
1042
1042 def __wrRadarControllerHeader(self, fp=None):
1043 def __wrRadarControllerHeader(self, fp=None):
1043 """
1044 """
1044 Escribe solo el RadarController header en el file creado
1045 Escribe solo el RadarController header en el file creado
1045
1046
1046 Return:
1047 Return:
1047 None
1048 None
1048 """
1049 """
1049 if fp == None:
1050 if fp == None:
1050 fp = self.fp
1051 fp = self.fp
1051
1052
1052 self.dataOutObj.m_RadarControllerHeader.write(fp)
1053 self.dataOutObj.m_RadarControllerHeader.write(fp)
1053
1054
1054
1055
1055 def __wrProcessingHeader(self, fp=None):
1056 def __wrProcessingHeader(self, fp=None):
1056 """
1057 """
1057 Escribe solo el Processing header en el file creado
1058 Escribe solo el Processing header en el file creado
1058
1059
1059 Return:
1060 Return:
1060 None
1061 None
1061 """
1062 """
1062 if fp == None:
1063 if fp == None:
1063 fp = self.fp
1064 fp = self.fp
1064
1065
1065 self.dataOutObj.m_ProcessingHeader.write(fp)
1066 self.dataOutObj.m_ProcessingHeader.write(fp)
1066
1067
1067
1068
1068 def setNextFile(self):
1069 def setNextFile(self):
1069 """
1070 """
1070 Determina el siguiente file que sera escrito
1071 Determina el siguiente file que sera escrito
1071
1072
1072 Affected:
1073 Affected:
1073 self.filename
1074 self.filename
1074 self.subfolder
1075 self.subfolder
1075 self.fp
1076 self.fp
1076 self.setFile
1077 self.setFile
1077 self.flagIsNewFile
1078 self.flagIsNewFile
1078
1079
1079 Return:
1080 Return:
1080 0 : Si el archivo no puede ser escrito
1081 0 : Si el archivo no puede ser escrito
1081 1 : Si el archivo esta listo para ser escrito
1082 1 : Si el archivo esta listo para ser escrito
1082 """
1083 """
1083 ext = self.ext
1084 ext = self.ext
1084 path = self.path
1085 path = self.path
1085
1086
1086 if self.fp != None:
1087 if self.fp != None:
1087 self.fp.close()
1088 self.fp.close()
1088
1089
1089 timeTuple = time.localtime( self.dataOutObj.m_BasicHeader.utc )
1090 timeTuple = time.localtime( self.dataOutObj.m_BasicHeader.utc )
1090 subfolder = 'D%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1091 subfolder = 'D%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1091
1092
1092 doypath = os.path.join( path, subfolder )
1093 doypath = os.path.join( path, subfolder )
1093 if not( os.path.exists(doypath) ):
1094 if not( os.path.exists(doypath) ):
1094 os.mkdir(doypath)
1095 os.mkdir(doypath)
1095 self.setFile = -1 #inicializo mi contador de seteo
1096 self.setFile = -1 #inicializo mi contador de seteo
1096 else:
1097 else:
1097 filesList = os.listdir( doypath )
1098 filesList = os.listdir( doypath )
1098 if len( filesList ) > 0:
1099 if len( filesList ) > 0:
1099 filesList = sorted( filesList, key=str.lower )
1100 filesList = sorted( filesList, key=str.lower )
1100 filen = filesList[-1]
1101 filen = filesList[-1]
1101 # el filename debera tener el siguiente formato
1102 # el filename debera tener el siguiente formato
1102 # 0 1234 567 89A BCDE (hex)
1103 # 0 1234 567 89A BCDE (hex)
1103 # x YYYY DDD SSS .ext
1104 # x YYYY DDD SSS .ext
1104 if isNumber( filen[8:11] ):
1105 if isNumber( filen[8:11] ):
1105 self.setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1106 self.setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1106 else:
1107 else:
1107 self.setFile = -1
1108 self.setFile = -1
1108 else:
1109 else:
1109 self.setFile = -1 #inicializo mi contador de seteo
1110 self.setFile = -1 #inicializo mi contador de seteo
1110
1111
1111 setFile = self.setFile
1112 setFile = self.setFile
1112 setFile += 1
1113 setFile += 1
1113
1114
1114 file = '%s%4.4d%3.3d%3.3d%s' % (self.optchar,
1115 file = '%s%4.4d%3.3d%3.3d%s' % (self.optchar,
1115 timeTuple.tm_year,
1116 timeTuple.tm_year,
1116 timeTuple.tm_yday,
1117 timeTuple.tm_yday,
1117 setFile,
1118 setFile,
1118 ext )
1119 ext )
1119
1120
1120 filename = os.path.join( path, subfolder, file )
1121 filename = os.path.join( path, subfolder, file )
1121
1122
1122 fp = open( filename,'wb' )
1123 fp = open( filename,'wb' )
1123
1124
1124 self.nWriteBlocks = 0
1125 self.nWriteBlocks = 0
1125
1126
1126 #guardando atributos
1127 #guardando atributos
1127 self.filename = filename
1128 self.filename = filename
1128 self.subfolder = subfolder
1129 self.subfolder = subfolder
1129 self.fp = fp
1130 self.fp = fp
1130 self.setFile = setFile
1131 self.setFile = setFile
1131 self.flagIsNewFile = 1
1132 self.flagIsNewFile = 1
1132
1133
1133 print 'Writing the file: %s'%self.filename
1134 print 'Writing the file: %s'%self.filename
1134
1135
1135 self.__writeFirstHeader()
1136 self.__writeFirstHeader()
1136
1137
1137 return 1
1138 return 1
1138
1139
1139
1140
1140 def __setNewBlock(self):
1141 def __setNewBlock(self):
1141 """
1142 """
1142 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1143 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1143
1144
1144 Return:
1145 Return:
1145 0 : si no pudo escribir nada
1146 0 : si no pudo escribir nada
1146 1 : Si escribio el Basic el First Header
1147 1 : Si escribio el Basic el First Header
1147 """
1148 """
1148 if self.fp == None:
1149 if self.fp == None:
1149 self.setNextFile()
1150 self.setNextFile()
1150
1151
1151 if self.flagIsNewFile:
1152 if self.flagIsNewFile:
1152 return 1
1153 return 1
1153
1154
1154 if self.nWriteBlocks < self.m_ProcessingHeader.dataBlocksPerFile:
1155 if self.nWriteBlocks < self.m_ProcessingHeader.dataBlocksPerFile:
1155 self.__writeBasicHeader()
1156 self.__writeBasicHeader()
1156 return 1
1157 return 1
1157
1158
1158 if not( self.setNextFile() ):
1159 if not( self.setNextFile() ):
1159 return 0
1160 return 0
1160
1161
1161 return 1
1162 return 1
1162
1163
1163
1164
1164 def writeNextBlock(self):
1165 def writeNextBlock(self):
1165 """
1166 """
1166 Selecciona el bloque siguiente de datos y los escribe en un file
1167 Selecciona el bloque siguiente de datos y los escribe en un file
1167
1168
1168 Return:
1169 Return:
1169 0 : Si no hizo pudo escribir el bloque de datos
1170 0 : Si no hizo pudo escribir el bloque de datos
1170 1 : Si no pudo escribir el bloque de datos
1171 1 : Si no pudo escribir el bloque de datos
1171 """
1172 """
1172 if not( self.__setNewBlock() ):
1173 if not( self.__setNewBlock() ):
1173 return 0
1174 return 0
1174
1175
1175 self.writeBlock()
1176 self.writeBlock()
1176
1177
1177 return 1
1178 return 1
1178
1179
1179
1180
1180 def getDataHeader(self):
1181 def getDataHeader(self):
1181 """
1182 """
1182 Obtiene una copia del First Header
1183 Obtiene una copia del First Header
1183
1184
1184 Affected:
1185 Affected:
1185 self.m_BasicHeader
1186 self.m_BasicHeader
1186 self.m_SystemHeader
1187 self.m_SystemHeader
1187 self.m_RadarControllerHeader
1188 self.m_RadarControllerHeader
1188 self.m_ProcessingHeader
1189 self.m_ProcessingHeader
1189 self.dataType
1190 self.dataType
1190
1191
1191 Return:
1192 Return:
1192 None
1193 None
1193 """
1194 """
1194 self.dataOutObj.updateHeaderFromObj()
1195 self.dataOutObj.updateHeaderFromObj()
1195
1196
1196 self.m_BasicHeader = self.dataOutObj.m_BasicHeader.copy()
1197 self.m_BasicHeader = self.dataOutObj.m_BasicHeader.copy()
1197 self.m_SystemHeader = self.dataOutObj.m_SystemHeader.copy()
1198 self.m_SystemHeader = self.dataOutObj.m_SystemHeader.copy()
1198 self.m_RadarControllerHeader = self.dataOutObj.m_RadarControllerHeader.copy()
1199 self.m_RadarControllerHeader = self.dataOutObj.m_RadarControllerHeader.copy()
1199 self.m_ProcessingHeader = self.dataOutObj.m_ProcessingHeader.copy()
1200 self.m_ProcessingHeader = self.dataOutObj.m_ProcessingHeader.copy()
1200
1201
1201 self.dataType = self.dataOutObj.dataType
1202 self.dataType = self.dataOutObj.dataType
1202
1203
1203
1204
1204 def setup(self, path, set=0, ext=None):
1205 def setup(self, path, set=0, ext=None):
1205 """
1206 """
1206 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1207 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1207
1208
1208 Inputs:
1209 Inputs:
1209 path : el path destino en el cual se escribiran los files a crear
1210 path : el path destino en el cual se escribiran los files a crear
1210 format : formato en el cual sera salvado un file
1211 format : formato en el cual sera salvado un file
1211 set : el setebo del file
1212 set : el setebo del file
1212
1213
1213 Return:
1214 Return:
1214 0 : Si no realizo un buen seteo
1215 0 : Si no realizo un buen seteo
1215 1 : Si realizo un buen seteo
1216 1 : Si realizo un buen seteo
1216 """
1217 """
1217
1218
1218 if ext == None:
1219 if ext == None:
1219 ext = self.ext
1220 ext = self.ext
1220
1221
1221 ext = ext.lower()
1222 ext = ext.lower()
1222
1223
1223 self.path = path
1224 self.path = path
1224 self.setFile = set - 1
1225 self.setFile = set - 1
1225 self.ext = ext
1226 self.ext = ext
1226 #self.format = format
1227 #self.format = format
1227 self.getDataHeader()
1228 self.getDataHeader()
1228
1229
1229 self.setBlockDimension()
1230 self.setBlockDimension()
1230
1231
1231 if not( self.setNextFile() ):
1232 if not( self.setNextFile() ):
1232 print "There isn't a next file"
1233 print "There isn't a next file"
1233 return 0
1234 return 0
1234
1235
1235 return 1
1236 return 1
@@ -1,672 +1,674
1 '''
1 '''
2 Created on Feb 7, 2012
2 Created on Feb 7, 2012
3
3
4 @author $Author$
4 @author $Author$
5 @version $Id$
5 @version $Id$
6 '''
6 '''
7
7
8 import os, sys
8 import os, sys
9 import numpy
9 import numpy
10
10
11 path = os.path.split(os.getcwd())[0]
11 path = os.path.split(os.getcwd())[0]
12 sys.path.append(path)
12 sys.path.append(path)
13
13
14 from Model.Voltage import Voltage
14 from Model.Voltage import Voltage
15 from IO.VoltageIO import VoltageWriter
15 from IO.VoltageIO import VoltageWriter
16 from Graphics.VoltagePlot import Osciloscope
16 from Graphics.VoltagePlot import Osciloscope
17 from Graphics.VoltagePlot import RTI
17 from Graphics.VoltagePlot import RTI
18
18
19 class VoltageProcessor:
19 class VoltageProcessor:
20 '''
20 '''
21 classdocs
21 classdocs
22 '''
22 '''
23
23
24 dataInObj = None
24 dataInObj = None
25 dataOutObj = None
25 dataOutObj = None
26
26
27 integratorObjIndex = None
27 integratorObjIndex = None
28 decoderObjIndex = None
28 decoderObjIndex = None
29 profSelectorObjIndex = None
29 profSelectorObjIndex = None
30 writerObjIndex = None
30 writerObjIndex = None
31 plotterObjIndex = None
31 plotterObjIndex = None
32 flipIndex = None
32 flipIndex = None
33
33
34 integratorObjList = []
34 integratorObjList = []
35 decoderObjList = []
35 decoderObjList = []
36 profileSelectorObjList = []
36 profileSelectorObjList = []
37 writerObjList = []
37 writerObjList = []
38 plotterObjList = []
38 plotterObjList = []
39 m_Voltage= Voltage()
39 m_Voltage= Voltage()
40
40
41 def __init__(self):
41 def __init__(self):
42 '''
42 '''
43 Constructor
43 Constructor
44 '''
44 '''
45
45
46 self.integratorObjIndex = None
46 self.integratorObjIndex = None
47 self.decoderObjIndex = None
47 self.decoderObjIndex = None
48 self.profSelectorObjIndex = None
48 self.profSelectorObjIndex = None
49 self.writerObjIndex = None
49 self.writerObjIndex = None
50 self.plotterObjIndex = None
50 self.plotterObjIndex = None
51 self.flipIndex = 1
51 self.flipIndex = 1
52 self.integratorObjList = []
52 self.integratorObjList = []
53 self.decoderObjList = []
53 self.decoderObjList = []
54 self.profileSelectorObjList = []
54 self.profileSelectorObjList = []
55 self.writerObjList = []
55 self.writerObjList = []
56 self.plotterObjList = []
56 self.plotterObjList = []
57
57
58 def setup(self, dataInObj=None, dataOutObj=None):
58 def setup(self, dataInObj=None, dataOutObj=None):
59
59
60 self.dataInObj = dataInObj
60 self.dataInObj = dataInObj
61
61
62 if dataOutObj == None:
62 if dataOutObj == None:
63 dataOutObj = Voltage()
63 dataOutObj = Voltage()
64
64
65 dataOutObj.copy(dataInObj)
65 dataOutObj.copy(dataInObj)
66
66
67 self.dataOutObj = dataOutObj
67 self.dataOutObj = dataOutObj
68
68
69 return self.dataOutObj
69 return self.dataOutObj
70
70
71
71
72 def init(self):
72 def init(self):
73
73
74 self.integratorObjIndex = 0
74 self.integratorObjIndex = 0
75 self.decoderObjIndex = 0
75 self.decoderObjIndex = 0
76 self.profSelectorObjIndex = 0
76 self.profSelectorObjIndex = 0
77 self.writerObjIndex = 0
77 self.writerObjIndex = 0
78 self.plotterObjIndex = 0
78 self.plotterObjIndex = 0
79 self.dataOutObj.copy(self.dataInObj)
79 self.dataOutObj.copy(self.dataInObj)
80
80
81 if self.profSelectorObjIndex != None:
81 if self.profSelectorObjIndex != None:
82 for profSelObj in self.profileSelectorObjList:
82 for profSelObj in self.profileSelectorObjList:
83 profSelObj.incIndex()
83 profSelObj.incIndex()
84
84
85 def addWriter(self, wrpath):
85 def addWriter(self, wrpath):
86 objWriter = VoltageWriter(self.dataOutObj)
86 objWriter = VoltageWriter(self.dataOutObj)
87 objWriter.setup(wrpath)
87 objWriter.setup(wrpath)
88 self.writerObjList.append(objWriter)
88 self.writerObjList.append(objWriter)
89
89
90 def addRti(self,index=None):
90 def addRti(self,index=None):
91 if index==None:
91 if index==None:
92 index = self.plotterObjIndex
92 index = self.plotterObjIndex
93
93
94 plotObj = RTI(self.dataOutObj, index)
94 plotObj = RTI(self.dataOutObj, index)
95 self.plotterObjList.append(plotObj)
95 self.plotterObjList.append(plotObj)
96
96
97 def addPlotter(self, index=None):
97 def addPlotter(self, index=None):
98 if index==None:
98 if index==None:
99 index = self.plotterObjIndex
99 index = self.plotterObjIndex
100
100
101 plotObj = Osciloscope(self.dataOutObj, index)
101 plotObj = Osciloscope(self.dataOutObj, index)
102 self.plotterObjList.append(plotObj)
102 self.plotterObjList.append(plotObj)
103
103
104 def addIntegrator(self, N,timeInterval):
104 def addIntegrator(self, N,timeInterval):
105
105
106 objCohInt = CoherentIntegrator(N,timeInterval)
106 objCohInt = CoherentIntegrator(N,timeInterval)
107 self.integratorObjList.append(objCohInt)
107 self.integratorObjList.append(objCohInt)
108
108
109 def addDecoder(self, code, ncode, nbaud):
109 def addDecoder(self, code, ncode, nbaud):
110
110
111 objDecoder = Decoder(code,ncode,nbaud)
111 objDecoder = Decoder(code,ncode,nbaud)
112 self.decoderObjList.append(objDecoder)
112 self.decoderObjList.append(objDecoder)
113
113
114 def addProfileSelector(self, nProfiles):
114 def addProfileSelector(self, nProfiles):
115
115
116 objProfSelector = ProfileSelector(nProfiles)
116 objProfSelector = ProfileSelector(nProfiles)
117 self.profileSelectorObjList.append(objProfSelector)
117 self.profileSelectorObjList.append(objProfSelector)
118
118
119 def writeData(self,wrpath):
119 def writeData(self,wrpath):
120
120
121 if self.dataOutObj.flagNoData:
121 if self.dataOutObj.flagNoData:
122 return 0
122 return 0
123
123
124 if len(self.writerObjList) <= self.writerObjIndex:
124 if len(self.writerObjList) <= self.writerObjIndex:
125 self.addWriter(wrpath)
125 self.addWriter(wrpath)
126
126
127 self.writerObjList[self.writerObjIndex].putData()
127 self.writerObjList[self.writerObjIndex].putData()
128
128
129 self.writerObjIndex += 1
129 self.writerObjIndex += 1
130
130
131 def addScope(self,index=None):
131 def addScope(self,index=None):
132 if index==None:
132 if index==None:
133 index = self.plotterObjIndex
133 index = self.plotterObjIndex
134
134
135 plotObj = Osciloscope(self.dataOutObj, index)
135 plotObj = Osciloscope(self.dataOutObj, index)
136 self.plotterObjList.append(plotObj)
136 self.plotterObjList.append(plotObj)
137
137
138 def plotScope(self,
138 def plotScope(self,
139 xmin=None,
139 xmin=None,
140 xmax=None,
140 xmax=None,
141 ymin=None,
141 ymin=None,
142 ymax=None,
142 ymax=None,
143 titleList=None,
143 titleList=None,
144 xlabelList=None,
144 xlabelList=None,
145 ylabelList=None,
145 ylabelList=None,
146 winTitle='',
146 winTitle='',
147 type="power",
147 type="power",
148 index=None):
148 index=None):
149
149
150 if self.dataOutObj.flagNoData:
150 if self.dataOutObj.flagNoData:
151 return 0
151 return 0
152
152
153 if len(self.plotterObjList) <= self.plotterObjIndex:
153 if len(self.plotterObjList) <= self.plotterObjIndex:
154 self.addScope(index)
154 self.addScope(index)
155
155
156 self.plotterObjList[self.plotterObjIndex].plotData(xmin,
156 self.plotterObjList[self.plotterObjIndex].plotData(xmin,
157 xmax,
157 xmax,
158 ymin,
158 ymin,
159 ymax,
159 ymax,
160 titleList,
160 titleList,
161 xlabelList,
161 xlabelList,
162 ylabelList,
162 ylabelList,
163 winTitle,
163 winTitle,
164 type)
164 type)
165
165
166 self.plotterObjIndex += 1
166 self.plotterObjIndex += 1
167
167
168 def plotRti(self,
168 def plotRti(self,
169 xmin=None,
169 xmin=None,
170 xmax=None,
170 xmax=None,
171 ymin=None,
171 ymin=None,
172 ymax=None,
172 ymax=None,
173 zmin=None,
173 zmin=None,
174 zmax=None,
174 zmax=None,
175 titleList=None,
175 titleList=None,
176 xlabelList=None,
176 xlabelList=None,
177 ylabelList=None,
177 ylabelList=None,
178 winTitle='',
178 winTitle='',
179 timezone='lt',
179 timezone='lt',
180 npoints=1000.0,
180 npoints=1000.0,
181 colormap="br_green",
181 colormap="br_green",
182 showColorbar=True,
182 showColorbar=True,
183 showPowerProfile=False,
183 showPowerProfile=False,
184 XAxisAsTime=True,
184 XAxisAsTime=True,
185 save=False,
185 index=None):
186 index=None):
186
187
187 if self.dataOutObj.flagNoData:
188 if self.dataOutObj.flagNoData:
188 return 0
189 return 0
189
190
190 if len(self.plotterObjList) <= self.plotterObjIndex:
191 if len(self.plotterObjList) <= self.plotterObjIndex:
191 self.addRti(index)
192 self.addRti(index)
192
193
193 self.plotterObjList[self.plotterObjIndex].plotData(xmin,
194 self.plotterObjList[self.plotterObjIndex].plotData(xmin,
194 xmax,
195 xmax,
195 ymin,
196 ymin,
196 ymax,
197 ymax,
197 zmin,
198 zmin,
198 zmax,
199 zmax,
199 titleList,
200 titleList,
200 xlabelList,
201 xlabelList,
201 ylabelList,
202 ylabelList,
202 winTitle,
203 winTitle,
203 timezone,
204 timezone,
204 npoints,
205 npoints,
205 colormap,
206 colormap,
206 showColorbar,
207 showColorbar,
207 showPowerProfile,
208 showPowerProfile,
208 XAxisAsTime)
209 XAxisAsTime,
210 save)
209
211
210 self.plotterObjIndex += 1
212 self.plotterObjIndex += 1
211
213
212
214
213 def plotData(self,xmin=None, xmax=None, ymin=None, ymax=None, type='iq', winTitle='', index=None):
215 def plotData(self,xmin=None, xmax=None, ymin=None, ymax=None, type='iq', winTitle='', index=None):
214 if self.dataOutObj.flagNoData:
216 if self.dataOutObj.flagNoData:
215 return 0
217 return 0
216
218
217 if len(self.plotterObjList) <= self.plotterObjIndex:
219 if len(self.plotterObjList) <= self.plotterObjIndex:
218 self.addPlotter(index)
220 self.addPlotter(index)
219
221
220 self.plotterObjList[self.plotterObjIndex].plotData(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,type=type, winTitle=winTitle)
222 self.plotterObjList[self.plotterObjIndex].plotData(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,type=type, winTitle=winTitle)
221
223
222 self.plotterObjIndex += 1
224 self.plotterObjIndex += 1
223
225
224 def integrator(self, N=None, timeInterval=None):
226 def integrator(self, N=None, timeInterval=None):
225
227
226 if self.dataOutObj.flagNoData:
228 if self.dataOutObj.flagNoData:
227 return 0
229 return 0
228
230
229 if len(self.integratorObjList) <= self.integratorObjIndex:
231 if len(self.integratorObjList) <= self.integratorObjIndex:
230 self.addIntegrator(N,timeInterval)
232 self.addIntegrator(N,timeInterval)
231
233
232 myCohIntObj = self.integratorObjList[self.integratorObjIndex]
234 myCohIntObj = self.integratorObjList[self.integratorObjIndex]
233 myCohIntObj.exe(data=self.dataOutObj.data,timeOfData=self.dataOutObj.m_BasicHeader.utc)
235 myCohIntObj.exe(data=self.dataOutObj.data,timeOfData=self.dataOutObj.m_BasicHeader.utc)
234
236
235 if myCohIntObj.isReady:
237 if myCohIntObj.isReady:
236 self.dataOutObj.data = myCohIntObj.data
238 self.dataOutObj.data = myCohIntObj.data
237 self.dataOutObj.nAvg = myCohIntObj.navg
239 self.dataOutObj.nAvg = myCohIntObj.navg
238 self.dataOutObj.m_ProcessingHeader.coherentInt *= myCohIntObj.navg
240 self.dataOutObj.m_ProcessingHeader.coherentInt *= myCohIntObj.navg
239 #print "myCohIntObj.navg: ",myCohIntObj.navg
241 #print "myCohIntObj.navg: ",myCohIntObj.navg
240 self.dataOutObj.flagNoData = False
242 self.dataOutObj.flagNoData = False
241
243
242 else:
244 else:
243 self.dataOutObj.flagNoData = True
245 self.dataOutObj.flagNoData = True
244
246
245 self.integratorObjIndex += 1
247 self.integratorObjIndex += 1
246
248
247 def decoder(self,code=None,type = 0):
249 def decoder(self,code=None,type = 0):
248
250
249 if self.dataOutObj.flagNoData:
251 if self.dataOutObj.flagNoData:
250 return 0
252 return 0
251
253
252 if code == None:
254 if code == None:
253 code = self.dataOutObj.m_RadarControllerHeader.code
255 code = self.dataOutObj.m_RadarControllerHeader.code
254 ncode, nbaud = code.shape
256 ncode, nbaud = code.shape
255
257
256 if len(self.decoderObjList) <= self.decoderObjIndex:
258 if len(self.decoderObjList) <= self.decoderObjIndex:
257 self.addDecoder(code,ncode,nbaud)
259 self.addDecoder(code,ncode,nbaud)
258
260
259 myDecodObj = self.decoderObjList[self.decoderObjIndex]
261 myDecodObj = self.decoderObjList[self.decoderObjIndex]
260 myDecodObj.exe(data=self.dataOutObj.data,type=type)
262 myDecodObj.exe(data=self.dataOutObj.data,type=type)
261
263
262 if myDecodObj.flag:
264 if myDecodObj.flag:
263 self.dataOutObj.data = myDecodObj.data
265 self.dataOutObj.data = myDecodObj.data
264 self.dataOutObj.flagNoData = False
266 self.dataOutObj.flagNoData = False
265 else:
267 else:
266 self.dataOutObj.flagNoData = True
268 self.dataOutObj.flagNoData = True
267
269
268 self.decoderObjIndex += 1
270 self.decoderObjIndex += 1
269
271
270
272
271 def filterByHei(self, window):
273 def filterByHei(self, window):
272 if window == None:
274 if window == None:
273 window = self.dataOutObj.m_RadarControllerHeader.txA / self.dataOutObj.m_ProcessingHeader.deltaHeight[0]
275 window = self.dataOutObj.m_RadarControllerHeader.txA / self.dataOutObj.m_ProcessingHeader.deltaHeight[0]
274
276
275 newdelta = self.dataOutObj.m_ProcessingHeader.deltaHeight[0] * window
277 newdelta = self.dataOutObj.m_ProcessingHeader.deltaHeight[0] * window
276 dim1 = self.dataOutObj.data.shape[0]
278 dim1 = self.dataOutObj.data.shape[0]
277 dim2 = self.dataOutObj.data.shape[1]
279 dim2 = self.dataOutObj.data.shape[1]
278 r = dim2 % window
280 r = dim2 % window
279
281
280 buffer = self.dataOutObj.data[:,0:dim2-r]
282 buffer = self.dataOutObj.data[:,0:dim2-r]
281 buffer = buffer.reshape(dim1,dim2/window,window)
283 buffer = buffer.reshape(dim1,dim2/window,window)
282 buffer = numpy.sum(buffer,2)
284 buffer = numpy.sum(buffer,2)
283 self.dataOutObj.data = buffer
285 self.dataOutObj.data = buffer
284
286
285 self.dataOutObj.m_ProcessingHeader.deltaHeight = newdelta
287 self.dataOutObj.m_ProcessingHeader.deltaHeight = newdelta
286 self.dataOutObj.m_ProcessingHeader.numHeights = buffer.shape[1]
288 self.dataOutObj.m_ProcessingHeader.numHeights = buffer.shape[1]
287
289
288 self.dataOutObj.nHeights = self.dataOutObj.m_ProcessingHeader.numHeights
290 self.dataOutObj.nHeights = self.dataOutObj.m_ProcessingHeader.numHeights
289
291
290 #self.dataOutObj.heightList es un numpy.array
292 #self.dataOutObj.heightList es un numpy.array
291 self.dataOutObj.heightList = numpy.arange(self.dataOutObj.m_ProcessingHeader.firstHeight[0],newdelta*self.dataOutObj.nHeights,newdelta)
293 self.dataOutObj.heightList = numpy.arange(self.dataOutObj.m_ProcessingHeader.firstHeight[0],newdelta*self.dataOutObj.nHeights,newdelta)
292
294
293 def deFlip(self):
295 def deFlip(self):
294 self.dataOutObj.data *= self.flipIndex
296 self.dataOutObj.data *= self.flipIndex
295 self.flipIndex *= -1.
297 self.flipIndex *= -1.
296
298
297 def selectChannels(self, channelList):
299 def selectChannels(self, channelList):
298 pass
300 pass
299
301
300 def selectChannelsByIndex(self, channelIndexList):
302 def selectChannelsByIndex(self, channelIndexList):
301 """
303 """
302 Selecciona un bloque de datos en base a canales segun el channelIndexList
304 Selecciona un bloque de datos en base a canales segun el channelIndexList
303
305
304 Input:
306 Input:
305 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
307 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
306
308
307 Affected:
309 Affected:
308 self.dataOutObj.data
310 self.dataOutObj.data
309 self.dataOutObj.channelIndexList
311 self.dataOutObj.channelIndexList
310 self.dataOutObj.nChannels
312 self.dataOutObj.nChannels
311 self.dataOutObj.m_ProcessingHeader.totalSpectra
313 self.dataOutObj.m_ProcessingHeader.totalSpectra
312 self.dataOutObj.m_SystemHeader.numChannels
314 self.dataOutObj.m_SystemHeader.numChannels
313 self.dataOutObj.m_ProcessingHeader.blockSize
315 self.dataOutObj.m_ProcessingHeader.blockSize
314
316
315 Return:
317 Return:
316 None
318 None
317 """
319 """
318 if self.dataOutObj.flagNoData:
320 if self.dataOutObj.flagNoData:
319 return 0
321 return 0
320
322
321 for channel in channelIndexList:
323 for channel in channelIndexList:
322 if channel not in self.dataOutObj.channelIndexList:
324 if channel not in self.dataOutObj.channelIndexList:
323 raise ValueError, "The value %d in channelIndexList is not valid" %channel
325 raise ValueError, "The value %d in channelIndexList is not valid" %channel
324
326
325 nChannels = len(channelIndexList)
327 nChannels = len(channelIndexList)
326
328
327 data = self.dataOutObj.data[channelIndexList,:]
329 data = self.dataOutObj.data[channelIndexList,:]
328
330
329 self.dataOutObj.data = data
331 self.dataOutObj.data = data
330 self.dataOutObj.channelIndexList = channelIndexList
332 self.dataOutObj.channelIndexList = channelIndexList
331 self.dataOutObj.nChannels = nChannels
333 self.dataOutObj.nChannels = nChannels
332
334
333 self.dataOutObj.m_ProcessingHeader.totalSpectra = 0
335 self.dataOutObj.m_ProcessingHeader.totalSpectra = 0
334 self.dataOutObj.m_SystemHeader.numChannels = nChannels
336 self.dataOutObj.m_SystemHeader.numChannels = nChannels
335 self.dataOutObj.m_ProcessingHeader.blockSize = data.size
337 self.dataOutObj.m_ProcessingHeader.blockSize = data.size
336 return 1
338 return 1
337
339
338
340
339 def selectHeightsByValue(self, minHei, maxHei):
341 def selectHeightsByValue(self, minHei, maxHei):
340 """
342 """
341 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
343 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
342 minHei <= height <= maxHei
344 minHei <= height <= maxHei
343
345
344 Input:
346 Input:
345 minHei : valor minimo de altura a considerar
347 minHei : valor minimo de altura a considerar
346 maxHei : valor maximo de altura a considerar
348 maxHei : valor maximo de altura a considerar
347
349
348 Affected:
350 Affected:
349 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
351 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
350
352
351 Return:
353 Return:
352 1 si el metodo se ejecuto con exito caso contrario devuelve 0
354 1 si el metodo se ejecuto con exito caso contrario devuelve 0
353 """
355 """
354 if self.dataOutObj.flagNoData:
356 if self.dataOutObj.flagNoData:
355 return 0
357 return 0
356
358
357 if (minHei < self.dataOutObj.heightList[0]) or (minHei > maxHei):
359 if (minHei < self.dataOutObj.heightList[0]) or (minHei > maxHei):
358 raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
360 raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
359
361
360 if (maxHei > self.dataOutObj.heightList[-1]):
362 if (maxHei > self.dataOutObj.heightList[-1]):
361 raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
363 raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei)
362
364
363 minIndex = 0
365 minIndex = 0
364 maxIndex = 0
366 maxIndex = 0
365 data = self.dataOutObj.heightList
367 data = self.dataOutObj.heightList
366
368
367 for i,val in enumerate(data):
369 for i,val in enumerate(data):
368 if val < minHei:
370 if val < minHei:
369 continue
371 continue
370 else:
372 else:
371 minIndex = i;
373 minIndex = i;
372 break
374 break
373
375
374 for i,val in enumerate(data):
376 for i,val in enumerate(data):
375 if val <= maxHei:
377 if val <= maxHei:
376 maxIndex = i;
378 maxIndex = i;
377 else:
379 else:
378 break
380 break
379
381
380 self.selectHeightsByIndex(minIndex, maxIndex)
382 self.selectHeightsByIndex(minIndex, maxIndex)
381 return 1
383 return 1
382
384
383
385
384 def selectHeightsByIndex(self, minIndex, maxIndex):
386 def selectHeightsByIndex(self, minIndex, maxIndex):
385 """
387 """
386 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
388 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
387 minIndex <= index <= maxIndex
389 minIndex <= index <= maxIndex
388
390
389 Input:
391 Input:
390 minIndex : valor de indice minimo de altura a considerar
392 minIndex : valor de indice minimo de altura a considerar
391 maxIndex : valor de indice maximo de altura a considerar
393 maxIndex : valor de indice maximo de altura a considerar
392
394
393 Affected:
395 Affected:
394 self.dataOutObj.data
396 self.dataOutObj.data
395 self.dataOutObj.heightList
397 self.dataOutObj.heightList
396 self.dataOutObj.nHeights
398 self.dataOutObj.nHeights
397 self.dataOutObj.m_ProcessingHeader.blockSize
399 self.dataOutObj.m_ProcessingHeader.blockSize
398 self.dataOutObj.m_ProcessingHeader.numHeights
400 self.dataOutObj.m_ProcessingHeader.numHeights
399 self.dataOutObj.m_ProcessingHeader.firstHeight
401 self.dataOutObj.m_ProcessingHeader.firstHeight
400 self.dataOutObj.m_RadarControllerHeader
402 self.dataOutObj.m_RadarControllerHeader
401
403
402 Return:
404 Return:
403 1 si el metodo se ejecuto con exito caso contrario devuelve 0
405 1 si el metodo se ejecuto con exito caso contrario devuelve 0
404 """
406 """
405 if self.dataOutObj.flagNoData:
407 if self.dataOutObj.flagNoData:
406 return 0
408 return 0
407
409
408 if (minIndex < 0) or (minIndex > maxIndex):
410 if (minIndex < 0) or (minIndex > maxIndex):
409 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
411 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
410
412
411 if (maxIndex >= self.dataOutObj.nHeights):
413 if (maxIndex >= self.dataOutObj.nHeights):
412 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
414 raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex)
413
415
414 nHeights = maxIndex - minIndex + 1
416 nHeights = maxIndex - minIndex + 1
415
417
416 #voltage
418 #voltage
417 data = self.dataOutObj.data[:,minIndex:maxIndex+1]
419 data = self.dataOutObj.data[:,minIndex:maxIndex+1]
418
420
419 firstHeight = self.dataOutObj.heightList[minIndex]
421 firstHeight = self.dataOutObj.heightList[minIndex]
420
422
421 self.dataOutObj.data = data
423 self.dataOutObj.data = data
422 self.dataOutObj.heightList = self.dataOutObj.heightList[minIndex:maxIndex+1]
424 self.dataOutObj.heightList = self.dataOutObj.heightList[minIndex:maxIndex+1]
423 self.dataOutObj.nHeights = nHeights
425 self.dataOutObj.nHeights = nHeights
424 self.dataOutObj.m_ProcessingHeader.blockSize = data.size
426 self.dataOutObj.m_ProcessingHeader.blockSize = data.size
425 self.dataOutObj.m_ProcessingHeader.numHeights = nHeights
427 self.dataOutObj.m_ProcessingHeader.numHeights = nHeights
426 self.dataOutObj.m_ProcessingHeader.firstHeight = firstHeight
428 self.dataOutObj.m_ProcessingHeader.firstHeight = firstHeight
427 self.dataOutObj.m_RadarControllerHeader.numHeights = nHeights
429 self.dataOutObj.m_RadarControllerHeader.numHeights = nHeights
428 return 1
430 return 1
429
431
430 def selectProfilesByValue(self,indexList, nProfiles):
432 def selectProfilesByValue(self,indexList, nProfiles):
431 if self.dataOutObj.flagNoData:
433 if self.dataOutObj.flagNoData:
432 return 0
434 return 0
433
435
434 if self.profSelectorObjIndex >= len(self.profileSelectorObjList):
436 if self.profSelectorObjIndex >= len(self.profileSelectorObjList):
435 self.addProfileSelector(nProfiles)
437 self.addProfileSelector(nProfiles)
436
438
437 profileSelectorObj = self.profileSelectorObjList[self.profSelectorObjIndex]
439 profileSelectorObj = self.profileSelectorObjList[self.profSelectorObjIndex]
438
440
439 if not(profileSelectorObj.isProfileInList(indexList)):
441 if not(profileSelectorObj.isProfileInList(indexList)):
440 self.dataOutObj.flagNoData = True
442 self.dataOutObj.flagNoData = True
441 self.profSelectorObjIndex += 1
443 self.profSelectorObjIndex += 1
442 return 0
444 return 0
443
445
444 self.dataOutObj.flagNoData = False
446 self.dataOutObj.flagNoData = False
445 self.profSelectorObjIndex += 1
447 self.profSelectorObjIndex += 1
446
448
447 return 1
449 return 1
448
450
449
451
450 def selectProfilesByIndex(self, minIndex, maxIndex, nProfiles):
452 def selectProfilesByIndex(self, minIndex, maxIndex, nProfiles):
451 """
453 """
452 Selecciona un bloque de datos en base a un grupo indices de perfiles segun el rango
454 Selecciona un bloque de datos en base a un grupo indices de perfiles segun el rango
453 minIndex <= index <= maxIndex
455 minIndex <= index <= maxIndex
454
456
455 Input:
457 Input:
456 minIndex : valor de indice minimo de perfil a considerar
458 minIndex : valor de indice minimo de perfil a considerar
457 maxIndex : valor de indice maximo de perfil a considerar
459 maxIndex : valor de indice maximo de perfil a considerar
458 nProfiles : numero de profiles
460 nProfiles : numero de profiles
459
461
460 Affected:
462 Affected:
461 self.dataOutObj.flagNoData
463 self.dataOutObj.flagNoData
462 self.profSelectorObjIndex
464 self.profSelectorObjIndex
463
465
464 Return:
466 Return:
465 1 si el metodo se ejecuto con exito caso contrario devuelve 0
467 1 si el metodo se ejecuto con exito caso contrario devuelve 0
466 """
468 """
467
469
468 if self.dataOutObj.flagNoData:
470 if self.dataOutObj.flagNoData:
469 return 0
471 return 0
470
472
471 if self.profSelectorObjIndex >= len(self.profileSelectorObjList):
473 if self.profSelectorObjIndex >= len(self.profileSelectorObjList):
472 self.addProfileSelector(nProfiles)
474 self.addProfileSelector(nProfiles)
473
475
474 profileSelectorObj = self.profileSelectorObjList[self.profSelectorObjIndex]
476 profileSelectorObj = self.profileSelectorObjList[self.profSelectorObjIndex]
475
477
476 if not(profileSelectorObj.isProfileInRange(minIndex, maxIndex)):
478 if not(profileSelectorObj.isProfileInRange(minIndex, maxIndex)):
477 self.dataOutObj.flagNoData = True
479 self.dataOutObj.flagNoData = True
478 self.profSelectorObjIndex += 1
480 self.profSelectorObjIndex += 1
479 return 0
481 return 0
480
482
481 self.dataOutObj.flagNoData = False
483 self.dataOutObj.flagNoData = False
482 self.profSelectorObjIndex += 1
484 self.profSelectorObjIndex += 1
483
485
484 return 1
486 return 1
485
487
486 def selectNtxs(self, ntx):
488 def selectNtxs(self, ntx):
487 pass
489 pass
488
490
489
491
490 class Decoder:
492 class Decoder:
491
493
492 data = None
494 data = None
493 profCounter = 1
495 profCounter = 1
494 nCode = None
496 nCode = None
495 nBaud = None
497 nBaud = None
496 codeIndex = 0
498 codeIndex = 0
497 code = None
499 code = None
498 flag = False
500 flag = False
499
501
500 def __init__(self,code, ncode, nbaud):
502 def __init__(self,code, ncode, nbaud):
501
503
502 self.data = None
504 self.data = None
503 self.profCounter = 1
505 self.profCounter = 1
504 self.nCode = ncode
506 self.nCode = ncode
505 self.nBaud = nbaud
507 self.nBaud = nbaud
506 self.codeIndex = 0
508 self.codeIndex = 0
507 self.code = code #this is a List
509 self.code = code #this is a List
508 self.flag = False
510 self.flag = False
509
511
510 def exe(self, data, ndata=None, type = 0):
512 def exe(self, data, ndata=None, type = 0):
511
513
512 if ndata == None: ndata = data.shape[1]
514 if ndata == None: ndata = data.shape[1]
513
515
514 if type == 0:
516 if type == 0:
515 self.convolutionInFreq(data,ndata)
517 self.convolutionInFreq(data,ndata)
516
518
517 if type == 1:
519 if type == 1:
518 self.convolutionInTime(data, ndata)
520 self.convolutionInTime(data, ndata)
519
521
520 def convolutionInFreq(self,data, ndata):
522 def convolutionInFreq(self,data, ndata):
521
523
522 newcode = numpy.zeros(ndata)
524 newcode = numpy.zeros(ndata)
523 newcode[0:self.nBaud] = self.code[self.codeIndex]
525 newcode[0:self.nBaud] = self.code[self.codeIndex]
524
526
525 self.codeIndex += 1
527 self.codeIndex += 1
526
528
527 fft_data = numpy.fft.fft(data, axis=1)
529 fft_data = numpy.fft.fft(data, axis=1)
528 fft_code = numpy.conj(numpy.fft.fft(newcode))
530 fft_code = numpy.conj(numpy.fft.fft(newcode))
529 fft_code = fft_code.reshape(1,len(fft_code))
531 fft_code = fft_code.reshape(1,len(fft_code))
530
532
531 conv = fft_data.copy()
533 conv = fft_data.copy()
532 conv.fill(0)
534 conv.fill(0)
533
535
534 conv = fft_data*fft_code
536 conv = fft_data*fft_code
535
537
536 self.data = numpy.fft.ifft(conv,axis=1)
538 self.data = numpy.fft.ifft(conv,axis=1)
537 self.flag = True
539 self.flag = True
538
540
539 if self.profCounter == self.nCode:
541 if self.profCounter == self.nCode:
540 self.profCounter = 0
542 self.profCounter = 0
541 self.codeIndex = 0
543 self.codeIndex = 0
542
544
543 self.profCounter += 1
545 self.profCounter += 1
544
546
545 def convolutionInTime(self, data, ndata):
547 def convolutionInTime(self, data, ndata):
546
548
547 nchannel = data.shape[1]
549 nchannel = data.shape[1]
548 newcode = self.code[self.codeIndex]
550 newcode = self.code[self.codeIndex]
549 self.codeIndex += 1
551 self.codeIndex += 1
550 conv = data.copy()
552 conv = data.copy()
551 for i in range(nchannel):
553 for i in range(nchannel):
552 conv[i,:] = numpy.correlate(data[i,:], newcode, 'same')
554 conv[i,:] = numpy.correlate(data[i,:], newcode, 'same')
553
555
554 self.data = conv
556 self.data = conv
555 self.flag = True
557 self.flag = True
556
558
557 if self.profCounter == self.nCode:
559 if self.profCounter == self.nCode:
558 self.profCounter = 0
560 self.profCounter = 0
559 self.codeIndex = 0
561 self.codeIndex = 0
560
562
561 self.profCounter += 1
563 self.profCounter += 1
562
564
563
565
564 class CoherentIntegrator:
566 class CoherentIntegrator:
565
567
566 integ_counter = None
568 integ_counter = None
567 data = None
569 data = None
568 navg = None
570 navg = None
569 buffer = None
571 buffer = None
570 nCohInt = None
572 nCohInt = None
571
573
572 def __init__(self, N=None,timeInterval=None):
574 def __init__(self, N=None,timeInterval=None):
573
575
574 self.data = None
576 self.data = None
575 self.navg = None
577 self.navg = None
576 self.buffer = None
578 self.buffer = None
577 self.timeOut = None
579 self.timeOut = None
578 self.exitCondition = False
580 self.exitCondition = False
579 self.isReady = False
581 self.isReady = False
580 self.nCohInt = N
582 self.nCohInt = N
581 self.integ_counter = 0
583 self.integ_counter = 0
582 if timeInterval!=None:
584 if timeInterval!=None:
583 self.timeIntervalInSeconds = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line
585 self.timeIntervalInSeconds = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line
584
586
585 if ((timeInterval==None) and (N==None)):
587 if ((timeInterval==None) and (N==None)):
586 print 'N = None ; timeInterval = None'
588 print 'N = None ; timeInterval = None'
587 sys.exit(0)
589 sys.exit(0)
588 elif timeInterval == None:
590 elif timeInterval == None:
589 self.timeFlag = False
591 self.timeFlag = False
590 else:
592 else:
591 self.timeFlag = True
593 self.timeFlag = True
592
594
593 def exe(self, data, timeOfData):
595 def exe(self, data, timeOfData):
594
596
595 if self.timeFlag:
597 if self.timeFlag:
596 if self.timeOut == None:
598 if self.timeOut == None:
597 self.timeOut = timeOfData + self.timeIntervalInSeconds
599 self.timeOut = timeOfData + self.timeIntervalInSeconds
598
600
599 if timeOfData < self.timeOut:
601 if timeOfData < self.timeOut:
600 if self.buffer == None:
602 if self.buffer == None:
601 self.buffer = data
603 self.buffer = data
602 else:
604 else:
603 self.buffer = self.buffer + data
605 self.buffer = self.buffer + data
604 self.integ_counter += 1
606 self.integ_counter += 1
605 else:
607 else:
606 self.exitCondition = True
608 self.exitCondition = True
607
609
608 else:
610 else:
609 if self.integ_counter < self.nCohInt:
611 if self.integ_counter < self.nCohInt:
610 if self.buffer == None:
612 if self.buffer == None:
611 self.buffer = data
613 self.buffer = data
612 else:
614 else:
613 self.buffer = self.buffer + data
615 self.buffer = self.buffer + data
614
616
615 self.integ_counter += 1
617 self.integ_counter += 1
616
618
617 if self.integ_counter == self.nCohInt:
619 if self.integ_counter == self.nCohInt:
618 self.exitCondition = True
620 self.exitCondition = True
619
621
620 if self.exitCondition:
622 if self.exitCondition:
621 self.data = self.buffer
623 self.data = self.buffer
622 self.navg = self.integ_counter
624 self.navg = self.integ_counter
623 self.isReady = True
625 self.isReady = True
624 self.buffer = None
626 self.buffer = None
625 self.timeOut = None
627 self.timeOut = None
626 self.integ_counter = 0
628 self.integ_counter = 0
627 self.exitCondition = False
629 self.exitCondition = False
628
630
629 if self.timeFlag:
631 if self.timeFlag:
630 self.buffer = data
632 self.buffer = data
631 self.timeOut = timeOfData + self.timeIntervalInSeconds
633 self.timeOut = timeOfData + self.timeIntervalInSeconds
632 else:
634 else:
633 self.isReady = False
635 self.isReady = False
634
636
635
637
636
638
637 class ProfileSelector:
639 class ProfileSelector:
638
640
639 profileIndex = None
641 profileIndex = None
640 # Tamanho total de los perfiles
642 # Tamanho total de los perfiles
641 nProfiles = None
643 nProfiles = None
642
644
643 def __init__(self, nProfiles):
645 def __init__(self, nProfiles):
644
646
645 self.profileIndex = 0
647 self.profileIndex = 0
646 self.nProfiles = nProfiles
648 self.nProfiles = nProfiles
647
649
648 def incIndex(self):
650 def incIndex(self):
649 self.profileIndex += 1
651 self.profileIndex += 1
650
652
651 if self.profileIndex >= self.nProfiles:
653 if self.profileIndex >= self.nProfiles:
652 self.profileIndex = 0
654 self.profileIndex = 0
653
655
654 def isProfileInRange(self, minIndex, maxIndex):
656 def isProfileInRange(self, minIndex, maxIndex):
655
657
656 if self.profileIndex < minIndex:
658 if self.profileIndex < minIndex:
657 return False
659 return False
658
660
659 if self.profileIndex > maxIndex:
661 if self.profileIndex > maxIndex:
660 return False
662 return False
661
663
662 return True
664 return True
663
665
664 def isProfileInList(self, profileList):
666 def isProfileInList(self, profileList):
665
667
666 if self.profileIndex not in profileList:
668 if self.profileIndex not in profileList:
667 return False
669 return False
668
670
669 return True
671 return True
670
672
671
673
672 No newline at end of file
674
General Comments 0
You need to be logged in to leave comments. Login now