##// END OF EJS Templates
Desplazamiento automatico de los puntos de FFT en el modulo de lectura de espectros.
Miguel Valdez -
r26:0d3203b6912d
parent child
Show More
@@ -1,844 +1,852
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
8
9 import numpy
9 import numpy
10 import plplot
10 import plplot
11
11
12 def cmap1_init(colormap="gray"):
12 def cmap1_init(colormap="gray"):
13
13
14 ncolor = None
14 ncolor = None
15 rgb_lvl = None
15 rgb_lvl = None
16
16
17 # Routine for defining a specific color map 1 in HLS space.
17 # Routine for defining a specific color map 1 in HLS space.
18 # if gray is true, use basic grayscale variation from half-dark to light.
18 # if gray is true, use basic grayscale variation from half-dark to light.
19 # otherwise use false color variation from blue (240 deg) to red (360 deg).
19 # otherwise use false color variation from blue (240 deg) to red (360 deg).
20
20
21 # Independent variable of control points.
21 # Independent variable of control points.
22 i = numpy.array((0., 1.))
22 i = numpy.array((0., 1.))
23 if colormap=="gray":
23 if colormap=="gray":
24 ncolor = 256
24 ncolor = 256
25 # Hue for control points. Doesn't matter since saturation is zero.
25 # Hue for control points. Doesn't matter since saturation is zero.
26 h = numpy.array((0., 0.))
26 h = numpy.array((0., 0.))
27 # Lightness ranging from half-dark (for interest) to light.
27 # Lightness ranging from half-dark (for interest) to light.
28 l = numpy.array((0.5, 1.))
28 l = numpy.array((0.5, 1.))
29 # Gray scale has zero saturation
29 # Gray scale has zero saturation
30 s = numpy.array((0., 0.))
30 s = numpy.array((0., 0.))
31
31
32 # number of cmap1 colours is 256 in this case.
32 # number of cmap1 colours is 256 in this case.
33 plplot.plscmap1n(ncolor)
33 plplot.plscmap1n(ncolor)
34 # Interpolate between control points to set up cmap1.
34 # Interpolate between control points to set up cmap1.
35 plplot.plscmap1l(0, i, h, l, s)
35 plplot.plscmap1l(0, i, h, l, s)
36
36
37 return None
37 return None
38
38
39 if colormap=="br_green":
39 if colormap=="br_green":
40 ncolor = 256
40 ncolor = 256
41 # Hue ranges from blue (240 deg) to red (0 or 360 deg)
41 # Hue ranges from blue (240 deg) to red (0 or 360 deg)
42 h = numpy.array((240., 0.))
42 h = numpy.array((240., 0.))
43 # Lightness and saturation are constant (values taken from C example).
43 # Lightness and saturation are constant (values taken from C example).
44 l = numpy.array((0.6, 0.6))
44 l = numpy.array((0.6, 0.6))
45 s = numpy.array((0.8, 0.8))
45 s = numpy.array((0.8, 0.8))
46
46
47 # number of cmap1 colours is 256 in this case.
47 # number of cmap1 colours is 256 in this case.
48 plplot.plscmap1n(ncolor)
48 plplot.plscmap1n(ncolor)
49 # Interpolate between control points to set up cmap1.
49 # Interpolate between control points to set up cmap1.
50 plplot.plscmap1l(0, i, h, l, s)
50 plplot.plscmap1l(0, i, h, l, s)
51
51
52 return None
52 return None
53
53
54 if colormap=="tricolor":
54 if colormap=="tricolor":
55 ncolor = 3
55 ncolor = 3
56 # Hue ranges from blue (240 deg) to red (0 or 360 deg)
56 # Hue ranges from blue (240 deg) to red (0 or 360 deg)
57 h = numpy.array((240., 0.))
57 h = numpy.array((240., 0.))
58 # Lightness and saturation are constant (values taken from C example).
58 # Lightness and saturation are constant (values taken from C example).
59 l = numpy.array((0.6, 0.6))
59 l = numpy.array((0.6, 0.6))
60 s = numpy.array((0.8, 0.8))
60 s = numpy.array((0.8, 0.8))
61
61
62 # number of cmap1 colours is 256 in this case.
62 # number of cmap1 colours is 256 in this case.
63 plplot.plscmap1n(ncolor)
63 plplot.plscmap1n(ncolor)
64 # Interpolate between control points to set up cmap1.
64 # Interpolate between control points to set up cmap1.
65 plplot.plscmap1l(0, i, h, l, s)
65 plplot.plscmap1l(0, i, h, l, s)
66
66
67 return None
67 return None
68
68
69 if colormap == 'rgb' or colormap == 'rgb666':
69 if colormap == 'rgb' or colormap == 'rgb666':
70
70
71 color_sz = 6
71 color_sz = 6
72 ncolor = color_sz*color_sz*color_sz
72 ncolor = color_sz*color_sz*color_sz
73 pos = numpy.zeros((ncolor))
73 pos = numpy.zeros((ncolor))
74 r = numpy.zeros((ncolor))
74 r = numpy.zeros((ncolor))
75 g = numpy.zeros((ncolor))
75 g = numpy.zeros((ncolor))
76 b = numpy.zeros((ncolor))
76 b = numpy.zeros((ncolor))
77 ind = 0
77 ind = 0
78 for ri in range(color_sz):
78 for ri in range(color_sz):
79 for gi in range(color_sz):
79 for gi in range(color_sz):
80 for bi in range(color_sz):
80 for bi in range(color_sz):
81 r[ind] = ri/(color_sz-1.0)
81 r[ind] = ri/(color_sz-1.0)
82 g[ind] = gi/(color_sz-1.0)
82 g[ind] = gi/(color_sz-1.0)
83 b[ind] = bi/(color_sz-1.0)
83 b[ind] = bi/(color_sz-1.0)
84 pos[ind] = ind/(ncolor-1.0)
84 pos[ind] = ind/(ncolor-1.0)
85 ind += 1
85 ind += 1
86 rgb_lvl = [6,6,6] #Levels for RGB colors
86 rgb_lvl = [6,6,6] #Levels for RGB colors
87
87
88 if colormap == 'rgb676':
88 if colormap == 'rgb676':
89 ncolor = 6*7*6
89 ncolor = 6*7*6
90 pos = numpy.zeros((ncolor))
90 pos = numpy.zeros((ncolor))
91 r = numpy.zeros((ncolor))
91 r = numpy.zeros((ncolor))
92 g = numpy.zeros((ncolor))
92 g = numpy.zeros((ncolor))
93 b = numpy.zeros((ncolor))
93 b = numpy.zeros((ncolor))
94 ind = 0
94 ind = 0
95 for ri in range(8):
95 for ri in range(8):
96 for gi in range(8):
96 for gi in range(8):
97 for bi in range(4):
97 for bi in range(4):
98 r[ind] = ri/(6-1.0)
98 r[ind] = ri/(6-1.0)
99 g[ind] = gi/(7-1.0)
99 g[ind] = gi/(7-1.0)
100 b[ind] = bi/(6-1.0)
100 b[ind] = bi/(6-1.0)
101 pos[ind] = ind/(ncolor-1.0)
101 pos[ind] = ind/(ncolor-1.0)
102 ind += 1
102 ind += 1
103 rgb_lvl = [6,7,6] #Levels for RGB colors
103 rgb_lvl = [6,7,6] #Levels for RGB colors
104
104
105 if colormap == 'rgb685':
105 if colormap == 'rgb685':
106 ncolor = 6*8*5
106 ncolor = 6*8*5
107 pos = numpy.zeros((ncolor))
107 pos = numpy.zeros((ncolor))
108 r = numpy.zeros((ncolor))
108 r = numpy.zeros((ncolor))
109 g = numpy.zeros((ncolor))
109 g = numpy.zeros((ncolor))
110 b = numpy.zeros((ncolor))
110 b = numpy.zeros((ncolor))
111 ind = 0
111 ind = 0
112 for ri in range(8):
112 for ri in range(8):
113 for gi in range(8):
113 for gi in range(8):
114 for bi in range(4):
114 for bi in range(4):
115 r[ind] = ri/(6-1.0)
115 r[ind] = ri/(6-1.0)
116 g[ind] = gi/(8-1.0)
116 g[ind] = gi/(8-1.0)
117 b[ind] = bi/(5-1.0)
117 b[ind] = bi/(5-1.0)
118 pos[ind] = ind/(ncolor-1.0)
118 pos[ind] = ind/(ncolor-1.0)
119 ind += 1
119 ind += 1
120 rgb_lvl = [6,8,5] #Levels for RGB colors
120 rgb_lvl = [6,8,5] #Levels for RGB colors
121
121
122 if colormap == 'rgb884':
122 if colormap == 'rgb884':
123 ncolor = 8*8*4
123 ncolor = 8*8*4
124 pos = numpy.zeros((ncolor))
124 pos = numpy.zeros((ncolor))
125 r = numpy.zeros((ncolor))
125 r = numpy.zeros((ncolor))
126 g = numpy.zeros((ncolor))
126 g = numpy.zeros((ncolor))
127 b = numpy.zeros((ncolor))
127 b = numpy.zeros((ncolor))
128 ind = 0
128 ind = 0
129 for ri in range(8):
129 for ri in range(8):
130 for gi in range(8):
130 for gi in range(8):
131 for bi in range(4):
131 for bi in range(4):
132 r[ind] = ri/(8-1.0)
132 r[ind] = ri/(8-1.0)
133 g[ind] = gi/(8-1.0)
133 g[ind] = gi/(8-1.0)
134 b[ind] = bi/(4-1.0)
134 b[ind] = bi/(4-1.0)
135 pos[ind] = ind/(ncolor-1.0)
135 pos[ind] = ind/(ncolor-1.0)
136 ind += 1
136 ind += 1
137 rgb_lvl = [8,8,4] #Levels for RGB colors
137 rgb_lvl = [8,8,4] #Levels for RGB colors
138
138
139 if ncolor == None:
139 if ncolor == None:
140 raise ValueError, "The colormap selected is not valid"
140 raise ValueError, "The colormap selected is not valid"
141
141
142 plplot.plscmap1n(ncolor)
142 plplot.plscmap1n(ncolor)
143 plplot.plscmap1l(1, pos, r, g, b)
143 plplot.plscmap1l(1, pos, r, g, b)
144
144
145 return rgb_lvl
145 return rgb_lvl
146
146
147 class BaseGraph:
147 class BaseGraph:
148 """
148 """
149
149
150 """
150 """
151
151
152
152
153
153
154 def __init__(self):
154 def __init__(self):
155 """
155 """
156
156
157 """
157 """
158 self.hasNotRange = True
158 self.hasNotRange = True
159
159
160 self.xrange = None
160 self.xrange = None
161 self.yrange = None
161 self.yrange = None
162 self.zrange = None
162 self.zrange = None
163
163
164 self.xlabel = None
164 self.xlabel = None
165 self.ylabel = None
165 self.ylabel = None
166 self.title = None
166 self.title = None
167
167
168 self.legends = None
168 self.legends = None
169
169
170 self.__name = None
170 self.__name = None
171
171
172 self.__colormap = None
172 self.__colormap = None
173 self.__colbox = None
173 self.__colbox = None
174 self.__colleg = None
174 self.__colleg = None
175
175
176 self.__xpos = None
176 self.__xpos = None
177 self.__ypos = None
177 self.__ypos = None
178
178
179 self.__xopt = None #"bcnst"
179 self.__xopt = None #"bcnst"
180 self.__yopt = None #"bcnstv"
180 self.__yopt = None #"bcnstv"
181
181
182 self.__xlpos = None
182 self.__xlpos = None
183 self.__ylpos = None
183 self.__ylpos = None
184
184
185 self.__xrangeIsTime = False
185 self.__xrangeIsTime = False
186
186
187 #Advanced
187 #Advanced
188 self.__xg = None
188 self.__xg = None
189 self.__yg = None
189 self.__yg = None
190
190
191 def setName(self, name):
191 def setName(self, name):
192 self.__name = name
192 self.__name = name
193
193
194 def setScreenPos(self, xpos, ypos):
194 def setScreenPos(self, xpos, ypos):
195 self.__xpos = xpos
195 self.__xpos = xpos
196 self.__ypos = ypos
196 self.__ypos = ypos
197
197
198 def setOpt(self, xopt, yopt):
198 def setOpt(self, xopt, yopt):
199 self.__xopt = xopt
199 self.__xopt = xopt
200 self.__yopt = yopt
200 self.__yopt = yopt
201
201
202 def setXAxisAsTime(self):
202 def setXAxisAsTime(self):
203 self.__xrangeIsTime = True
203 self.__xrangeIsTime = True
204
204
205
205
206 def setup(self, title=None, xlabel=None, ylabel=None, colormap=None):
206 def setup(self, title=None, xlabel=None, ylabel=None, colormap=None):
207 """
207 """
208 """
208 """
209 self.title = title
209 self.title = title
210 self.xlabel = xlabel
210 self.xlabel = xlabel
211 self.ylabel = ylabel
211 self.ylabel = ylabel
212 self.__colormap = colormap
212 self.__colormap = colormap
213
213
214 def plotBox(self, xmin, xmax, ymin, ymax):
214 def plotBox(self, xmin, xmax, ymin, ymax, xopt=None, yopt=None):
215 """
215 """
216
216
217 """
217 """
218 if self.__xrangeIsTime:
218 if self.__xrangeIsTime:
219 plplot.pltimefmt("%H:%M")
219 plplot.pltimefmt("%H:%M")
220
220
221 plplot.plvpor(self.__xpos[0], self.__xpos[1], self.__ypos[0], self.__ypos[1])
221 plplot.plvpor(self.__xpos[0], self.__xpos[1], self.__ypos[0], self.__ypos[1])
222 plplot.plwind(float(xmin),
222 plplot.plwind(float(xmin),
223 float(xmax),
223 float(xmax),
224 float(ymin),
224 float(ymin),
225 float(ymax)
225 float(ymax)
226 )
226 )
227 plplot.plbox(self.__xopt, 0.0, 0, self.__yopt, 0.0, 0)
227
228 if xopt == None: xopt = self.__xopt
229 if yopt == None: yopt = self.__yopt
230
231 plplot.plbox(xopt, 0.0, 0, yopt, 0.0, 0)
232
228 plplot.pllab(self.xlabel, self.ylabel, self.title)
233 plplot.pllab(self.xlabel, self.ylabel, self.title)
229
234
230
235
231 def colorbarPlot(self, xmin=0., xmax=1., ymin=0., ymax=1.):
236 def colorbarPlot(self, xmin=0., xmax=1., ymin=0., ymax=1.):
232 data = numpy.arange(256)
237 data = numpy.arange(256)
233 data = numpy.reshape(data, (1,-1))
238 data = numpy.reshape(data, (1,-1))
234
239
235 plplot.plimage(data,
240 plplot.plimage(data,
236 float(xmin),
241 float(xmin),
237 float(xmax),
242 float(xmax),
238 float(ymin),
243 float(ymin),
239 float(ymax),
244 float(ymax),
240 0.,
245 0.,
241 255.,
246 255.,
242 float(xmin),
247 float(xmin),
243 float(xmax),
248 float(xmax),
244 float(ymin),
249 float(ymin),
245 float(ymax))
250 float(ymax))
246
251
247 def basicXYPlot(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None):
252 def basicXYPlot(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None):
248
253
249 if xmin == None: xmin = x[0]
254 if xmin == None: xmin = x[0]
250 if xmax == None: xmax = x[-1]
255 if xmax == None: xmax = x[-1]
251 if ymin == None: ymin = y[0]
256 if ymin == None: ymin = y[0]
252 if ymax == None: ymax = y[-1]
257 if ymax == None: ymax = y[-1]
253
258
254 plplot.plline(x, y)
259 plplot.plline(x, y)
255
260
256 def basicXYwithErrorPlot(self):
261 def basicXYwithErrorPlot(self):
257 pass
262 pass
258
263
259 def basicLineTimePlot(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None, colline=1):
264 def basicLineTimePlot(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None, colline=1):
260
265
261 if xmin == None: xmin = x[0]
266 if xmin == None: xmin = x[0]
262 if xmax == None: xmax = x[-1]
267 if xmax == None: xmax = x[-1]
263 if ymin == None: ymin = y[0]
268 if ymin == None: ymin = y[0]
264 if ymax == None: ymax = y[-1]
269 if ymax == None: ymax = y[-1]
265
270
266 plplot.plcol0(colline)
271 plplot.plcol0(colline)
267 plplot.plline(x, y)
272 plplot.plline(x, y)
268 plplot.plcol0(1)
273 plplot.plcol0(1)
269
274
270 def basicPcolorPlot(self, data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None):
275 def basicPcolorPlot(self, data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None):
271 """
276 """
272 """
277 """
273 if xmin == None: xmin = x[0]
278 if xmin == None: xmin = x[0]
274 if xmax == None: xmax = x[-1]
279 if xmax == None: xmax = x[-1]
275 if ymin == None: ymin = y[0]
280 if ymin == None: ymin = y[0]
276 if ymax == None: ymax = y[-1]
281 if ymax == None: ymax = y[-1]
277 if zmin == None: zmin = numpy.nanmin(data)
282 if zmin == None: zmin = numpy.nanmin(data)
278 if zmax == None: zmax = numpy.nanmax(data)
283 if zmax == None: zmax = numpy.nanmax(data)
279
284
280 plplot.plimage(data,
285 plplot.plimage(data,
281 float(x[0]),
286 float(x[0]),
282 float(x[-1]),
287 float(x[-1]),
283 float(y[0]),
288 float(y[0]),
284 float(y[-1]),
289 float(y[-1]),
285 float(zmin),
290 float(zmin),
286 float(zmax),
291 float(zmax),
287 float(xmin),
292 float(xmin),
288 float(xmax),
293 float(xmax),
289 float(ymin),
294 float(ymin),
290 float(ymax)
295 float(ymax)
291 )
296 )
292
297
293 def __getBoxpltr(self, x, y, deltax=None, deltay=None):
298 def __getBoxpltr(self, x, y, deltax=None, deltay=None):
294
299
295 if not(len(x)>1 and len(y)>1):
300 if not(len(x)>1 and len(y)>1):
296 raise ValueError, "x axis and y axis are empty"
301 raise ValueError, "x axis and y axis are empty"
297
302
298 if deltax == None: deltax = x[-1] - x[-2]
303 if deltax == None: deltax = x[-1] - x[-2]
299 if deltay == None: deltay = y[-1] - y[-2]
304 if deltay == None: deltay = y[-1] - y[-2]
300
305
301 x1 = numpy.append(x, x[-1] + deltax)
306 x1 = numpy.append(x, x[-1] + deltax)
302 y1 = numpy.append(y, y[-1] + deltay)
307 y1 = numpy.append(y, y[-1] + deltay)
303
308
304 xg = (numpy.multiply.outer(x1, numpy.ones(len(y1))))
309 xg = (numpy.multiply.outer(x1, numpy.ones(len(y1))))
305 yg = (numpy.multiply.outer(numpy.ones(len(x1)), y1))
310 yg = (numpy.multiply.outer(numpy.ones(len(x1)), y1))
306
311
307 self.__xg = xg
312 self.__xg = xg
308 self.__yg = yg
313 self.__yg = yg
309
314
310 def advPcolorPlot(self, data, x, y, zmin=0., zmax=0.):
315 def advPcolorPlot(self, data, x, y, zmin=0., zmax=0.):
311 """
316 """
312 """
317 """
313
318
314 if self.__xg == None and self.__yg == None:
319 if self.__xg == None and self.__yg == None:
315 self.__getBoxpltr(x, y)
320 self.__getBoxpltr(x, y)
316
321
317 plplot.plimagefr(data, x[0], x[-1], y[0], y[-1], 0., 0., zmin, zmax, plplot.pltr2, self.__xg, self.__yg)
322 plplot.plimagefr(data, x[0], x[-1], y[0], y[-1], 0., 0., zmin, zmax, plplot.pltr2, self.__xg, self.__yg)
318
323
319
324
320 class LinearPlot():
325 class LinearPlot():
321
326
322 __szchar = 1.0
327 __szchar = 1.0
323 __xrange = None
328 __xrange = None
324 __yrange = None
329 __yrange = None
325
330
326 m_BaseGraph = None
331 m_BaseGraph = None
327
332
328 def __init__(self):
333 def __init__(self):
329
334
330
335
331 key = "linearplot"
336 key = "linearplot"
332 self.m_BaseGraph = BaseGraph()
337 self.m_BaseGraph = BaseGraph()
333 self.m_BaseGraph.setName(key)
338 self.m_BaseGraph.setName(key)
334
339
335 self.__subpage = 0
340 self.__subpage = 0
336
341
337 def setColormap(self, colormap="br_green"):
342 def setColormap(self, colormap="br_green"):
338
343
339 if colormap == None:
344 if colormap == None:
340 colormap = self.__colormap
345 colormap = self.__colormap
341
346
342 cmap1_init(colormap)
347 cmap1_init(colormap)
343
348
344 def iniSubpage(self):
349 def iniSubpage(self):
345
350
346 if plplot.plgdev() == '':
351 if plplot.plgdev() == '':
347 raise ValueError, "Plot device has not been initialize"
352 raise ValueError, "Plot device has not been initialize"
348
353
349 plplot.pladv(self.__subpage)
354 plplot.pladv(self.__subpage)
350 plplot.plschr(0.0, self.__szchar)
355 plplot.plschr(0.0, self.__szchar)
351
356
352 self.setColormap()
357 self.setColormap()
353
358
354 def setScreenPos(self, width='small'):
359 def setScreenPos(self, width='small'):
355
360
356 if width == 'small':
361 if width == 'small':
357 xi = 0.12; yi = 0.14; xw = 0.78; yw = 0.80
362 xi = 0.12; yi = 0.14; xw = 0.78; yw = 0.80
358
363
359 if width == 'medium':
364 if width == 'medium':
360 xi = 0.07; yi = 0.10; xw = 0.90; yw = 0.60
365 xi = 0.07; yi = 0.10; xw = 0.90; yw = 0.60
361
366
362 xf = xi + xw
367 xf = xi + xw
363 yf = yi + yw
368 yf = yi + yw
364
369
365 self.m_BaseGraph.setScreenPos([xi, xf], [yi, yf])
370 self.m_BaseGraph.setScreenPos([xi, xf], [yi, yf])
366
371
367 def setup(self, subpage, title="", xlabel="", ylabel="", XAxisAsTime=False):
372 def setup(self, subpage, title="", xlabel="", ylabel="", XAxisAsTime=False):
368 """
373 """
369 """
374 """
370
375
371 self.m_BaseGraph.setOpt("bcnts","bcntsv")
376 self.m_BaseGraph.setOpt("bcnts","bcntsv")
372 self.m_BaseGraph.setup(title,
377 self.m_BaseGraph.setup(title,
373 xlabel,
378 xlabel,
374 ylabel
379 ylabel
375 )
380 )
376
381
377 self.setScreenPos(width='medium')
382 self.setScreenPos(width='medium')
378
383
379 if XAxisAsTime:
384 if XAxisAsTime:
380 self.m_BaseGraph.setXAxisAsTime()
385 self.m_BaseGraph.setXAxisAsTime()
381
386
382 self.__subpage = subpage
387 self.__subpage = subpage
383 # def setRanges(self, xrange, yrange, zrange):
388 # def setRanges(self, xrange, yrange, zrange):
384 #
389 #
385 # self.m_BaseGraph.setRanges(xrange, yrange, zrange)
390 # self.m_BaseGraph.setRanges(xrange, yrange, zrange)
386
391
387 def plotData(self, x, y=None, xmin=None, xmax=None, ymin=None, ymax=None, colline=1):
392 def plotData(self, x, y=None, xmin=None, xmax=None, ymin=None, ymax=None, colline=1):
388 """
393 """
389 Inputs:
394 Inputs:
390
395
391 x : Numpy array of dimension 1
396 x : Numpy array of dimension 1
392 y : Numpy array of dimension 1
397 y : Numpy array of dimension 1
393
398
394 """
399 """
395
400
396 try:
401 try:
397 nX = numpy.shape(x)
402 nX = numpy.shape(x)
398 except:
403 except:
399 raise ValueError, "x is not a numpy array"
404 raise ValueError, "x is not a numpy array"
400
405
401 if y == None: y = numpy.arange(nX)
406 if y == None: y = numpy.arange(nX)
402
407
403 if xmin == None: xmin = x[0]
408 if xmin == None: xmin = x[0]
404 if xmax == None: xmax = x[-1]
409 if xmax == None: xmax = x[-1]
405 if ymin == None: ymin = y[0]
410 if ymin == None: ymin = y[0]
406 if ymax == None: ymax = y[-1]
411 if ymax == None: ymax = y[-1]
407
412
408 self.m_BaseGraph.plotBox(xmin, xmax, ymin, ymax)
413 self.m_BaseGraph.plotBox(xmin, xmax, ymin, ymax)
409 self.m_BaseGraph.basicLineTimePlot(x, y, xmin, xmax, ymin, ymax, colline)
414 self.m_BaseGraph.basicLineTimePlot(x, y, xmin, xmax, ymin, ymax, colline)
410
415
411 def plotComplexData(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None, colline=1, type='power'):
416 def plotComplexData(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None, colline=1, type='power'):
412 """
417 """
413 Inputs:
418 Inputs:
414
419
415 x : Numpy array of dimension 1
420 x : Numpy array of dimension 1
416 y : Complex numpy array of dimension 1
421 y : Complex numpy array of dimension 1
417
422
418 """
423 """
419
424
420 try:
425 try:
421 nX = numpy.shape(x)
426 nX = numpy.shape(x)
422 except:
427 except:
423 raise ValueError, "x is not a numpy array"
428 raise ValueError, "x is not a numpy array"
424
429
425 try:
430 try:
426 nY = numpy.shape(y)
431 nY = numpy.shape(y)
427 except:
432 except:
428 raise ValueError, "y is not a numpy array"
433 raise ValueError, "y is not a numpy array"
429
434
430 if xmin == None: xmin = x[0]
435 if xmin == None: xmin = x[0]
431 if xmax == None: xmax = x[-1]
436 if xmax == None: xmax = x[-1]
432 if ymin == None: ymin = y[0]
437 if ymin == None: ymin = y[0]
433 if ymax == None: ymax = y[-1]
438 if ymax == None: ymax = y[-1]
434
439
435 self.m_BaseGraph.plotBox(xmin, xmax, ymin, ymax)
440 self.m_BaseGraph.plotBox(xmin, xmax, ymin, ymax)
436
441
437 if type.lower() == 'power':
442 if type.lower() == 'power':
438 self.m_BaseGraph.basicLineTimePlot(x, abs(y), xmin, xmax, ymin, ymax, colline)
443 self.m_BaseGraph.basicLineTimePlot(x, abs(y), xmin, xmax, ymin, ymax, colline)
439
444
440 if type.lower() == 'iq':
445 if type.lower() == 'iq':
441
446
442 self.m_BaseGraph.basicLineTimePlot(x, y.real, xmin, xmax, ymin, ymax, colline)
447 self.m_BaseGraph.basicLineTimePlot(x, y.real, xmin, xmax, ymin, ymax, colline)
443 self.m_BaseGraph.basicLineTimePlot(x, y.imag, xmin, xmax, ymin, ymax, colline+1)
448 self.m_BaseGraph.basicLineTimePlot(x, y.imag, xmin, xmax, ymin, ymax, colline+1)
444
449
445 class ColorPlot():
450 class ColorPlot():
446
451
447 def __init__(self):
452 def __init__(self):
448
453
449 self.graphObjDict = {}
454 self.graphObjDict = {}
450
455
451 self.__subpage = 0
456 self.__subpage = 0
452 self.__showColorbar = False
457 self.__showColorbar = False
453 self.__showPowerProfile = True
458 self.__showPowerProfile = True
454
459
455 self.__szchar = 0.7
460 self.__szchar = 0.7
456 self.__xrange = None
461 self.__xrange = None
457 self.__yrange = None
462 self.__yrange = None
458 self.__zrange = None
463 self.__zrange = None
459
464
460 key = "colorplot"
465 key = "colorplot"
461 self.m_BaseGraph = BaseGraph()
466 self.m_BaseGraph = BaseGraph()
462 self.m_BaseGraph.setName(key)
467 self.m_BaseGraph.setName(key)
463
468
464 def setup(self, subpage, title="", xlabel="Frequency", ylabel="Range", colormap="jet", showColorbar=False, showPowerProfile=False, XAxisAsTime=False):
469 def setup(self, subpage, title="", xlabel="Frequency", ylabel="Range", colormap="jet", showColorbar=False, showPowerProfile=False, XAxisAsTime=False):
465 """
470 """
466 """
471 """
467
472
468 self.m_BaseGraph.setOpt("bcnts","bcntsv")
473 self.m_BaseGraph.setOpt("bcnts","bcntsv")
469 self.m_BaseGraph.setup(title,
474 self.m_BaseGraph.setup(title,
470 xlabel,
475 xlabel,
471 ylabel
476 ylabel
472 )
477 )
473
478
474 self.__subpage = subpage
479 self.__subpage = subpage
475 self.__colormap = colormap
480 self.__colormap = colormap
476 self.__showColorbar = showColorbar
481 self.__showColorbar = showColorbar
477 self.__showPowerProfile = showPowerProfile
482 self.__showPowerProfile = showPowerProfile
478
483
479 if showColorbar:
484 if showColorbar:
480 key = "colorbar"
485 key = "colorbar"
481
486
482 cmapObj = BaseGraph()
487 cmapObj = BaseGraph()
483 cmapObj.setName(key)
488 cmapObj.setName(key)
484 cmapObj.setOpt("bc","bcmt")
489 cmapObj.setOpt("bc","bcmt")
485 cmapObj.setup(title="dBs",
490 cmapObj.setup(title="dBs",
486 xlabel="",
491 xlabel="",
487 ylabel="",
492 ylabel="",
488 colormap=colormap)
493 colormap=colormap)
489
494
490 self.graphObjDict[key] = cmapObj
495 self.graphObjDict[key] = cmapObj
491
496
492
497
493 if showPowerProfile:
498 if showPowerProfile:
494 key = "powerprof"
499 key = "powerprof"
495
500
496 powObj = BaseGraph()
501 powObj = BaseGraph()
497 powObj.setName(key)
502 powObj.setName(key)
498 powObj.setOpt("bcntg","bc")
503 powObj.setOpt("bcntg","bc")
499 powObj.setup(title="Power Profile",
504 powObj.setup(title="Power Profile",
500 xlabel="dBs",
505 xlabel="dB",
501 ylabel="")
506 ylabel="")
502
507
503 self.graphObjDict[key] = powObj
508 self.graphObjDict[key] = powObj
504
509
505 self.setScreenPos(width='small')
510 self.setScreenPos(width='small')
506
511
507 if XAxisAsTime:
512 if XAxisAsTime:
508 self.m_BaseGraph.setXAxisAsTime()
513 self.m_BaseGraph.setXAxisAsTime()
509
514
510
515
511
516
512 def setColormap(self, colormap="br_green"):
517 def setColormap(self, colormap="br_green"):
513
518
514 if colormap == None:
519 if colormap == None:
515 colormap = self.__colormap
520 colormap = self.__colormap
516
521
517 cmap1_init(colormap)
522 cmap1_init(colormap)
518
523
519 def iniSubpage(self):
524 def iniSubpage(self):
520
525
521 if plplot.plgdev() == '':
526 if plplot.plgdev() == '':
522 raise ValueError, "Plot device has not been initialize"
527 raise ValueError, "Plot device has not been initialize"
523
528
524 plplot.pladv(self.__subpage)
529 plplot.pladv(self.__subpage)
525 plplot.plschr(0.0, self.__szchar)
530 plplot.plschr(0.0, self.__szchar)
526
531
527 self.setColormap()
532 self.setColormap()
528
533
529 def setScreenPos(self, width='small'):
534 def setScreenPos(self, width='small'):
530
535
531 if width == 'small':
536 if width == 'small':
532 xi = 0.12; yi = 0.12; xw = 0.86; yw = 0.70; xcmapw = 0.05; xpoww = 0.26; deltaxcmap = 0.02; deltaxpow = 0.06
537 xi = 0.13; yi = 0.12; xw = 0.86; yw = 0.70; xcmapw = 0.05; xpoww = 0.26; deltaxcmap = 0.02; deltaxpow = 0.05
533
538
534 if width == 'medium':
539 if width == 'medium':
535 xi = 0.07; yi = 0.10; xw = 0.90; yw = 0.60; xcmapw = 0.05; xpoww = 0.24; deltaxcmap = 0.02; deltaxpow = 0.06
540 xi = 0.07; yi = 0.10; xw = 0.90; yw = 0.60; xcmapw = 0.05; xpoww = 0.24; deltaxcmap = 0.02; deltaxpow = 0.06
536
541
537 if self.__showColorbar:
542 if self.__showColorbar:
538 xw -= xcmapw + deltaxcmap
543 xw -= xcmapw + deltaxcmap
539
544
540 if self.__showPowerProfile:
545 if self.__showPowerProfile:
541 xw -= xpoww + deltaxpow
546 xw -= xpoww + deltaxpow
542
547
543 xf = xi + xw
548 xf = xi + xw
544 yf = yi + yw
549 yf = yi + yw
545 xcmapf = xf
550 xcmapf = xf
546
551
547 self.m_BaseGraph.setScreenPos([xi, xf], [yi, yf])
552 self.m_BaseGraph.setScreenPos([xi, xf], [yi, yf])
548
553
549 if self.__showColorbar:
554 if self.__showColorbar:
550 xcmapi = xf + deltaxcmap
555 xcmapi = xf + deltaxcmap
551 xcmapf = xcmapi + xcmapw
556 xcmapf = xcmapi + xcmapw
552
557
553 key = "colorbar"
558 key = "colorbar"
554 cmapObj = self.graphObjDict[key]
559 cmapObj = self.graphObjDict[key]
555 cmapObj.setScreenPos([xcmapi, xcmapf], [yi, yf])
560 cmapObj.setScreenPos([xcmapi, xcmapf], [yi, yf])
556
561
557 if self.__showPowerProfile:
562 if self.__showPowerProfile:
558
563
559 xpowi = xcmapf + deltaxpow
564 xpowi = xcmapf + deltaxpow
560 xpowf = xpowi + xpoww
565 xpowf = xpowi + xpoww
561
566
562 key = "powerprof"
567 key = "powerprof"
563 powObj = self.graphObjDict[key]
568 powObj = self.graphObjDict[key]
564 powObj.setScreenPos([xpowi, xpowf], [yi, yf])
569 powObj.setScreenPos([xpowi, xpowf], [yi, yf])
565
570
566
571
567
572
568 def plotData(self, data, x=None, y=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None):
573 def plotData(self, data, x=None, y=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None):
569 """
574 """
570 Inputs:
575 Inputs:
571
576
572 x : Numpy array of dimension 1
577 x : Numpy array of dimension 1
573 y : Numpy array of dimension 1
578 y : Numpy array of dimension 1
574
579
575 """
580 """
576
581
577 try:
582 try:
578 nX, nY = numpy.shape(data)
583 nX, nY = numpy.shape(data)
579 except:
584 except:
580 raise ValueError, "data is not a numpy array"
585 raise ValueError, "data is not a numpy array"
581
586
582 if x == None: x = numpy.arange(nX)
587 if x == None: x = numpy.arange(nX)
583 if y == None: y = numpy.arange(nY)
588 if y == None: y = numpy.arange(nY)
584
589
585 if xmin == None: xmin = x[0]
590 if xmin == None: xmin = x[0]
586 if xmax == None: xmax = x[-1]
591 if xmax == None: xmax = x[-1]
587 if ymin == None: ymin = y[0]
592 if ymin == None: ymin = y[0]
588 if ymax == None: ymax = y[-1]
593 if ymax == None: ymax = y[-1]
589 if zmin == None: zmin = numpy.nanmin(data)
594 if zmin == None: zmin = numpy.nanmin(data)
590 if zmax == None: zmax = numpy.nanmax(data)
595 if zmax == None: zmax = numpy.nanmax(data)
591
596
592 self.m_BaseGraph.plotBox(xmin, xmax, ymin, ymax)
597 self.m_BaseGraph.plotBox(xmin, xmax, ymin, ymax)
593 self.m_BaseGraph.basicPcolorPlot(data, x, y, xmin, xmax, ymin, ymax, zmin, zmax)
598 self.m_BaseGraph.basicPcolorPlot(data, x, y, xmin, xmax, ymin, ymax, zmin, zmax)
594
599
595 if self.__showColorbar:
600 if self.__showColorbar:
596 key = "colorbar"
601 key = "colorbar"
597 cmapObj = self.graphObjDict[key]
602 cmapObj = self.graphObjDict[key]
598 cmapObj.plotBox(0., 1., zmin, zmax)
603 cmapObj.plotBox(0., 1., zmin, zmax)
599 cmapObj.colorbarPlot(0., 1., zmin, zmax)
604 cmapObj.colorbarPlot(0., 1., zmin, zmax)
600
605
601 if self.__showPowerProfile:
606 if self.__showPowerProfile:
602 power = numpy.average(data, axis=0)
607 power = numpy.max(data, axis=0)
603
608
604 step = (ymax - ymin)/(nY-1)
609 step = (ymax - ymin)/(nY-1)
605 heis = numpy.arange(ymin, ymax + step, step)
610 heis = numpy.arange(ymin, ymax + step, step)
606
611
607 key = "powerprof"
612 key = "powerprof"
608 powObj = self.graphObjDict[key]
613 powObj = self.graphObjDict[key]
609
614
610 plplot.pllsty(2)
615 plplot.pllsty(2)
611 powObj.plotBox(zmin, zmax, ymin, ymax)
616 powObj.plotBox(zmin, zmax, ymin, ymax)
612 plplot.pllsty(1)
617 plplot.pllsty(1)
618 powObj.plotBox(zmin, zmax, ymin, ymax, xopt='bc', yopt='bc')
619 plplot.plcol0(9)
613 powObj.basicXYPlot(power, heis)
620 powObj.basicXYPlot(power, heis)
621 plplot.plcol0(1)
614
622
615
623
616 class ColorPlotX():
624 class ColorPlotX():
617
625
618
626
619 graphObjDict = {}
627 graphObjDict = {}
620 showColorbar = False
628 showColorbar = False
621 showPowerProfile = True
629 showPowerProfile = True
622
630
623 __szchar = 0.7
631 __szchar = 0.7
624 __xrange = None
632 __xrange = None
625 __yrange = None
633 __yrange = None
626 __zrange = None
634 __zrange = None
627
635
628 m_BaseGraph = BaseGraph()
636 m_BaseGraph = BaseGraph()
629
637
630 def __init__(self):
638 def __init__(self):
631
639
632 key = "colorplot"
640 key = "colorplot"
633 self.m_BaseGraph.setName(key)
641 self.m_BaseGraph.setName(key)
634
642
635 self.__subpage = 0
643 self.__subpage = 0
636
644
637 self.graphObjDict[key] = self.m_BaseGraph
645 self.graphObjDict[key] = self.m_BaseGraph
638
646
639 def setColormap(self, colormap="br_green"):
647 def setColormap(self, colormap="br_green"):
640
648
641 if colormap == None:
649 if colormap == None:
642 colormap = self.__colormap
650 colormap = self.__colormap
643
651
644 cmap1_init(colormap)
652 cmap1_init(colormap)
645
653
646 def iniSubpage(self):
654 def iniSubpage(self):
647
655
648 if plplot.plgdev() == '':
656 if plplot.plgdev() == '':
649 raise ValueError, "Plot device has not been initialize"
657 raise ValueError, "Plot device has not been initialize"
650
658
651 plplot.pladv(self.__subpage)
659 plplot.pladv(self.__subpage)
652 plplot.plschr(0.0, self.__szchar)
660 plplot.plschr(0.0, self.__szchar)
653
661
654 self.setColormap()
662 self.setColormap()
655
663
656 def setup(self, subpage, title="", xlabel="", ylabel="", colormap="jet", showColorbar=False, showPowerProfile=False, XAxisAsTime=False):
664 def setup(self, subpage, title="", xlabel="", ylabel="", colormap="jet", showColorbar=False, showPowerProfile=False, XAxisAsTime=False):
657 """
665 """
658 """
666 """
659
667
660 self.m_BaseGraph.setSubpage(subpage)
668 self.m_BaseGraph.setSubpage(subpage)
661 self.m_BaseGraph.setSzchar(self.__szchar)
669 self.m_BaseGraph.setSzchar(self.__szchar)
662 self.m_BaseGraph.setOpt("bcnts","bcntsv")
670 self.m_BaseGraph.setOpt("bcnts","bcntsv")
663 self.m_BaseGraph.setup(title,
671 self.m_BaseGraph.setup(title,
664 xlabel,
672 xlabel,
665 ylabel,
673 ylabel,
666 colormap)
674 colormap)
667
675
668 if showColorbar:
676 if showColorbar:
669 key = "colorbar"
677 key = "colorbar"
670
678
671 cmapObj = BaseGraph()
679 cmapObj = BaseGraph()
672 cmapObj.setName(key)
680 cmapObj.setName(key)
673 cmapObj.setSubpage(subpage)
681 cmapObj.setSubpage(subpage)
674 cmapObj.setSzchar(self.__szchar)
682 cmapObj.setSzchar(self.__szchar)
675 cmapObj.setOpt("bc","bcmt")
683 cmapObj.setOpt("bc","bcmt")
676 cmapObj.setup(title="dBs",
684 cmapObj.setup(title="dBs",
677 xlabel="",
685 xlabel="",
678 ylabel="",
686 ylabel="",
679 colormap=colormap)
687 colormap=colormap)
680
688
681 self.graphObjDict[key] = cmapObj
689 self.graphObjDict[key] = cmapObj
682
690
683
691
684 if showPowerProfile:
692 if showPowerProfile:
685 key = "powerprof"
693 key = "powerprof"
686
694
687 powObj = BaseGraph()
695 powObj = BaseGraph()
688 powObj.setName(key)
696 powObj.setName(key)
689 powObj.setSubpage(subpage)
697 powObj.setSubpage(subpage)
690 powObj.setSzchar(self.__szchar)
698 powObj.setSzchar(self.__szchar)
691 plplot.pllsty(2)
699 plplot.pllsty(2)
692 powObj.setOpt("bcntg","bc")
700 powObj.setOpt("bcntg","bc")
693 plplot.pllsty(1)
701 plplot.pllsty(1)
694 powObj.setup(title="Power Profile",
702 powObj.setup(title="Power Profile",
695 xlabel="dBs",
703 xlabel="dBs",
696 ylabel="")
704 ylabel="")
697
705
698 self.graphObjDict[key] = powObj
706 self.graphObjDict[key] = powObj
699
707
700 self.showColorbar = showColorbar
708 self.showColorbar = showColorbar
701 self.showPowerProfile = showPowerProfile
709 self.showPowerProfile = showPowerProfile
702 self.setScreenPos()
710 self.setScreenPos()
703
711
704 if XAxisAsTime:
712 if XAxisAsTime:
705 self.m_BaseGraph.setXAxisAsTime()
713 self.m_BaseGraph.setXAxisAsTime()
706 #self.setScreenPos(xi = 0.05, yi = 0.18, xw = 0.92, yw = 0.74, xcmapw = 0.015, xpoww = 0.14, deltaxcmap = 0.01, deltaxpow = 0.02)
714 #self.setScreenPos(xi = 0.05, yi = 0.18, xw = 0.92, yw = 0.74, xcmapw = 0.015, xpoww = 0.14, deltaxcmap = 0.01, deltaxpow = 0.02)
707
715
708
716
709 def setScreenPos(self, xi = 0.12, yi = 0.14, xw = 0.78, yw = 0.80, xcmapw = 0.05, xpoww = 0.24, deltaxcmap = 0.02, deltaxpow = 0.06):
717 def setScreenPos(self, xi = 0.12, yi = 0.14, xw = 0.78, yw = 0.80, xcmapw = 0.05, xpoww = 0.24, deltaxcmap = 0.02, deltaxpow = 0.06):
710
718
711 if self.showColorbar:
719 if self.showColorbar:
712 xw -= xcmapw + deltaxcmap
720 xw -= xcmapw + deltaxcmap
713
721
714 if self.showPowerProfile:
722 if self.showPowerProfile:
715 xw -= xpoww + deltaxpow
723 xw -= xpoww + deltaxpow
716
724
717 xf = xi + xw
725 xf = xi + xw
718 yf = yi + yw
726 yf = yi + yw
719 xcmapf = xf
727 xcmapf = xf
720
728
721 self.m_BaseGraph.setScreenPos([xi, xf], [yi, yf])
729 self.m_BaseGraph.setScreenPos([xi, xf], [yi, yf])
722
730
723 if self.showColorbar:
731 if self.showColorbar:
724 xcmapi = xf + deltaxcmap
732 xcmapi = xf + deltaxcmap
725 xcmapf = xcmapi + xcmapw
733 xcmapf = xcmapi + xcmapw
726
734
727 key = "colorbar"
735 key = "colorbar"
728 cmapObj = self.graphObjDict[key]
736 cmapObj = self.graphObjDict[key]
729 cmapObj.setScreenPos([xcmapi, xcmapf], [yi, yf])
737 cmapObj.setScreenPos([xcmapi, xcmapf], [yi, yf])
730
738
731 if self.showPowerProfile:
739 if self.showPowerProfile:
732
740
733 xpowi = xcmapf + deltaxpow
741 xpowi = xcmapf + deltaxpow
734 xpowf = xpowi + xpoww
742 xpowf = xpowi + xpoww
735
743
736 key = "powerprof"
744 key = "powerprof"
737 powObj = self.graphObjDict[key]
745 powObj = self.graphObjDict[key]
738 powObj.setScreenPos([xpowi, xpowf], [yi, yf])
746 powObj.setScreenPos([xpowi, xpowf], [yi, yf])
739
747
740 def setRanges(self, xrange, yrange, zrange):
748 def setRanges(self, xrange, yrange, zrange):
741
749
742 self.m_BaseGraph.setRanges(xrange, yrange, zrange)
750 self.m_BaseGraph.setRanges(xrange, yrange, zrange)
743
751
744 keyList = self.graphObjDict.keys()
752 keyList = self.graphObjDict.keys()
745
753
746 key = "colorbar"
754 key = "colorbar"
747 if key in keyList:
755 if key in keyList:
748 cmapObj = self.graphObjDict[key]
756 cmapObj = self.graphObjDict[key]
749 cmapObj.setRanges([0., 1.], zrange)
757 cmapObj.setRanges([0., 1.], zrange)
750
758
751 key = "powerprof"
759 key = "powerprof"
752 if key in keyList:
760 if key in keyList:
753 powObj = self.graphObjDict[key]
761 powObj = self.graphObjDict[key]
754 powObj.setRanges(zrange, yrange)
762 powObj.setRanges(zrange, yrange)
755
763
756 def plotData(self, data, x=None, y=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None):
764 def plotData(self, data, x=None, y=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None):
757 """
765 """
758 """
766 """
759
767
760 try:
768 try:
761 nX, nY = numpy.shape(data)
769 nX, nY = numpy.shape(data)
762 except:
770 except:
763 raise ValueError, "data is not a numpy array"
771 raise ValueError, "data is not a numpy array"
764
772
765 if x == None: x = numpy.arange(nX)
773 if x == None: x = numpy.arange(nX)
766 if y == None: y = numpy.arange(nY)
774 if y == None: y = numpy.arange(nY)
767
775
768 if xmin == None: xmin = x[0]
776 if xmin == None: xmin = x[0]
769 if xmax == None: xmax = x[-1]
777 if xmax == None: xmax = x[-1]
770 if ymin == None: ymin = y[0]
778 if ymin == None: ymin = y[0]
771 if ymax == None: ymax = y[-1]
779 if ymax == None: ymax = y[-1]
772 if zmin == None: zmin = numpy.nanmin(data)
780 if zmin == None: zmin = numpy.nanmin(data)
773 if zmax == None: zmax = numpy.nanmax(data)
781 if zmax == None: zmax = numpy.nanmax(data)
774
782
775 if self.m_BaseGraph.hasNotRange:
783 if self.m_BaseGraph.hasNotRange:
776 self.setRanges([xmin, xmax], [ymin,ymax], [zmin,zmax])
784 self.setRanges([xmin, xmax], [ymin,ymax], [zmin,zmax])
777
785
778 self.m_BaseGraph.initSubpage()
786 self.m_BaseGraph.initSubpage()
779 self.m_BaseGraph.basicPcolorPlot(data, x, y, xmin, xmax, ymin, ymax, self.m_BaseGraph.zrange[0], self.m_BaseGraph.zrange[1])
787 self.m_BaseGraph.basicPcolorPlot(data, x, y, xmin, xmax, ymin, ymax, self.m_BaseGraph.zrange[0], self.m_BaseGraph.zrange[1])
780
788
781 if self.showColorbar:
789 if self.showColorbar:
782 key = "colorbar"
790 key = "colorbar"
783 cmapObj = self.graphObjDict[key]
791 cmapObj = self.graphObjDict[key]
784 cmapObj.colorbarPlot()
792 cmapObj.colorbarPlot()
785
793
786 if self.showPowerProfile:
794 if self.showPowerProfile:
787 power = numpy.average(data, axis=1)
795 power = numpy.average(data, axis=1)
788
796
789 step = (ymax - ymin)/(nY-1)
797 step = (ymax - ymin)/(nY-1)
790 heis = numpy.arange(ymin, ymax + step, step)
798 heis = numpy.arange(ymin, ymax + step, step)
791
799
792 key = "powerprof"
800 key = "powerprof"
793 powObj = self.graphObjDict[key]
801 powObj = self.graphObjDict[key]
794 powObj.basicXYPlot(power, heis)
802 powObj.basicXYPlot(power, heis)
795
803
796 if __name__ == '__main__':
804 if __name__ == '__main__':
797
805
798 import numpy
806 import numpy
799 plplot.plsetopt("geometry", "%dx%d" %(350*2, 300*2))
807 plplot.plsetopt("geometry", "%dx%d" %(350*2, 300*2))
800 plplot.plsdev("xwin")
808 plplot.plsdev("xwin")
801 plplot.plscolbg(255,255,255)
809 plplot.plscolbg(255,255,255)
802 plplot.plscol0(1,0,0,0)
810 plplot.plscol0(1,0,0,0)
803 plplot.plspause(False)
811 plplot.plspause(False)
804 plplot.plinit()
812 plplot.plinit()
805 plplot.plssub(2, 2)
813 plplot.plssub(2, 2)
806
814
807 nx = 64
815 nx = 64
808 ny = 100
816 ny = 100
809
817
810 data = numpy.random.uniform(-50,50,(nx,ny))
818 data = numpy.random.uniform(-50,50,(nx,ny))
811
819
812 baseObj = ColorPlot()
820 baseObj = ColorPlot()
813 specObj = ColorPlot()
821 specObj = ColorPlot()
814 baseObj1 = ColorPlot()
822 baseObj1 = ColorPlot()
815 specObj1 = ColorPlot()
823 specObj1 = ColorPlot()
816
824
817 baseObj.setup(1, "Spectrum", "Frequency", "Range", "br_green", True, True)
825 baseObj.setup(1, "Spectrum", "Frequency", "Range", "br_green", True, True)
818 specObj.setup(2, "Spectrum", "Frequency", "Range", "br_green", False, True)
826 specObj.setup(2, "Spectrum", "Frequency", "Range", "br_green", False, True)
819
827
820 baseObj1.setup(3, "Spectrum", "Frequency", "Range", "br_green", False, True)
828 baseObj1.setup(3, "Spectrum", "Frequency", "Range", "br_green", False, True)
821 specObj1.setup(4, "Spectrum", "Frequency", "Range", "br_green", False, True)
829 specObj1.setup(4, "Spectrum", "Frequency", "Range", "br_green", False, True)
822
830
823 data = numpy.random.uniform(-50,50,(nx,ny))
831 data = numpy.random.uniform(-50,50,(nx,ny))
824
832
825 plplot.plbop()
833 plplot.plbop()
826 baseObj.iniSubpage()
834 baseObj.iniSubpage()
827 baseObj.plotData(data)
835 baseObj.plotData(data)
828
836
829 specObj.iniSubpage()
837 specObj.iniSubpage()
830 specObj.plotData(data)
838 specObj.plotData(data)
831
839
832 baseObj1.iniSubpage()
840 baseObj1.iniSubpage()
833 baseObj1.plotData(data)
841 baseObj1.plotData(data)
834
842
835 specObj1.iniSubpage()
843 specObj1.iniSubpage()
836 specObj1.plotData(data)
844 specObj1.plotData(data)
837
845
838 plplot.plflush()
846 plplot.plflush()
839
847
840 plplot.plspause(1)
848 plplot.plspause(1)
841 plplot.plend()
849 plplot.plend()
842 exit(0)
850 exit(0)
843
851
844
852
@@ -1,149 +1,156
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 import plplot
10 import plplot
11
11
12 path = os.path.split(os.getcwd())[0]
12 path = os.path.split(os.getcwd())[0]
13 sys.path.append(path)
13 sys.path.append(path)
14
14
15 from Graphics.BaseGraph import *
15 from Graphics.BaseGraph import *
16 from Model.Spectra import Spectra
16 from Model.Spectra import Spectra
17
17
18 class Spectrum():
18 class Spectrum():
19
19
20 def __init__(self, Spectra):
20 def __init__(self, Spectra):
21
21
22 """
22 """
23
23
24 Inputs:
24 Inputs:
25
25
26 type: "power" ->> Potencia
26 type: "power" ->> Potencia
27 "iq" ->> Real + Imaginario
27 "iq" ->> Real + Imaginario
28 """
28 """
29
29
30 self.__isPlotConfig = False
30 self.__isPlotConfig = False
31
31
32 self.__isPlotIni = False
32 self.__isPlotIni = False
33
33
34 self.__xrange = None
34 self.__xrange = None
35
35
36 self.__yrange = None
36 self.__yrange = None
37
37
38 self.nGraphs = 0
38 self.nGraphs = 0
39
39
40 self.graphObjList = []
40 self.graphObjList = []
41
41
42 self.m_Spectra = Spectra
42 self.m_Spectra = Spectra
43
43
44
44
45 def __addGraph(self, subpage, title="", xlabel="", ylabel="", showColorbar=False, showPowerProfile=True, XAxisAsTime=False):
45 def __addGraph(self, subpage, title="", xlabel="", ylabel="", showColorbar=False, showPowerProfile=True, XAxisAsTime=False):
46
46
47 graphObj = ColorPlot()
47 graphObj = ColorPlot()
48 graphObj.setup(subpage,
48 graphObj.setup(subpage,
49 title,
49 title,
50 xlabel,
50 xlabel,
51 ylabel,
51 ylabel,
52 showColorbar=showColorbar,
52 showColorbar=showColorbar,
53 showPowerProfile=showPowerProfile,
53 showPowerProfile=showPowerProfile,
54 XAxisAsTime=XAxisAsTime)
54 XAxisAsTime=XAxisAsTime)
55
55
56 self.graphObjList.append(graphObj)
56 self.graphObjList.append(graphObj)
57
57
58
58
59 def setup(self, titleList=None, xlabelList=None, ylabelList=None, showColorbar=False, showPowerProfile=True, XAxisAsTime=False):
59 def setup(self, titleList=None, xlabelList=None, ylabelList=None, showColorbar=False, showPowerProfile=True, XAxisAsTime=False):
60
60
61 nChan = int(self.m_Spectra.m_SystemHeader.numChannels)
61 nChan = int(self.m_Spectra.m_SystemHeader.numChannels)
62 channels = range(nChan)
62
63
63 myTitle = ""
64 myXlabel = "Radial Velocity (m/s)"
64 myXlabel = ""
65 myYlabel = "Range (km)"
65 myYlabel = ""
66
66
67 for i in range(nChan):
67 for i in channels:
68 if titleList != None:
68 if titleList != None:
69 myTitle = titleList[i]
69 myTitle = titleList[i]
70 myXlabel = xlabelList[i]
70 myXlabel = xlabelList[i]
71 myYlabel = ylabelList[i]
71 myYlabel = ylabelList[i]
72
72
73 if self.m_Spectra.noise != None:
74 noise = '%4.2fdB' %(self.m_Spectra.noise[i])
75 else:
76 noise = '--'
77
78 myTitle = "Channel: %d - Noise: %s" %(i, noise)
79
73 self.__addGraph(i+1,
80 self.__addGraph(i+1,
74 title=myTitle,
81 title=myTitle,
75 xlabel=myXlabel,
82 xlabel=myXlabel,
76 ylabel=myYlabel,
83 ylabel=myYlabel,
77 showColorbar=showColorbar,
84 showColorbar=showColorbar,
78 showPowerProfile=showPowerProfile,
85 showPowerProfile=showPowerProfile,
79 XAxisAsTime=XAxisAsTime)
86 XAxisAsTime=XAxisAsTime)
80
87
81 self.nGraphs = nChan
88 self.nGraphs = nChan
82 self.__isPlotConfig = True
89 self.__isPlotConfig = True
83
90
84 def iniPlot(self):
91 def iniPlot(self):
85
92
86 nx = int(numpy.sqrt(self.nGraphs)+1)
93 nx = int(numpy.sqrt(self.nGraphs)+1)
87 #ny = int(self.nGraphs/nx)
94 #ny = int(self.nGraphs/nx)
88
95
89 plplot.plsetopt("geometry", "%dx%d" %(400*nx, 300*nx))
96 plplot.plsetopt("geometry", "%dx%d" %(300*nx, 240*nx))
90 plplot.plsdev("xcairo")
97 plplot.plsdev("xcairo")
91 plplot.plscolbg(255,255,255)
98 plplot.plscolbg(255,255,255)
92 plplot.plscol0(1,0,0,0)
99 plplot.plscol0(1,0,0,0)
93 plplot.plinit()
100 plplot.plinit()
94 plplot.plspause(False)
101 plplot.plspause(False)
95 plplot.pladv(0)
102 plplot.pladv(0)
96 plplot.plssub(nx, nx)
103 plplot.plssub(nx, nx)
97
104
98 self.__isPlotIni = True
105 self.__isPlotIni = True
99
106
100 def plotData(self, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, titleList=None, xlabelList=None, ylabelList=None, showColorbar=False, showPowerProfile=True, XAxisAsTime=False):
107 def plotData(self, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, titleList=None, xlabelList=None, ylabelList=None, showColorbar=False, showPowerProfile=True, XAxisAsTime=False):
101
108
102 if not(self.__isPlotConfig):
109 if not(self.__isPlotConfig):
103 self.setup(titleList,
110 self.setup(titleList,
104 xlabelList,
111 xlabelList,
105 ylabelList,
112 ylabelList,
106 showColorbar,
113 showColorbar,
107 showPowerProfile,
114 showPowerProfile,
108 XAxisAsTime)
115 XAxisAsTime)
109
116
110 if not(self.__isPlotIni):
117 if not(self.__isPlotIni):
111 self.iniPlot()
118 self.iniPlot()
112
119
113 data = numpy.log10(self.m_Spectra.data_spc)
120 data = 10.*numpy.log10(self.m_Spectra.data_spc)
114
121
115 nX, nY, nChan = numpy.shape(data)
122 nX, nY, nChan = numpy.shape(data)
116
123
117 x = numpy.arange(nX)
124 x = numpy.arange(nX)
118 y = self.m_Spectra.heights
125 y = self.m_Spectra.heights
119
126
120 if xmin == None: xmin = x[0]
127 if xmin == None: xmin = x[0]
121 if xmax == None: xmax = x[-1]
128 if xmax == None: xmax = x[-1]
122 if ymin == None: ymin = y[0]
129 if ymin == None: ymin = y[0]
123 if ymax == None: ymax = y[-1]
130 if ymax == None: ymax = y[-1]
124 if zmin == None: zmin = numpy.nanmin(abs(data))
131 if zmin == None: zmin = numpy.nanmin(abs(data))
125 if zmax == None: zmax = numpy.nanmax(abs(data))
132 if zmax == None: zmax = numpy.nanmax(abs(data))
126
133
127 plplot.plbop()
134 plplot.plbop()
128 for i in range(self.nGraphs):
135 for i in range(self.nGraphs):
129 self.graphObjList[i].iniSubpage()
136 self.graphObjList[i].iniSubpage()
130 self.graphObjList[i].plotData(data[:,:,i],
137 self.graphObjList[i].plotData(data[i,:,:],
131 x,
138 x,
132 y,
139 y,
133 xmin=xmin,
140 xmin=xmin,
134 xmax=xmax,
141 xmax=xmax,
135 ymin=ymin,
142 ymin=ymin,
136 ymax=ymax,
143 ymax=ymax,
137 zmin=zmin,
144 zmin=zmin,
138 zmax=zmax)
145 zmax=zmax)
139
146
140
147
141 plplot.plflush()
148 plplot.plflush()
142 plplot.pleop()
149 plplot.pleop()
143
150
144 def end(self):
151 def end(self):
145 plplot.plend()
152 plplot.plend()
146
153
147
154
148 if __name__ == '__main__':
155 if __name__ == '__main__':
149 pass No newline at end of file
156 pass
@@ -1,402 +1,409
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 '''
6 '''
7
7
8 import numpy
8 import numpy
9
9
10 class BasicHeader:
10 class BasicHeader:
11
11
12 def __init__(self):
12 def __init__(self):
13 self.size = 0
13 self.size = 0
14 self.version = 0
14 self.version = 0
15 self.dataBlock = 0
15 self.dataBlock = 0
16 self.utc = 0
16 self.utc = 0
17 self.miliSecond = 0
17 self.miliSecond = 0
18 self.timeZone = 0
18 self.timeZone = 0
19 self.dstFlag = 0
19 self.dstFlag = 0
20 self.errorCount = 0
20 self.errorCount = 0
21 self.struct = numpy.dtype([
21 self.struct = numpy.dtype([
22 ('nSize','<u4'),
22 ('nSize','<u4'),
23 ('nVersion','<u2'),
23 ('nVersion','<u2'),
24 ('nDataBlockId','<u4'),
24 ('nDataBlockId','<u4'),
25 ('nUtime','<u4'),
25 ('nUtime','<u4'),
26 ('nMilsec','<u2'),
26 ('nMilsec','<u2'),
27 ('nTimezone','<i2'),
27 ('nTimezone','<i2'),
28 ('nDstflag','<i2'),
28 ('nDstflag','<i2'),
29 ('nErrorCount','<u4')
29 ('nErrorCount','<u4')
30 ])
30 ])
31 pass
31 pass
32
32
33 def read(self, fp):
33 def read(self, fp):
34
34
35 header = numpy.fromfile(fp, self.struct,1)
35 header = numpy.fromfile(fp, self.struct,1)
36 self.size = header['nSize'][0]
36 self.size = header['nSize'][0]
37 self.version = header['nVersion'][0]
37 self.version = header['nVersion'][0]
38 self.dataBlock = header['nDataBlockId'][0]
38 self.dataBlock = header['nDataBlockId'][0]
39 self.utc = header['nUtime'][0]
39 self.utc = header['nUtime'][0]
40 self.miliSecond = header['nMilsec'][0]
40 self.miliSecond = header['nMilsec'][0]
41 self.timeZone = header['nTimezone'][0]
41 self.timeZone = header['nTimezone'][0]
42 self.dstFlag = header['nDstflag'][0]
42 self.dstFlag = header['nDstflag'][0]
43 self.errorCount = header['nErrorCount'][0]
43 self.errorCount = header['nErrorCount'][0]
44
44
45 return 1
45 return 1
46
46
47 def copy(self):
47 def copy(self):
48
48
49 obj = BasicHeader()
49 obj = BasicHeader()
50 obj.size = self.size
50 obj.size = self.size
51 obj.version = self.version
51 obj.version = self.version
52 obj.dataBlock = self.dataBlock
52 obj.dataBlock = self.dataBlock
53 obj.utc = self.utc
53 obj.utc = self.utc
54 obj.miliSecond = self.miliSecond
54 obj.miliSecond = self.miliSecond
55 obj.timeZone = self.timeZone
55 obj.timeZone = self.timeZone
56 obj.dstFlag = self.dstFlag
56 obj.dstFlag = self.dstFlag
57 obj.errorCount = self.errorCount
57 obj.errorCount = self.errorCount
58
58
59 return obj
59 return obj
60
60
61 def write(self, fp):
61 def write(self, fp):
62 headerTuple = (self.size,self.version,self.dataBlock,self.utc,self.miliSecond,self.timeZone,self.dstFlag,self.errorCount)
62 headerTuple = (self.size,self.version,self.dataBlock,self.utc,self.miliSecond,self.timeZone,self.dstFlag,self.errorCount)
63 header = numpy.array(headerTuple,self.struct)
63 header = numpy.array(headerTuple,self.struct)
64 header.tofile(fp)
64 header.tofile(fp)
65
65
66 return 1
66 return 1
67
67
68 class SystemHeader:
68 class SystemHeader:
69
69
70 def __init__(self):
70 def __init__(self):
71 self.size = 0
71 self.size = 0
72 self.numSamples = 0
72 self.numSamples = 0
73 self.numProfiles = 0
73 self.numProfiles = 0
74 self.numChannels = 0
74 self.numChannels = 0
75 self.adcResolution = 0
75 self.adcResolution = 0
76 self.pciDioBusWidth = 0
76 self.pciDioBusWidth = 0
77 self.struct = numpy.dtype([
77 self.struct = numpy.dtype([
78 ('nSize','<u4'),
78 ('nSize','<u4'),
79 ('nNumSamples','<u4'),
79 ('nNumSamples','<u4'),
80 ('nNumProfiles','<u4'),
80 ('nNumProfiles','<u4'),
81 ('nNumChannels','<u4'),
81 ('nNumChannels','<u4'),
82 ('nADCResolution','<u4'),
82 ('nADCResolution','<u4'),
83 ('nPCDIOBusWidth','<u4'),
83 ('nPCDIOBusWidth','<u4'),
84 ])
84 ])
85
85
86
86
87 def read(self, fp):
87 def read(self, fp):
88 header = numpy.fromfile(fp,self.struct,1)
88 header = numpy.fromfile(fp,self.struct,1)
89 self.size = header['nSize'][0]
89 self.size = header['nSize'][0]
90 self.numSamples = header['nNumSamples'][0]
90 self.numSamples = header['nNumSamples'][0]
91 self.numProfiles = header['nNumProfiles'][0]
91 self.numProfiles = header['nNumProfiles'][0]
92 self.numChannels = header['nNumChannels'][0]
92 self.numChannels = header['nNumChannels'][0]
93 self.adcResolution = header['nADCResolution'][0]
93 self.adcResolution = header['nADCResolution'][0]
94 self.pciDioBusWidth = header['nPCDIOBusWidth'][0]
94 self.pciDioBusWidth = header['nPCDIOBusWidth'][0]
95
95
96
96
97 return 1
97 return 1
98
98
99 def copy(self):
99 def copy(self):
100
100
101 obj = SystemHeader()
101 obj = SystemHeader()
102 obj.size = self.size
102 obj.size = self.size
103 obj.numSamples = self.numSamples
103 obj.numSamples = self.numSamples
104 obj.numProfiles = self.numProfiles
104 obj.numProfiles = self.numProfiles
105 obj.numChannels = self.numChannels
105 obj.numChannels = self.numChannels
106 obj.adcResolution = self.adcResolution
106 obj.adcResolution = self.adcResolution
107 self.pciDioBusWidth = self.pciDioBusWidth
107 self.pciDioBusWidth = self.pciDioBusWidth
108
108
109
109
110 return obj
110 return obj
111
111
112 def write(self, fp):
112 def write(self, fp):
113 headerTuple = (self.size,self.numSamples,self.numProfiles,self.numChannels,self.adcResolution,self.pciDioBusWidth)
113 headerTuple = (self.size,self.numSamples,self.numProfiles,self.numChannels,self.adcResolution,self.pciDioBusWidth)
114 header = numpy.array(headerTuple,self.struct)
114 header = numpy.array(headerTuple,self.struct)
115 header.tofile(fp)
115 header.tofile(fp)
116
116
117 return 1
117 return 1
118
118
119 class RadarControllerHeader:
119 class RadarControllerHeader:
120
120
121
121
122 def __init__(self):
122 def __init__(self):
123 self.size = 0
123 self.size = 0
124 self.expType = 0
124 self.expType = 0
125 self.nTx = 0
125 self.nTx = 0
126 self.ipp = 0
126 self.ipp = 0
127 self.txA = 0
127 self.txA = 0
128 self.txB = 0
128 self.txB = 0
129 self.numWindows = 0
129 self.numWindows = 0
130 self.numTaus = 0
130 self.numTaus = 0
131 self.codeType = 0
131 self.codeType = 0
132 self.line6Function = 0
132 self.line6Function = 0
133 self.line5Function = 0
133 self.line5Function = 0
134 self.fClock = 0
134 self.fClock = 0
135 self.prePulseBefore = 0
135 self.prePulseBefore = 0
136 self.prePulserAfter = 0
136 self.prePulserAfter = 0
137 self.rangeIpp = 0
137 self.rangeIpp = 0
138 self.rangeTxA = 0
138 self.rangeTxA = 0
139 self.rangeTxB = 0
139 self.rangeTxB = 0
140 self.struct = numpy.dtype([
140 self.struct = numpy.dtype([
141 ('nSize','<u4'),
141 ('nSize','<u4'),
142 ('nExpType','<u4'),
142 ('nExpType','<u4'),
143 ('nNTx','<u4'),
143 ('nNTx','<u4'),
144 ('fIpp','<f4'),
144 ('fIpp','<f4'),
145 ('fTxA','<f4'),
145 ('fTxA','<f4'),
146 ('fTxB','<f4'),
146 ('fTxB','<f4'),
147 ('nNumWindows','<u4'),
147 ('nNumWindows','<u4'),
148 ('nNumTaus','<u4'),
148 ('nNumTaus','<u4'),
149 ('nCodeType','<u4'),
149 ('nCodeType','<u4'),
150 ('nLine6Function','<u4'),
150 ('nLine6Function','<u4'),
151 ('nLine5Function','<u4'),
151 ('nLine5Function','<u4'),
152 ('fClock','<f4'),
152 ('fClock','<f4'),
153 ('nPrePulseBefore','<u4'),
153 ('nPrePulseBefore','<u4'),
154 ('nPrePulseAfter','<u4'),
154 ('nPrePulseAfter','<u4'),
155 ('sRangeIPP','<a20'),
155 ('sRangeIPP','<a20'),
156 ('sRangeTxA','<a20'),
156 ('sRangeTxA','<a20'),
157 ('sRangeTxB','<a20'),
157 ('sRangeTxB','<a20'),
158 ])
158 ])
159 self.dynamic = numpy.array([],numpy.dtype('byte'))
159 self.dynamic = numpy.array([],numpy.dtype('byte'))
160
160
161
161
162 def read(self, fp):
162 def read(self, fp):
163 header = numpy.fromfile(fp,self.struct,1)
163 header = numpy.fromfile(fp,self.struct,1)
164 self.size = header['nSize'][0]
164 self.size = header['nSize'][0]
165 self.expType = header['nExpType'][0]
165 self.expType = header['nExpType'][0]
166 self.nTx = header['nNTx'][0]
166 self.nTx = header['nNTx'][0]
167 self.ipp = header['fIpp'][0]
167 self.ipp = header['fIpp'][0]
168 self.txA = header['fTxA'][0]
168 self.txA = header['fTxA'][0]
169 self.txB = header['fTxB'][0]
169 self.txB = header['fTxB'][0]
170 self.numWindows = header['nNumWindows'][0]
170 self.numWindows = header['nNumWindows'][0]
171 self.numTaus = header['nNumTaus'][0]
171 self.numTaus = header['nNumTaus'][0]
172 self.codeType = header['nCodeType'][0]
172 self.codeType = header['nCodeType'][0]
173 self.line6Function = header['nLine6Function'][0]
173 self.line6Function = header['nLine6Function'][0]
174 self.line5Function = header['nLine5Function'][0]
174 self.line5Function = header['nLine5Function'][0]
175 self.fClock = header['fClock'][0]
175 self.fClock = header['fClock'][0]
176 self.prePulseBefore = header['nPrePulseBefore'][0]
176 self.prePulseBefore = header['nPrePulseBefore'][0]
177 self.prePulserAfter = header['nPrePulseAfter'][0]
177 self.prePulserAfter = header['nPrePulseAfter'][0]
178 self.rangeIpp = header['sRangeIPP'][0]
178 self.rangeIpp = header['sRangeIPP'][0]
179 self.rangeTxA = header['sRangeTxA'][0]
179 self.rangeTxA = header['sRangeTxA'][0]
180 self.rangeTxB = header['sRangeTxB'][0]
180 self.rangeTxB = header['sRangeTxB'][0]
181 # jump Dynamic Radar Controller Header
181 # jump Dynamic Radar Controller Header
182 jumpHeader = self.size - 116
182 jumpHeader = self.size - 116
183 self.dynamic = numpy.fromfile(fp,numpy.dtype('byte'),jumpHeader)
183 self.dynamic = numpy.fromfile(fp,numpy.dtype('byte'),jumpHeader)
184
184
185 return 1
185 return 1
186
186
187 def copy(self):
187 def copy(self):
188
188
189 obj = RadarControllerHeader()
189 obj = RadarControllerHeader()
190 obj.size = self.size
190 obj.size = self.size
191 obj.expType = self.expType
191 obj.expType = self.expType
192 obj.nTx = self.nTx
192 obj.nTx = self.nTx
193 obj.ipp = self.ipp
193 obj.ipp = self.ipp
194 obj.txA = self.txA
194 obj.txA = self.txA
195 obj.txB = self.txB
195 obj.txB = self.txB
196 obj.numWindows = self.numWindows
196 obj.numWindows = self.numWindows
197 obj.numTaus = self.numTaus
197 obj.numTaus = self.numTaus
198 obj.codeType = self.codeType
198 obj.codeType = self.codeType
199 obj.line6Function = self.line6Function
199 obj.line6Function = self.line6Function
200 obj.line5Function = self.line5Function
200 obj.line5Function = self.line5Function
201 obj.fClock = self.fClock
201 obj.fClock = self.fClock
202 obj.prePulseBefore = self.prePulseBefore
202 obj.prePulseBefore = self.prePulseBefore
203 obj.prePulserAfter = self.prePulserAfter
203 obj.prePulserAfter = self.prePulserAfter
204 obj.rangeIpp = self.rangeIpp
204 obj.rangeIpp = self.rangeIpp
205 obj.rangeTxA = self.rangeTxA
205 obj.rangeTxA = self.rangeTxA
206 obj.rangeTxB = self.rangeTxB
206 obj.rangeTxB = self.rangeTxB
207 obj.dynamic = self.dynamic
207 obj.dynamic = self.dynamic
208
208
209 return obj
209 return obj
210
210
211 def write(self, fp):
211 def write(self, fp):
212 headerTuple = (self.size,
212 headerTuple = (self.size,
213 self.expType,
213 self.expType,
214 self.nTx,
214 self.nTx,
215 self.ipp,
215 self.ipp,
216 self.txA,
216 self.txA,
217 self.txB,
217 self.txB,
218 self.numWindows,
218 self.numWindows,
219 self.numTaus,
219 self.numTaus,
220 self.codeType,
220 self.codeType,
221 self.line6Function,
221 self.line6Function,
222 self.line5Function,
222 self.line5Function,
223 self.fClock,
223 self.fClock,
224 self.prePulseBefore,
224 self.prePulseBefore,
225 self.prePulserAfter,
225 self.prePulserAfter,
226 self.rangeIpp,
226 self.rangeIpp,
227 self.rangeTxA,
227 self.rangeTxA,
228 self.rangeTxB)
228 self.rangeTxB)
229
229
230 header = numpy.array(headerTuple,self.struct)
230 header = numpy.array(headerTuple,self.struct)
231 header.tofile(fp)
231 header.tofile(fp)
232
232
233 dynamic = self.dynamic
233 dynamic = self.dynamic
234 dynamic.tofile(fp)
234 dynamic.tofile(fp)
235
235
236 return 1
236 return 1
237
237
238
238
239
239
240 class ProcessingHeader:
240 class ProcessingHeader:
241
241
242 def __init__(self):
242 def __init__(self):
243 self.size = 0
243 self.size = 0
244 self.dataType = 0
244 self.dataType = 0
245 self.blockSize = 0
245 self.blockSize = 0
246 self.profilesPerBlock = 0
246 self.profilesPerBlock = 0
247 self.dataBlocksPerFile = 0
247 self.dataBlocksPerFile = 0
248 self.numWindows = 0
248 self.numWindows = 0
249 self.processFlags = 0
249 self.processFlags = 0
250 self.coherentInt = 0
250 self.coherentInt = 0
251 self.incoherentInt = 0
251 self.incoherentInt = 0
252 self.totalSpectra = 0
252 self.totalSpectra = 0
253 self.struct = numpy.dtype([
253 self.struct = numpy.dtype([
254 ('nSize','<u4'),
254 ('nSize','<u4'),
255 ('nDataType','<u4'),
255 ('nDataType','<u4'),
256 ('nSizeOfDataBlock','<u4'),
256 ('nSizeOfDataBlock','<u4'),
257 ('nProfilesperBlock','<u4'),
257 ('nProfilesperBlock','<u4'),
258 ('nDataBlocksperFile','<u4'),
258 ('nDataBlocksperFile','<u4'),
259 ('nNumWindows','<u4'),
259 ('nNumWindows','<u4'),
260 ('nProcessFlags','<u4'),
260 ('nProcessFlags','<u4'),
261 ('nCoherentIntegrations','<u4'),
261 ('nCoherentIntegrations','<u4'),
262 ('nIncoherentIntegrations','<u4'),
262 ('nIncoherentIntegrations','<u4'),
263 ('nTotalSpectra','<u4')
263 ('nTotalSpectra','<u4')
264 ])
264 ])
265 self.samplingWindow = 0
265 self.samplingWindow = 0
266 self.structSamplingWindow = numpy.dtype([('h0','<f4'),('dh','<f4'),('nsa','<u4')])
266 self.structSamplingWindow = numpy.dtype([('h0','<f4'),('dh','<f4'),('nsa','<u4')])
267 self.numHeights = 0
267 self.numHeights = 0
268 self.firstHeight = 0
268 self.firstHeight = 0
269 self.deltaHeight = 0
269 self.deltaHeight = 0
270 self.samplesWin = 0
270 self.samplesWin = 0
271 self.spectraComb = 0
271 self.spectraComb = 0
272 self.numCode = 0
272 self.numCode = 0
273 self.codes = 0
273 self.codes = 0
274 self.numBaud = 0
274 self.numBaud = 0
275
275
276 def read(self, fp):
276 def read(self, fp):
277 header = numpy.fromfile(fp,self.struct,1)
277 header = numpy.fromfile(fp,self.struct,1)
278 self.size = header['nSize'][0]
278 self.size = header['nSize'][0]
279 self.dataType = header['nDataType'][0]
279 self.dataType = header['nDataType'][0]
280 self.blockSize = header['nSizeOfDataBlock'][0]
280 self.blockSize = header['nSizeOfDataBlock'][0]
281 self.profilesPerBlock = header['nProfilesperBlock'][0]
281 self.profilesPerBlock = header['nProfilesperBlock'][0]
282 self.dataBlocksPerFile = header['nDataBlocksperFile'][0]
282 self.dataBlocksPerFile = header['nDataBlocksperFile'][0]
283 self.numWindows = header['nNumWindows'][0]
283 self.numWindows = header['nNumWindows'][0]
284 self.processFlags = header['nProcessFlags']
284 self.processFlags = header['nProcessFlags']
285 self.coherentInt = header['nCoherentIntegrations'][0]
285 self.coherentInt = header['nCoherentIntegrations'][0]
286 self.incoherentInt = header['nIncoherentIntegrations'][0]
286 self.incoherentInt = header['nIncoherentIntegrations'][0]
287 self.totalSpectra = header['nTotalSpectra'][0]
287 self.totalSpectra = header['nTotalSpectra'][0]
288 self.samplingWindow = numpy.fromfile(fp,self.structSamplingWindow,self.numWindows)
288 self.samplingWindow = numpy.fromfile(fp,self.structSamplingWindow,self.numWindows)
289 self.numHeights = numpy.sum(self.samplingWindow['nsa'])
289 self.numHeights = numpy.sum(self.samplingWindow['nsa'])
290 self.firstHeight = self.samplingWindow['h0']
290 self.firstHeight = self.samplingWindow['h0']
291 self.deltaHeight = self.samplingWindow['dh']
291 self.deltaHeight = self.samplingWindow['dh']
292 self.samplesWin = self.samplingWindow['nsa']
292 self.samplesWin = self.samplingWindow['nsa']
293 self.spectraComb = numpy.fromfile(fp,'u1',2*self.totalSpectra)
293 self.spectraComb = numpy.fromfile(fp,'u1',2*self.totalSpectra)
294
294 if self.processFlags & PROCFLAG.DEFINE_PROCESS_CODE == PROCFLAG.DEFINE_PROCESS_CODE:
295 if self.processFlags & PROCFLAG.DEFINE_PROCESS_CODE == PROCFLAG.DEFINE_PROCESS_CODE:
295 self.numCode = numpy.fromfile(fp,'<u4',1)
296 self.numCode = numpy.fromfile(fp,'<u4',1)
296 self.numBaud = numpy.fromfile(fp,'<u4',1)
297 self.numBaud = numpy.fromfile(fp,'<u4',1)
297 self.codes = numpy.fromfile(fp,'<f4',self.numCode*self.numBaud).reshape(self.numBaud,self.numCode)
298 self.codes = numpy.fromfile(fp,'<f4',self.numCode*self.numBaud).reshape(self.numBaud,self.numCode)
298
299
300 if self.processFlags & PROCFLAG.SHIFT_FFT_DATA == PROCFLAG.SHIFT_FFT_DATA:
301 self.shif_fft = True
302 else:
303 self.shif_fft = False
304
299
305
300 return 1
306 return 1
301
307
302 def copy(self):
308 def copy(self):
303
309
304 obj = ProcessingHeader()
310 obj = ProcessingHeader()
305 obj.size = self.size
311 obj.size = self.size
306 obj.dataType = self.dataType
312 obj.dataType = self.dataType
307 obj.blockSize = self.blockSize
313 obj.blockSize = self.blockSize
308 obj.profilesPerBlock = self.profilesPerBlock
314 obj.profilesPerBlock = self.profilesPerBlock
309 obj.dataBlocksPerFile = self.dataBlocksPerFile
315 obj.dataBlocksPerFile = self.dataBlocksPerFile
310 obj.numWindows = self.numWindows
316 obj.numWindows = self.numWindows
311 obj.processFlags = self.processFlags
317 obj.processFlags = self.processFlags
312 obj.coherentInt = self.coherentInt
318 obj.coherentInt = self.coherentInt
313 obj.incoherentInt = self.incoherentInt
319 obj.incoherentInt = self.incoherentInt
314 obj.totalSpectra = self.totalSpectra
320 obj.totalSpectra = self.totalSpectra
315 obj.samplingWindow = self.samplingWindow
321 obj.samplingWindow = self.samplingWindow
316 obj.numHeights = self.numHeights
322 obj.numHeights = self.numHeights
317 obj.firstHeight = self.firstHeight
323 obj.firstHeight = self.firstHeight
318 obj.deltaHeight = self.deltaHeight
324 obj.deltaHeight = self.deltaHeight
319 obj.samplesWin = self.samplesWin
325 obj.samplesWin = self.samplesWin
320 obj.spectraComb = self.spectraComb
326 obj.spectraComb = self.spectraComb
321 obj.numCode = self.numCode
327 obj.numCode = self.numCode
322 obj.numBaud = self.numBaud
328 obj.numBaud = self.numBaud
323 obj.codes = self.codes
329 obj.codes = self.codes
324
330
331 obj.shif_fft = self.shif_fft
325 return obj
332 return obj
326
333
327 def write(self, fp):
334 def write(self, fp):
328 headerTuple = (self.size,
335 headerTuple = (self.size,
329 self.dataType,
336 self.dataType,
330 self.blockSize,
337 self.blockSize,
331 self.profilesPerBlock,
338 self.profilesPerBlock,
332 self.dataBlocksPerFile,
339 self.dataBlocksPerFile,
333 self.numWindows,
340 self.numWindows,
334 self.processFlags,
341 self.processFlags,
335 self.coherentInt,
342 self.coherentInt,
336 self.incoherentInt,
343 self.incoherentInt,
337 self.totalSpectra)
344 self.totalSpectra)
338
345
339 header = numpy.array(headerTuple,self.struct)
346 header = numpy.array(headerTuple,self.struct)
340 header.tofile(fp)
347 header.tofile(fp)
341
348
342 if self.numWindows != 0:
349 if self.numWindows != 0:
343 sampleWindowTuple = (self.firstHeight,self.deltaHeight,self.samplesWin)
350 sampleWindowTuple = (self.firstHeight,self.deltaHeight,self.samplesWin)
344 samplingWindow = numpy.array(sampleWindowTuple,self.structSamplingWindow)
351 samplingWindow = numpy.array(sampleWindowTuple,self.structSamplingWindow)
345 samplingWindow.tofile(fp)
352 samplingWindow.tofile(fp)
346
353
347
354
348 if self.totalSpectra != 0:
355 if self.totalSpectra != 0:
349 spectraComb = numpy.array([],numpy.dtype('u1'))
356 spectraComb = numpy.array([],numpy.dtype('u1'))
350 spectraComb = self.spectraComb
357 spectraComb = self.spectraComb
351 spectraComb.tofile(fp)
358 spectraComb.tofile(fp)
352
359
353
360
354 if self.processFlags & PROCFLAG.DEFINE_PROCESS_CODE == PROCFLAG.DEFINE_PROCESS_CODE:
361 if self.processFlags & PROCFLAG.DEFINE_PROCESS_CODE == PROCFLAG.DEFINE_PROCESS_CODE:
355 numCode = self.numCode
362 numCode = self.numCode
356 numCode.tofile(fp)
363 numCode.tofile(fp)
357
364
358 numBaud = self.numBaud
365 numBaud = self.numBaud
359 numBaud.tofile(fp)
366 numBaud.tofile(fp)
360
367
361 codes = self.codes.reshape(numCode*numBaud)
368 codes = self.codes.reshape(numCode*numBaud)
362 codes.tofile(fp)
369 codes.tofile(fp)
363
370
364 return 1
371 return 1
365
372
366
373
367 class PROCFLAG:
374 class PROCFLAG:
368 COHERENT_INTEGRATION = numpy.uint32(0x00000001)
375 COHERENT_INTEGRATION = numpy.uint32(0x00000001)
369 DECODE_DATA = numpy.uint32(0x00000002)
376 DECODE_DATA = numpy.uint32(0x00000002)
370 SPECTRA_CALC = numpy.uint32(0x00000004)
377 SPECTRA_CALC = numpy.uint32(0x00000004)
371 INCOHERENT_INTEGRATION = numpy.uint32(0x00000008)
378 INCOHERENT_INTEGRATION = numpy.uint32(0x00000008)
372 POST_COHERENT_INTEGRATION = numpy.uint32(0x00000010)
379 POST_COHERENT_INTEGRATION = numpy.uint32(0x00000010)
373 SHIFT_FFT_DATA = numpy.uint32(0x00000020)
380 SHIFT_FFT_DATA = numpy.uint32(0x00000020)
374
381
375 DATATYPE_CHAR = numpy.uint32(0x00000040)
382 DATATYPE_CHAR = numpy.uint32(0x00000040)
376 DATATYPE_SHORT = numpy.uint32(0x00000080)
383 DATATYPE_SHORT = numpy.uint32(0x00000080)
377 DATATYPE_LONG = numpy.uint32(0x00000100)
384 DATATYPE_LONG = numpy.uint32(0x00000100)
378 DATATYPE_INT64 = numpy.uint32(0x00000200)
385 DATATYPE_INT64 = numpy.uint32(0x00000200)
379 DATATYPE_FLOAT = numpy.uint32(0x00000400)
386 DATATYPE_FLOAT = numpy.uint32(0x00000400)
380 DATATYPE_DOUBLE = numpy.uint32(0x00000800)
387 DATATYPE_DOUBLE = numpy.uint32(0x00000800)
381
388
382 DATAARRANGE_CONTIGUOUS_CH = numpy.uint32(0x00001000)
389 DATAARRANGE_CONTIGUOUS_CH = numpy.uint32(0x00001000)
383 DATAARRANGE_CONTIGUOUS_H = numpy.uint32(0x00002000)
390 DATAARRANGE_CONTIGUOUS_H = numpy.uint32(0x00002000)
384 DATAARRANGE_CONTIGUOUS_P = numpy.uint32(0x00004000)
391 DATAARRANGE_CONTIGUOUS_P = numpy.uint32(0x00004000)
385
392
386 SAVE_CHANNELS_DC = numpy.uint32(0x00008000)
393 SAVE_CHANNELS_DC = numpy.uint32(0x00008000)
387 DEFLIP_DATA = numpy.uint32(0x00010000)
394 DEFLIP_DATA = numpy.uint32(0x00010000)
388 DEFINE_PROCESS_CODE = numpy.uint32(0x00020000)
395 DEFINE_PROCESS_CODE = numpy.uint32(0x00020000)
389
396
390 ACQ_SYS_NATALIA = numpy.uint32(0x00040000)
397 ACQ_SYS_NATALIA = numpy.uint32(0x00040000)
391 ACQ_SYS_ECHOTEK = numpy.uint32(0x00080000)
398 ACQ_SYS_ECHOTEK = numpy.uint32(0x00080000)
392 ACQ_SYS_ADRXD = numpy.uint32(0x000C0000)
399 ACQ_SYS_ADRXD = numpy.uint32(0x000C0000)
393 ACQ_SYS_JULIA = numpy.uint32(0x00100000)
400 ACQ_SYS_JULIA = numpy.uint32(0x00100000)
394 ACQ_SYS_XXXXXX = numpy.uint32(0x00140000)
401 ACQ_SYS_XXXXXX = numpy.uint32(0x00140000)
395
402
396 EXP_NAME_ESP = numpy.uint32(0x00200000)
403 EXP_NAME_ESP = numpy.uint32(0x00200000)
397 CHANNEL_NAMES_ESP = numpy.uint32(0x00400000)
404 CHANNEL_NAMES_ESP = numpy.uint32(0x00400000)
398
405
399 OPERATION_MASK = numpy.uint32(0x0000003F)
406 OPERATION_MASK = numpy.uint32(0x0000003F)
400 DATATYPE_MASK = numpy.uint32(0x00000FC0)
407 DATATYPE_MASK = numpy.uint32(0x00000FC0)
401 DATAARRANGE_MASK = numpy.uint32(0x00007000)
408 DATAARRANGE_MASK = numpy.uint32(0x00007000)
402 ACQ_SYS_MASK = numpy.uint32(0x001C0000) No newline at end of file
409 ACQ_SYS_MASK = numpy.uint32(0x001C0000)
@@ -1,813 +1,821
1 '''
1 '''
2 File: SpectraIO.py
2 File: SpectraIO.py
3 Created on 20/02/2012
3 Created on 20/02/2012
4
4
5 @author $Author$
5 @author $Author$
6 @version $Id$
6 @version $Id$
7 '''
7 '''
8
8
9 import os, sys
9 import os, sys
10 import numpy
10 import numpy
11 import glob
11 import glob
12 import fnmatch
12 import fnmatch
13 import time, datetime
13 import time, datetime
14
14
15 path = os.path.split(os.getcwd())[0]
15 path = os.path.split(os.getcwd())[0]
16 sys.path.append(path)
16 sys.path.append(path)
17
17
18 from HeaderIO import *
18 from HeaderIO import *
19 from DataIO import DataReader
19 from DataIO import DataReader
20 from DataIO import DataWriter
20 from DataIO import DataWriter
21
21
22 from Model.Spectra import Spectra
22 from Model.Spectra import Spectra
23
23
24 def isThisFileinRange(filename, startUTSeconds, endUTSeconds):
24 def isThisFileinRange(filename, startUTSeconds, endUTSeconds):
25 """
25 """
26 Esta funcion determina si un archivo de datos en formato Jicamarca(.r) se encuentra
26 Esta funcion determina si un archivo de datos en formato Jicamarca(.r) se encuentra
27 o no dentro del rango de fecha especificado.
27 o no dentro del rango de fecha especificado.
28
28
29 Inputs:
29 Inputs:
30 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
30 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
31
31
32 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
32 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
33 segundos contados desde 01/01/1970.
33 segundos contados desde 01/01/1970.
34 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
34 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
35 segundos contados desde 01/01/1970.
35 segundos contados desde 01/01/1970.
36
36
37 Return:
37 Return:
38 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
38 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
39 fecha especificado, de lo contrario retorna False.
39 fecha especificado, de lo contrario retorna False.
40
40
41 Excepciones:
41 Excepciones:
42 Si el archivo no existe o no puede ser abierto
42 Si el archivo no existe o no puede ser abierto
43 Si la cabecera no puede ser leida.
43 Si la cabecera no puede ser leida.
44
44
45 """
45 """
46 m_BasicHeader = BasicHeader()
46 m_BasicHeader = BasicHeader()
47
47
48 try:
48 try:
49 fp = open(filename,'rb')
49 fp = open(filename,'rb')
50 except:
50 except:
51 raise IOError, "The file %s can't be opened" %(filename)
51 raise IOError, "The file %s can't be opened" %(filename)
52
52
53 if not(m_BasicHeader.read(fp)):
53 if not(m_BasicHeader.read(fp)):
54 raise IOError, "The file %s has not a valid header" %(filename)
54 raise IOError, "The file %s has not a valid header" %(filename)
55
55
56 fp.close()
56 fp.close()
57
57
58 if not ((startUTSeconds <= m_BasicHeader.utc) and (endUTSeconds >= m_BasicHeader.utc)):
58 if not ((startUTSeconds <= m_BasicHeader.utc) and (endUTSeconds >= m_BasicHeader.utc)):
59 return 0
59 return 0
60
60
61 return 1
61 return 1
62
62
63
63
64 class SpectraReader(DataReader):
64 class SpectraReader(DataReader):
65 """
65 """
66 Esta clase permite leer datos de espectros desde archivos procesados (.pdata). La lectura
66 Esta clase permite leer datos de espectros desde archivos procesados (.pdata). La lectura
67 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones:
67 de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones:
68 perfiless*alturas*canales) son almacenados en la variable "buffer".
68 perfiless*alturas*canales) son almacenados en la variable "buffer".
69
69
70 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
70 Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader,
71 RadarControllerHeader y Spectra. Los tres primeros se usan para almacenar informacion de la
71 RadarControllerHeader y Spectra. Los tres primeros se usan para almacenar informacion de la
72 cabecera de datos (metadata), y el cuarto (Spectra) para obtener y almacenar un bloque de
72 cabecera de datos (metadata), y el cuarto (Spectra) para obtener y almacenar un bloque de
73 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
73 datos desde el "buffer" cada vez que se ejecute el metodo "getData".
74
74
75 Example:
75 Example:
76
76
77 dpath = "/home/myuser/data"
77 dpath = "/home/myuser/data"
78
78
79 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
79 startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0)
80
80
81 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
81 endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0)
82
82
83 readerObj = SpectraReader()
83 readerObj = SpectraReader()
84
84
85 readerObj.setup(dpath, startTime, endTime)
85 readerObj.setup(dpath, startTime, endTime)
86
86
87 while(True):
87 while(True):
88
88
89 readerObj.getData()
89 readerObj.getData()
90
90
91 print readerObj.m_Spectra.data
91 print readerObj.m_Spectra.data
92
92
93 if readerObj.noMoreFiles:
93 if readerObj.noMoreFiles:
94 break
94 break
95
95
96 """
96 """
97
97
98 #speed of light
98 #speed of light
99 __c = 3E8
99 __c = 3E8
100
100
101 def __init__( self, m_Spectra = None ):
101 def __init__( self, m_Spectra = None ):
102 """
102 """
103 Inicializador de la clase SpectraReader para la lectura de datos de espectros.
103 Inicializador de la clase SpectraReader para la lectura de datos de espectros.
104
104
105 Input:
105 Input:
106 m_Spectra : Objeto de la clase Spectra. Este objeto sera utilizado para
106 m_Spectra : Objeto de la clase Spectra. Este objeto sera utilizado para
107 almacenar un perfil de datos cada vez que se haga un requerimiento
107 almacenar un perfil de datos cada vez que se haga un requerimiento
108 (getData). El perfil sera obtenido a partir del buffer de datos,
108 (getData). El perfil sera obtenido a partir del buffer de datos,
109 si el buffer esta vacio se hara un nuevo proceso de lectura de un
109 si el buffer esta vacio se hara un nuevo proceso de lectura de un
110 bloque de datos.
110 bloque de datos.
111 Si este parametro no es pasado se creara uno internamente.
111 Si este parametro no es pasado se creara uno internamente.
112
112
113 Variables afectadas:
113 Variables afectadas:
114 self.m_Spectra
114 self.m_Spectra
115 self.m_BasicHeader
115 self.m_BasicHeader
116 self.m_SystemHeader
116 self.m_SystemHeader
117 self.m_RadarControllerHeader
117 self.m_RadarControllerHeader
118 self.m_ProcessingHeader
118 self.m_ProcessingHeader
119
119
120
120
121 Return:
121 Return:
122 Void
122 Void
123
123
124 """
124 """
125 if m_Spectra == None:
125 if m_Spectra == None:
126 m_Spectra = Spectra()
126 m_Spectra = Spectra()
127
127
128 if not( isinstance(m_Spectra, Spectra) ):
128 if not( isinstance(m_Spectra, Spectra) ):
129 raise ValueError, "in SpectraReader, m_Spectra must be an Spectra class object"
129 raise ValueError, "in SpectraReader, m_Spectra must be an Spectra class object"
130
130
131 self.m_Spectra = m_Spectra
131 self.m_Spectra = m_Spectra
132
132
133 self.m_BasicHeader = BasicHeader()
133 self.m_BasicHeader = BasicHeader()
134
134
135 self.m_SystemHeader = SystemHeader()
135 self.m_SystemHeader = SystemHeader()
136
136
137 self.m_RadarControllerHeader = RadarControllerHeader()
137 self.m_RadarControllerHeader = RadarControllerHeader()
138
138
139 self.m_ProcessingHeader = ProcessingHeader()
139 self.m_ProcessingHeader = ProcessingHeader()
140
140
141 self.__fp = None
141 self.__fp = None
142
142
143 self.__idFile = None
143 self.__idFile = None
144
144
145 self.__startDateTime = None
145 self.__startDateTime = None
146
146
147 self.__endDateTime = None
147 self.__endDateTime = None
148
148
149 self.__dataType = None
149 self.__dataType = None
150
150
151 self.__fileSizeByHeader = 0
151 self.__fileSizeByHeader = 0
152
152
153 self.__pathList = []
153 self.__pathList = []
154
154
155 self.filenameList = []
155 self.filenameList = []
156
156
157 self.__lastUTTime = 0
157 self.__lastUTTime = 0
158
158
159 self.__maxTimeStep = 30
159 self.__maxTimeStep = 30
160
160
161 self.__flagIsNewFile = 0
161 self.__flagIsNewFile = 0
162
162
163 self.flagResetProcessing = 0
163 self.flagResetProcessing = 0
164
164
165 self.flagIsNewBlock = 0
165 self.flagIsNewBlock = 0
166
166
167 self.noMoreFiles = 0
167 self.noMoreFiles = 0
168
168
169 self.nReadBlocks = 0
169 self.nReadBlocks = 0
170
170
171 self.online = 0
171 self.online = 0
172
172
173 self.firstHeaderSize = 0
173 self.firstHeaderSize = 0
174
174
175 self.basicHeaderSize = 24
175 self.basicHeaderSize = 24
176
176
177 self.filename = None
177 self.filename = None
178
178
179 self.fileSize = None
179 self.fileSize = None
180
180
181 self.__buffer_spc = None
181 self.__buffer_spc = None
182 self.__buffer_cspc = None
182 self.__buffer_cspc = None
183 self.__buffer_dc = None
183 self.__buffer_dc = None
184
184
185 self.__buffer_id = 0
185 self.__buffer_id = 0
186
186
187 self.__ippSeconds = 0
187 self.__ippSeconds = 0
188
188
189 self.nSelfChannels = 0
189 self.nSelfChannels = 0
190
190
191 self.nCrossPairs = 0
191 self.nCrossPairs = 0
192
192
193 self.nChannels = 0
193 self.nChannels = 0
194
194
195 def __rdSystemHeader( self, fp=None ):
195 def __rdSystemHeader( self, fp=None ):
196 if fp == None:
196 if fp == None:
197 fp = self.__fp
197 fp = self.__fp
198
198
199 self.m_SystemHeader.read( fp )
199 self.m_SystemHeader.read( fp )
200
200
201 def __rdRadarControllerHeader( self, fp=None ):
201 def __rdRadarControllerHeader( self, fp=None ):
202 if fp == None:
202 if fp == None:
203 fp = self.__fp
203 fp = self.__fp
204
204
205 self.m_RadarControllerHeader.read(fp)
205 self.m_RadarControllerHeader.read(fp)
206
206
207 def __rdProcessingHeader( self,fp=None ):
207 def __rdProcessingHeader( self,fp=None ):
208 if fp == None:
208 if fp == None:
209 fp = self.__fp
209 fp = self.__fp
210
210
211 self.m_ProcessingHeader.read(fp)
211 self.m_ProcessingHeader.read(fp)
212
212
213 def __rdBasicHeader( self, fp=None ):
213 def __rdBasicHeader( self, fp=None ):
214 if fp == None:
214 if fp == None:
215 fp = self.__fp
215 fp = self.__fp
216
216
217 self.m_BasicHeader.read(fp)
217 self.m_BasicHeader.read(fp)
218
218
219 def __readFirstHeader( self ):
219 def __readFirstHeader( self ):
220 self.__rdBasicHeader()
220 self.__rdBasicHeader()
221 self.__rdSystemHeader()
221 self.__rdSystemHeader()
222 self.__rdRadarControllerHeader()
222 self.__rdRadarControllerHeader()
223 self.__rdProcessingHeader()
223 self.__rdProcessingHeader()
224 self.firstHeaderSize = self.m_BasicHeader.size
224 self.firstHeaderSize = self.m_BasicHeader.size
225
225
226 data_type = int( numpy.log2((self.m_ProcessingHeader.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR) )
226 data_type = int( numpy.log2((self.m_ProcessingHeader.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR) )
227 if data_type == 0:
227 if data_type == 0:
228 tmp = numpy.dtype([('real','<i1'),('imag','<i1')])
228 tmp = numpy.dtype([('real','<i1'),('imag','<i1')])
229
229
230 elif data_type == 1:
230 elif data_type == 1:
231 tmp = numpy.dtype([('real','<i2'),('imag','<i2')])
231 tmp = numpy.dtype([('real','<i2'),('imag','<i2')])
232
232
233 elif data_type == 2:
233 elif data_type == 2:
234 tmp = numpy.dtype([('real','<i4'),('imag','<i4')])
234 tmp = numpy.dtype([('real','<i4'),('imag','<i4')])
235
235
236 elif data_type == 3:
236 elif data_type == 3:
237 tmp = numpy.dtype([('real','<i8'),('imag','<i8')])
237 tmp = numpy.dtype([('real','<i8'),('imag','<i8')])
238
238
239 elif data_type == 4:
239 elif data_type == 4:
240 tmp = numpy.dtype([('real','<f4'),('imag','<f4')])
240 tmp = numpy.dtype([('real','<f4'),('imag','<f4')])
241
241
242 elif data_type == 5:
242 elif data_type == 5:
243 tmp = numpy.dtype([('real','<f8'),('imag','<f8')])
243 tmp = numpy.dtype([('real','<f8'),('imag','<f8')])
244
244
245 else:
245 else:
246 raise ValueError, 'Data type was not defined'
246 raise ValueError, 'Data type was not defined'
247
247
248 xi = self.m_ProcessingHeader.firstHeight
248 xi = self.m_ProcessingHeader.firstHeight
249 step = self.m_ProcessingHeader.deltaHeight
249 step = self.m_ProcessingHeader.deltaHeight
250 xf = xi + self.m_ProcessingHeader.numHeights*step
250 xf = xi + self.m_ProcessingHeader.numHeights*step
251
251
252 self.__heights = numpy.arange(xi, xf, step)
252 self.__heights = numpy.arange(xi, xf, step)
253 self.__dataType = tmp
253 self.__dataType = tmp
254 self.__fileSizeByHeader = self.m_ProcessingHeader.dataBlocksPerFile * self.m_ProcessingHeader.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.m_ProcessingHeader.dataBlocksPerFile - 1)
254 self.__fileSizeByHeader = self.m_ProcessingHeader.dataBlocksPerFile * self.m_ProcessingHeader.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.m_ProcessingHeader.dataBlocksPerFile - 1)
255 self.__ippSeconds = 2 * 1000 * self.m_RadarControllerHeader.ipp/self.__c
255 self.__ippSeconds = 2 * 1000 * self.m_RadarControllerHeader.ipp/self.__c
256
256
257 def __setNextFileOnline( self ):
257 def __setNextFileOnline( self ):
258 return 1
258 return 1
259
259
260 def __setNextFileOffline( self ):
260 def __setNextFileOffline( self ):
261 idFile = self.__idFile
261 idFile = self.__idFile
262
262
263 while(True):
263 while(True):
264 idFile += 1
264 idFile += 1
265
265
266 if not( idFile < len(self.filenameList) ):
266 if not( idFile < len(self.filenameList) ):
267 self.noMoreFiles = 1
267 self.noMoreFiles = 1
268 return 0
268 return 0
269
269
270 filename = self.filenameList[idFile]
270 filename = self.filenameList[idFile]
271 fileSize = os.path.getsize(filename)
271 fileSize = os.path.getsize(filename)
272
272
273 try:
273 try:
274 fp = open( filename, 'rb' )
274 fp = open( filename, 'rb' )
275 except:
275 except:
276 raise IOError, "The file %s can't be opened" %filename
276 raise IOError, "The file %s can't be opened" %filename
277
277
278 currentSize = fileSize - fp.tell()
278 currentSize = fileSize - fp.tell()
279 neededSize = self.m_ProcessingHeader.blockSize + self.firstHeaderSize
279 neededSize = self.m_ProcessingHeader.blockSize + self.firstHeaderSize
280
280
281 if (currentSize < neededSize):
281 if (currentSize < neededSize):
282 print "Skipping the file %s due to it hasn't enough data" %filename
282 print "Skipping the file %s due to it hasn't enough data" %filename
283 continue
283 continue
284
284
285 break
285 break
286
286
287 self.__flagIsNewFile = 1
287 self.__flagIsNewFile = 1
288 self.__idFile = idFile
288 self.__idFile = idFile
289 self.filename = filename
289 self.filename = filename
290 self.fileSize = fileSize
290 self.fileSize = fileSize
291 self.__fp = fp
291 self.__fp = fp
292
292
293 print 'Setting the file: %s'%self.filename
293 print 'Setting the file: %s'%self.filename
294
294
295 return 1
295 return 1
296
296
297 def __setNextFile(self):
297 def __setNextFile(self):
298 if self.online:
298 if self.online:
299 newFile = self.__setNextFileOnline()
299 newFile = self.__setNextFileOnline()
300 else:
300 else:
301 newFile = self.__setNextFileOffline()
301 newFile = self.__setNextFileOffline()
302
302
303 if not(newFile):
303 if not(newFile):
304 return 0
304 return 0
305
305
306 self.__readFirstHeader()
306 self.__readFirstHeader()
307
307
308 return 1
308 return 1
309
309
310 def __setNewBlock( self ):
310 def __setNewBlock( self ):
311 if self.__fp == None:
311 if self.__fp == None:
312 return 0
312 return 0
313
313
314 if self.__flagIsNewFile:
314 if self.__flagIsNewFile:
315 return 1
315 return 1
316
316
317 currentSize = self.fileSize - self.__fp.tell()
317 currentSize = self.fileSize - self.__fp.tell()
318 neededSize = self.m_ProcessingHeader.blockSize + self.basicHeaderSize
318 neededSize = self.m_ProcessingHeader.blockSize + self.basicHeaderSize
319
319
320 #If there is enough data setting new data block
320 #If there is enough data setting new data block
321 if ( currentSize >= neededSize ):
321 if ( currentSize >= neededSize ):
322 self.__rdBasicHeader()
322 self.__rdBasicHeader()
323 return 1
323 return 1
324
324
325 #Setting new file
325 #Setting new file
326 if not( self.__setNextFile() ):
326 if not( self.__setNextFile() ):
327 return 0
327 return 0
328
328
329 deltaTime = self.m_BasicHeader.utc - self.__lastUTTime # check this
329 deltaTime = self.m_BasicHeader.utc - self.__lastUTTime # check this
330
330
331 self.flagResetProcessing = 0
331 self.flagResetProcessing = 0
332
332
333 if deltaTime > self.__maxTimeStep:
333 if deltaTime > self.__maxTimeStep:
334 self.flagResetProcessing = 1
334 self.flagResetProcessing = 1
335 self.ns = 0
335 self.ns = 0
336
336
337 return 1
337 return 1
338
338
339
339
340
340
341 def __readBlock(self):
341 def __readBlock(self):
342 """
342 """
343 __readBlock lee el bloque de datos desde la posicion actual del puntero del archivo
343 __readBlock lee el bloque de datos desde la posicion actual del puntero del archivo
344 (self.__fp) y actualiza todos los parametros relacionados al bloque de datos
344 (self.__fp) y actualiza todos los parametros relacionados al bloque de datos
345 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
345 (metadata + data). La data leida es almacenada en el buffer y el contador del buffer
346 es seteado a 0
346 es seteado a 0
347
347
348 Inputs:
348 Inputs:
349 None
349 None
350
350
351 Return:
351 Return:
352 None
352 None
353
353
354 Variables afectadas:
354 Variables afectadas:
355
355
356 self.__buffer_id
356 self.__buffer_id
357
357
358 self.__buffer_sspc
358 self.__buffer_sspc
359
359
360 self.__flagIsNewFile
360 self.__flagIsNewFile
361
361
362 self.flagIsNewBlock
362 self.flagIsNewBlock
363
363
364 self.nReadBlocks
364 self.nReadBlocks
365
365
366 """
366 """
367 Npair_SelfSpectra = 0
367 Npair_SelfSpectra = 0
368 Npair_CrossSpectra = 0
368 Npair_CrossSpectra = 0
369
369
370 for i in range( 0,self.m_ProcessingHeader.totalSpectra*2,2 ):
370 for i in range( 0,self.m_ProcessingHeader.totalSpectra*2,2 ):
371 if self.m_ProcessingHeader.spectraComb[i] == self.m_ProcessingHeader.spectraComb[i+1]:
371 if self.m_ProcessingHeader.spectraComb[i] == self.m_ProcessingHeader.spectraComb[i+1]:
372 Npair_SelfSpectra = Npair_SelfSpectra + 1
372 Npair_SelfSpectra = Npair_SelfSpectra + 1
373 else:
373 else:
374 Npair_CrossSpectra = Npair_CrossSpectra + 1
374 Npair_CrossSpectra = Npair_CrossSpectra + 1
375
375
376 # self.__buffer_sspc = numpy.concatenate( (data_sspc,data_cspc,data_dcc), axis=0 )
376 # self.__buffer_sspc = numpy.concatenate( (data_sspc,data_cspc,data_dcc), axis=0 )
377
377
378 self.__buffer_id = 0
378 self.__buffer_id = 0
379 self.__flagIsNewFile = 0
379 self.__flagIsNewFile = 0
380 self.flagIsNewBlock = 1
380 self.flagIsNewBlock = 1
381
381
382 pts2read = self.m_ProcessingHeader.profilesPerBlock*self.m_ProcessingHeader.numHeights
382 pts2read = self.m_ProcessingHeader.profilesPerBlock*self.m_ProcessingHeader.numHeights
383
383
384 spc = numpy.fromfile(self.__fp, self.__dataType[0], int(pts2read*Npair_SelfSpectra))
384 spc = numpy.fromfile(self.__fp, self.__dataType[0], int(pts2read*Npair_SelfSpectra))
385 cspc = numpy.fromfile(self.__fp, self.__dataType, int(pts2read*Npair_CrossSpectra))
385 cspc = numpy.fromfile(self.__fp, self.__dataType, int(pts2read*Npair_CrossSpectra))
386 dc = numpy.fromfile(self.__fp, self.__dataType, int(self.m_ProcessingHeader.numHeights*self.m_SystemHeader.numChannels) )
386 dc = numpy.fromfile(self.__fp, self.__dataType, int(self.m_ProcessingHeader.numHeights*self.m_SystemHeader.numChannels) )
387
387
388 spc = spc.reshape((self.m_ProcessingHeader.profilesPerBlock, self.m_ProcessingHeader.numHeights, Npair_SelfSpectra))
388 spc = spc.reshape((Npair_SelfSpectra, self.m_ProcessingHeader.numHeights, self.m_ProcessingHeader.profilesPerBlock))
389 cspc = cspc.reshape((self.m_ProcessingHeader.profilesPerBlock, self.m_ProcessingHeader.numHeights, Npair_CrossSpectra))
389 cspc = cspc.reshape((Npair_CrossSpectra, self.m_ProcessingHeader.numHeights, self.m_ProcessingHeader.profilesPerBlock))
390 dc = dc.reshape((self.m_ProcessingHeader.numHeights, self.m_SystemHeader.numChannels))
390 dc = dc.reshape((self.m_SystemHeader.numChannels, self.m_ProcessingHeader.numHeights))
391
392 if not(self.m_ProcessingHeader.shif_fft):
393 spc = numpy.roll(spc, self.m_ProcessingHeader.profilesPerBlock/2, axis=2)
394 cspc = numpy.roll(cspc, self.m_ProcessingHeader.profilesPerBlock/2, axis=2)
395
396 spc = numpy.transpose(spc, (0,2,1))
397 cspc = numpy.transpose(cspc, (0,2,1))
398 #dc = numpy.transpose(dc, (0,2,1))
391
399
392 data_spc = spc
400 data_spc = spc
393 data_cspc = cspc['real'] + cspc['imag']*1j
401 data_cspc = cspc['real'] + cspc['imag']*1j
394 data_dc = dc['real'] + dc['imag']*1j
402 data_dc = dc['real'] + dc['imag']*1j
395
403
396 self.__buffer_spc = data_spc
404 self.__buffer_spc = data_spc
397 self.__buffer_cspc = data_cspc
405 self.__buffer_cspc = data_cspc
398 self.__buffer_dc = data_dc
406 self.__buffer_dc = data_dc
399
407
400 self.__flagIsNewFile = 0
408 self.__flagIsNewFile = 0
401
409
402 self.flagIsNewBlock = 1
410 self.flagIsNewBlock = 1
403
411
404 self.nReadBlocks += 1
412 self.nReadBlocks += 1
405
413
406
414
407 def __hasNotDataInBuffer(self):
415 def __hasNotDataInBuffer(self):
408 return 1
416 return 1
409
417
410 def __searchFiles(self, path, startDateTime, endDateTime, set=None, expLabel = "", ext = ".pdata"):
418 def __searchFiles(self, path, startDateTime, endDateTime, set=None, expLabel = "", ext = ".pdata"):
411 """
419 """
412 __searchFiles realiza una busqueda de los archivos que coincidan con los parametros
420 __searchFiles realiza una busqueda de los archivos que coincidan con los parametros
413 especificados y se encuentren ubicados en el path indicado. Para realizar una busqueda
421 especificados y se encuentren ubicados en el path indicado. Para realizar una busqueda
414 correcta la estructura de directorios debe ser la siguiente:
422 correcta la estructura de directorios debe ser la siguiente:
415
423
416 ...path/D[yyyy][ddd]/expLabel/D[yyyy][ddd][sss].ext
424 ...path/D[yyyy][ddd]/expLabel/D[yyyy][ddd][sss].ext
417
425
418 [yyyy]: anio
426 [yyyy]: anio
419 [ddd] : dia del anio
427 [ddd] : dia del anio
420 [sss] : set del archivo
428 [sss] : set del archivo
421
429
422 Inputs:
430 Inputs:
423 path : Directorio de datos donde se realizara la busqueda. Todos los
431 path : Directorio de datos donde se realizara la busqueda. Todos los
424 ficheros que concidan con el criterio de busqueda seran
432 ficheros que concidan con el criterio de busqueda seran
425 almacenados en una lista y luego retornados.
433 almacenados en una lista y luego retornados.
426 startDateTime : Fecha inicial. Rechaza todos los archivos donde
434 startDateTime : Fecha inicial. Rechaza todos los archivos donde
427 file end time < startDateTime (objeto datetime.datetime)
435 file end time < startDateTime (objeto datetime.datetime)
428
436
429 endDateTime : Fecha final. Rechaza todos los archivos donde
437 endDateTime : Fecha final. Rechaza todos los archivos donde
430 file start time > endDateTime (obejto datetime.datetime)
438 file start time > endDateTime (obejto datetime.datetime)
431
439
432 set : Set del primer archivo a leer. Por defecto None
440 set : Set del primer archivo a leer. Por defecto None
433
441
434 expLabel : Nombre del subdirectorio de datos. Por defecto ""
442 expLabel : Nombre del subdirectorio de datos. Por defecto ""
435
443
436 ext : Extension de los archivos a leer. Por defecto .r
444 ext : Extension de los archivos a leer. Por defecto .r
437
445
438 Return:
446 Return:
439
447
440 (pathList, filenameList)
448 (pathList, filenameList)
441
449
442 pathList : Lista de directorios donde se encontraron archivos dentro
450 pathList : Lista de directorios donde se encontraron archivos dentro
443 de los parametros especificados
451 de los parametros especificados
444 filenameList : Lista de archivos (ruta completa) que coincidieron con los
452 filenameList : Lista de archivos (ruta completa) que coincidieron con los
445 parametros especificados.
453 parametros especificados.
446
454
447 Variables afectadas:
455 Variables afectadas:
448
456
449 self.filenameList: Lista de archivos (ruta completa) que la clase utiliza
457 self.filenameList: Lista de archivos (ruta completa) que la clase utiliza
450 como fuente para leer los bloque de datos, si se termina
458 como fuente para leer los bloque de datos, si se termina
451 de leer todos los bloques de datos de un determinado
459 de leer todos los bloques de datos de un determinado
452 archivo se pasa al siguiente archivo de la lista.
460 archivo se pasa al siguiente archivo de la lista.
453
461
454 Excepciones:
462 Excepciones:
455
463
456 """
464 """
457
465
458 print "Searching files ..."
466 print "Searching files ..."
459
467
460 dirList = []
468 dirList = []
461 for thisPath in os.listdir(path):
469 for thisPath in os.listdir(path):
462 if os.path.isdir(os.path.join(path,thisPath)):
470 if os.path.isdir(os.path.join(path,thisPath)):
463 dirList.append(thisPath)
471 dirList.append(thisPath)
464
472
465 pathList = []
473 pathList = []
466
474
467 thisDateTime = startDateTime
475 thisDateTime = startDateTime
468
476
469 while(thisDateTime <= endDateTime):
477 while(thisDateTime <= endDateTime):
470 year = thisDateTime.timetuple().tm_year
478 year = thisDateTime.timetuple().tm_year
471 doy = thisDateTime.timetuple().tm_yday
479 doy = thisDateTime.timetuple().tm_yday
472
480
473 match = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy))
481 match = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy))
474 if len(match) == 0:
482 if len(match) == 0:
475 thisDateTime += datetime.timedelta(1)
483 thisDateTime += datetime.timedelta(1)
476 continue
484 continue
477
485
478 pathList.append(os.path.join(path,match[0],expLabel))
486 pathList.append(os.path.join(path,match[0],expLabel))
479 thisDateTime += datetime.timedelta(1)
487 thisDateTime += datetime.timedelta(1)
480
488
481 startUtSeconds = time.mktime(startDateTime.timetuple())
489 startUtSeconds = time.mktime(startDateTime.timetuple())
482 endUtSeconds = time.mktime(endDateTime.timetuple())
490 endUtSeconds = time.mktime(endDateTime.timetuple())
483
491
484 filenameList = []
492 filenameList = []
485 for thisPath in pathList:
493 for thisPath in pathList:
486 fileList = glob.glob1(thisPath, "*%s" %ext)
494 fileList = glob.glob1(thisPath, "*%s" %ext)
487 fileList.sort()
495 fileList.sort()
488 for file in fileList:
496 for file in fileList:
489 filename = os.path.join(thisPath,file)
497 filename = os.path.join(thisPath,file)
490 if isThisFileinRange(filename, startUtSeconds, endUtSeconds):
498 if isThisFileinRange(filename, startUtSeconds, endUtSeconds):
491 filenameList.append(filename)
499 filenameList.append(filename)
492
500
493 self.filenameList = filenameList
501 self.filenameList = filenameList
494
502
495 return pathList, filenameList
503 return pathList, filenameList
496
504
497
505
498 def setup( self, path, startDateTime, endDateTime=None, set=None, expLabel = "", ext = ".pdata", online = 0 ):
506 def setup( self, path, startDateTime, endDateTime=None, set=None, expLabel = "", ext = ".pdata", online = 0 ):
499 """
507 """
500 setup configura los parametros de lectura de la clase SpectraReader.
508 setup configura los parametros de lectura de la clase SpectraReader.
501
509
502 Si el modo de lectura es offline, primero se realiza una busqueda de todos los archivos
510 Si el modo de lectura es offline, primero se realiza una busqueda de todos los archivos
503 que coincidan con los parametros especificados; esta lista de archivos son almacenados en
511 que coincidan con los parametros especificados; esta lista de archivos son almacenados en
504 self.filenameList.
512 self.filenameList.
505
513
506 Input:
514 Input:
507 path : Directorios donde se ubican los datos a leer. Dentro de este
515 path : Directorios donde se ubican los datos a leer. Dentro de este
508 directorio deberia de estar subdirectorios de la forma:
516 directorio deberia de estar subdirectorios de la forma:
509
517
510 path/D[yyyy][ddd]/expLabel/P[yyyy][ddd][sss][ext]
518 path/D[yyyy][ddd]/expLabel/P[yyyy][ddd][sss][ext]
511
519
512 startDateTime : Fecha inicial. Rechaza todos los archivos donde
520 startDateTime : Fecha inicial. Rechaza todos los archivos donde
513 file end time < startDatetime (objeto datetime.datetime)
521 file end time < startDatetime (objeto datetime.datetime)
514
522
515 endDateTime : Fecha final. Si no es None, rechaza todos los archivos donde
523 endDateTime : Fecha final. Si no es None, rechaza todos los archivos donde
516 file end time < startDatetime (objeto datetime.datetime)
524 file end time < startDatetime (objeto datetime.datetime)
517
525
518 set : Set del primer archivo a leer. Por defecto None
526 set : Set del primer archivo a leer. Por defecto None
519
527
520 expLabel : Nombre del subdirectorio de datos. Por defecto ""
528 expLabel : Nombre del subdirectorio de datos. Por defecto ""
521
529
522 ext : Extension de los archivos a leer. Por defecto .r
530 ext : Extension de los archivos a leer. Por defecto .r
523
531
524 online :
532 online :
525
533
526 Return:
534 Return:
527
535
528 Affected:
536 Affected:
529
537
530 Excepciones:
538 Excepciones:
531
539
532 Example:
540 Example:
533
541
534 """
542 """
535 if online == 0:
543 if online == 0:
536 pathList, filenameList = self.__searchFiles(path, startDateTime, endDateTime, set, expLabel, ext)
544 pathList, filenameList = self.__searchFiles(path, startDateTime, endDateTime, set, expLabel, ext)
537
545
538 self.__idFile = -1
546 self.__idFile = -1
539
547
540 if not(self.__setNextFile()):
548 if not(self.__setNextFile()):
541 print "No files in range: %s - %s" %(startDateTime.ctime(), endDateTime.ctime())
549 print "No files in range: %s - %s" %(startDateTime.ctime(), endDateTime.ctime())
542 return 0
550 return 0
543
551
544 self.startUTCSeconds = time.mktime(startDateTime.timetuple())
552 self.startUTCSeconds = time.mktime(startDateTime.timetuple())
545 self.endUTCSeconds = time.mktime(endDateTime.timetuple())
553 self.endUTCSeconds = time.mktime(endDateTime.timetuple())
546
554
547 self.startYear = startDateTime.timetuple().tm_year
555 self.startYear = startDateTime.timetuple().tm_year
548 self.endYear = endDateTime.timetuple().tm_year
556 self.endYear = endDateTime.timetuple().tm_year
549
557
550 self.startDoy = startDateTime.timetuple().tm_yday
558 self.startDoy = startDateTime.timetuple().tm_yday
551 self.endDoy = endDateTime.timetuple().tm_yday
559 self.endDoy = endDateTime.timetuple().tm_yday
552 #call fillHeaderValues() - to Data Object
560 #call fillHeaderValues() - to Data Object
553
561
554 self.__pathList = pathList
562 self.__pathList = pathList
555 self.filenameList = filenameList
563 self.filenameList = filenameList
556 self.online = online
564 self.online = online
557
565
558 return 1
566 return 1
559
567
560 def readNextBlock(self):
568 def readNextBlock(self):
561 """
569 """
562 readNextBlock establece un nuevo bloque de datos a leer y los lee, si es que no existiese
570 readNextBlock establece un nuevo bloque de datos a leer y los lee, si es que no existiese
563 mas bloques disponibles en el archivo actual salta al siguiente.
571 mas bloques disponibles en el archivo actual salta al siguiente.
564
572
565 """
573 """
566
574
567 if not( self.__setNewBlock() ):
575 if not( self.__setNewBlock() ):
568 return 0
576 return 0
569
577
570 self.__readBlock()
578 self.__readBlock()
571
579
572 self.__lastUTTime = self.m_BasicHeader.utc
580 self.__lastUTTime = self.m_BasicHeader.utc
573
581
574 return 1
582 return 1
575
583
576
584
577 def getData(self):
585 def getData(self):
578 """
586 """
579 getData copia el buffer de lectura a la clase "Spectra",
587 getData copia el buffer de lectura a la clase "Spectra",
580 con todos los parametros asociados a este (metadata). cuando no hay datos en el buffer de
588 con todos los parametros asociados a este (metadata). cuando no hay datos en el buffer de
581 lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock"
589 lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock"
582
590
583 Inputs:
591 Inputs:
584 None
592 None
585
593
586 Return:
594 Return:
587 data : retorna un bloque de datos (nFFTs * alturas * canales) copiados desde el
595 data : retorna un bloque de datos (nFFTs * alturas * canales) copiados desde el
588 buffer. Si no hay mas archivos a leer retorna None.
596 buffer. Si no hay mas archivos a leer retorna None.
589
597
590 Variables afectadas:
598 Variables afectadas:
591 self.m_Spectra
599 self.m_Spectra
592 self.__buffer_id
600 self.__buffer_id
593
601
594 Excepciones:
602 Excepciones:
595
603
596 """
604 """
597
605
598 self.flagResetProcessing = 0
606 self.flagResetProcessing = 0
599 self.flagIsNewBlock = 0
607 self.flagIsNewBlock = 0
600
608
601 if self.__hasNotDataInBuffer():
609 if self.__hasNotDataInBuffer():
602 self.readNextBlock()
610 self.readNextBlock()
603
611
604 self.m_Spectra.m_BasicHeader = self.m_BasicHeader.copy()
612 self.m_Spectra.m_BasicHeader = self.m_BasicHeader.copy()
605 self.m_Spectra.m_ProcessingHeader = self.m_ProcessingHeader.copy()
613 self.m_Spectra.m_ProcessingHeader = self.m_ProcessingHeader.copy()
606 self.m_Spectra.m_RadarControllerHeader = self.m_RadarControllerHeader.copy()
614 self.m_Spectra.m_RadarControllerHeader = self.m_RadarControllerHeader.copy()
607 self.m_Spectra.m_SystemHeader = self.m_SystemHeader.copy()
615 self.m_Spectra.m_SystemHeader = self.m_SystemHeader.copy()
608 self.m_Spectra.heights = self.__heights
616 self.m_Spectra.heights = self.__heights
609 self.m_Spectra.dataType = self.__dataType
617 self.m_Spectra.dataType = self.__dataType
610
618
611 if self.noMoreFiles == 1:
619 if self.noMoreFiles == 1:
612 print 'Process finished'
620 print 'Process finished'
613 return 0
621 return 0
614
622
615 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
623 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
616 #print type(self.__buffer_sspc)
624 #print type(self.__buffer_sspc)
617
625
618 time = self.m_BasicHeader.utc + self.__buffer_id*self.__ippSeconds
626 time = self.m_BasicHeader.utc + self.__buffer_id*self.__ippSeconds
619
627
620 self.m_Spectra.m_BasicHeader.utc = time
628 self.m_Spectra.m_BasicHeader.utc = time
621 self.m_Spectra.data_spc = self.__buffer_spc
629 self.m_Spectra.data_spc = self.__buffer_spc
622 self.m_Spectra.data_cspc = self.__buffer_cspc
630 self.m_Spectra.data_cspc = self.__buffer_cspc
623 self.m_Spectra.data_dc = self.__buffer_dc
631 self.m_Spectra.data_dc = self.__buffer_dc
624
632
625 #call setData - to Data Object
633 #call setData - to Data Object
626
634
627 return 1
635 return 1
628
636
629
637
630 class SpectraWriter(DataWriter):
638 class SpectraWriter(DataWriter):
631
639
632 def __init__(self):
640 def __init__(self):
633 if m_Spectra == None:
641 if m_Spectra == None:
634 m_Spectra = Spectra()
642 m_Spectra = Spectra()
635
643
636 self.m_Spectra = m_Spectra
644 self.m_Spectra = m_Spectra
637
645
638 self.__fp = None
646 self.__fp = None
639
647
640 self.__blocksCounter = 0
648 self.__blocksCounter = 0
641
649
642 self.__setFile = None
650 self.__setFile = None
643
651
644 self.__flagIsNewFile = 0
652 self.__flagIsNewFile = 0
645
653
646 self.__buffer_sspc = 0
654 self.__buffer_sspc = 0
647
655
648 self.__buffer_id = 0
656 self.__buffer_id = 0
649
657
650 self.__dataType = None
658 self.__dataType = None
651
659
652 self.__ext = None
660 self.__ext = None
653
661
654 self.nWriteBlocks = 0
662 self.nWriteBlocks = 0
655
663
656 self.flagIsNewBlock = 0
664 self.flagIsNewBlock = 0
657
665
658 self.noMoreFiles = 0
666 self.noMoreFiles = 0
659
667
660 self.filename = None
668 self.filename = None
661
669
662 self.m_BasicHeader= BasicHeader()
670 self.m_BasicHeader= BasicHeader()
663
671
664 self.m_SystemHeader = SystemHeader()
672 self.m_SystemHeader = SystemHeader()
665
673
666 self.m_RadarControllerHeader = RadarControllerHeader()
674 self.m_RadarControllerHeader = RadarControllerHeader()
667
675
668 self.m_ProcessingHeader = ProcessingHeader()
676 self.m_ProcessingHeader = ProcessingHeader()
669
677
670 def __setNextFile(self):
678 def __setNextFile(self):
671 setFile = self.__setFile
679 setFile = self.__setFile
672 ext = self.__ext
680 ext = self.__ext
673 path = self.__path
681 path = self.__path
674
682
675 setFile += 1
683 setFile += 1
676
684
677 if not(self.__blocksCounter >= self.m_ProcessingHeader.dataBlocksPerFile):
685 if not(self.__blocksCounter >= self.m_ProcessingHeader.dataBlocksPerFile):
678 self.__fp.close()
686 self.__fp.close()
679 return 0
687 return 0
680
688
681 timeTuple = time.localtime(self.m_Spectra.m_BasicHeader.utc) # utc from m_Spectra
689 timeTuple = time.localtime(self.m_Spectra.m_BasicHeader.utc) # utc from m_Spectra
682 file = 'D%4.4d%3.3d%3.3d%s' % (timeTuple.tm_year,timeTuple.tm_doy,setFile,ext)
690 file = 'D%4.4d%3.3d%3.3d%s' % (timeTuple.tm_year,timeTuple.tm_doy,setFile,ext)
683 subfolder = 'D%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_doy)
691 subfolder = 'D%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_doy)
684 tmp = os.path.join(path,subfolder)
692 tmp = os.path.join(path,subfolder)
685 if not(os.path.exists(tmp)):
693 if not(os.path.exists(tmp)):
686 os.mkdir(tmp)
694 os.mkdir(tmp)
687
695
688 filename = os.path.join(path,subfolder,file)
696 filename = os.path.join(path,subfolder,file)
689 fp = open(filename,'wb')
697 fp = open(filename,'wb')
690
698
691 #guardando atributos
699 #guardando atributos
692 self.filename = filename
700 self.filename = filename
693 self.__subfolder = subfolder
701 self.__subfolder = subfolder
694 self.__fp = fp
702 self.__fp = fp
695 self.__setFile = setFile
703 self.__setFile = setFile
696 self.__flagIsNewFile = 1
704 self.__flagIsNewFile = 1
697
705
698 print 'Writing the file: %s'%self.filename
706 print 'Writing the file: %s'%self.filename
699
707
700 return 1
708 return 1
701
709
702
710
703
711
704 def __setNewBlock(self):
712 def __setNewBlock(self):
705 if self.__fp == None:
713 if self.__fp == None:
706 return 0
714 return 0
707
715
708 if self.__flagIsNewFile:
716 if self.__flagIsNewFile:
709 return 1
717 return 1
710
718
711 #Bloques completados?
719 #Bloques completados?
712 if self.__blocksCounter < self.m_ProcessingHeader.profilesPerBlock:
720 if self.__blocksCounter < self.m_ProcessingHeader.profilesPerBlock:
713 self.__writeBasicHeader()
721 self.__writeBasicHeader()
714 return 1
722 return 1
715
723
716 if not(self.__setNextFile()):
724 if not(self.__setNextFile()):
717 return 0
725 return 0
718
726
719 self.__writeFirstHeader()
727 self.__writeFirstHeader()
720
728
721 return 1
729 return 1
722
730
723 def __writeBlock(self):
731 def __writeBlock(self):
724
732
725 numpy.save(self.__fp,self.__buffer_sspc)
733 numpy.save(self.__fp,self.__buffer_sspc)
726
734
727 self.__buffer_sspc = numpy.array([],self.__dataType)
735 self.__buffer_sspc = numpy.array([],self.__dataType)
728
736
729 self.__buffer_id = 0
737 self.__buffer_id = 0
730
738
731 self.__flagIsNewFile = 0
739 self.__flagIsNewFile = 0
732
740
733 self.flagIsNewBlock = 1
741 self.flagIsNewBlock = 1
734
742
735 self.nWriteBlocks += 1
743 self.nWriteBlocks += 1
736
744
737 self.__blocksCounter += 1
745 self.__blocksCounter += 1
738
746
739 def writeNextBlock(self):
747 def writeNextBlock(self):
740 if not(self.__setNewBlock()):
748 if not(self.__setNewBlock()):
741 return 0
749 return 0
742
750
743 self.__writeBlock()
751 self.__writeBlock()
744
752
745 return 1
753 return 1
746
754
747 def __hasAllDataInBuffer(self):
755 def __hasAllDataInBuffer(self):
748 if self.__buffer_id >= self.m_ProcessingHeader.profilesPerBlock:
756 if self.__buffer_id >= self.m_ProcessingHeader.profilesPerBlock:
749 return 1
757 return 1
750
758
751 return 0
759 return 0
752
760
753 def putData(self):
761 def putData(self):
754 self.flagIsNewBlock = 0
762 self.flagIsNewBlock = 0
755
763
756 if self.m_Spectra.noData:
764 if self.m_Spectra.noData:
757 return None
765 return None
758
766
759 shape = self.m_Spectra.data.shape
767 shape = self.m_Spectra.data.shape
760 data = numpy.zeros(shape,self.__dataType)
768 data = numpy.zeros(shape,self.__dataType)
761 data['real'] = self.m_Spectra.data.real
769 data['real'] = self.m_Spectra.data.real
762 data['imag'] = self.m_Spectra.data.imag
770 data['imag'] = self.m_Spectra.data.imag
763 data = data.reshape((-1))
771 data = data.reshape((-1))
764
772
765 self.__buffer_sspc = numpy.hstack((self.__buffer_sspc,data))
773 self.__buffer_sspc = numpy.hstack((self.__buffer_sspc,data))
766
774
767 self.__buffer_id += 1
775 self.__buffer_id += 1
768
776
769 if __hasAllDataInBuffer():
777 if __hasAllDataInBuffer():
770 self.writeNextBlock()
778 self.writeNextBlock()
771
779
772
780
773 if self.noMoreFiles:
781 if self.noMoreFiles:
774 print 'Process finished'
782 print 'Process finished'
775 return None
783 return None
776
784
777 return 1
785 return 1
778
786
779
787
780 def setup(self,path,set=None,format=None):
788 def setup(self,path,set=None,format=None):
781
789
782 if set == None:
790 if set == None:
783 set = -1
791 set = -1
784 else:
792 else:
785 set -= 1
793 set -= 1
786
794
787 if format == 'hdf5':
795 if format == 'hdf5':
788 ext = '.hdf5'
796 ext = '.hdf5'
789 print 'call hdf5 library'
797 print 'call hdf5 library'
790 return 0
798 return 0
791
799
792 if format == 'rawdata':
800 if format == 'rawdata':
793 ext = '.r'
801 ext = '.r'
794
802
795 #call to config_headers
803 #call to config_headers
796
804
797 self.__setFile = set
805 self.__setFile = set
798
806
799 if not(self.__setNextFile()):
807 if not(self.__setNextFile()):
800 print "zzzzzzzzzzzz"
808 print "zzzzzzzzzzzz"
801 return 0
809 return 0
802
810
803 self.__writeFirstHeader() # dentro de esta funcion se debe setear e __dataType
811 self.__writeFirstHeader() # dentro de esta funcion se debe setear e __dataType
804
812
805 self.__buffer_sspc = numpy.array([],self.__dataType)
813 self.__buffer_sspc = numpy.array([],self.__dataType)
806
814
807
815
808
816
809 def __writeBasicHeader(self):
817 def __writeBasicHeader(self):
810 pass
818 pass
811
819
812 def __writeFirstHeader(self):
820 def __writeFirstHeader(self):
813 pass
821 pass
@@ -1,67 +1,71
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 os, sys
7 import os, sys
8
8
9 path = os.path.split(os.getcwd())[0]
9 path = os.path.split(os.getcwd())[0]
10 sys.path.append(path)
10 sys.path.append(path)
11
11
12 from Model.Data import Data
12 from Model.Data import Data
13 from IO.HeaderIO import *
13 from IO.HeaderIO import *
14
14
15
15
16 class Spectra(Data):
16 class Spectra(Data):
17 '''
17 '''
18 classdocs
18 classdocs
19 '''
19 '''
20
20
21
21
22 def __init__(self):
22 def __init__(self):
23 '''
23 '''
24 Constructor
24 Constructor
25 '''
25 '''
26
26
27 self.m_RadarControllerHeader = RadarControllerHeader()
27 self.m_RadarControllerHeader = RadarControllerHeader()
28
28
29 self.m_ProcessingHeader = ProcessingHeader()
29 self.m_ProcessingHeader = ProcessingHeader()
30
30
31 self.m_SystemHeader = SystemHeader()
31 self.m_SystemHeader = SystemHeader()
32
32
33 self.m_BasicHeader = BasicHeader()
33 self.m_BasicHeader = BasicHeader()
34
34
35 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
35 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
36 self.data_spc = None
36 self.data_spc = None
37
37
38 self.data_cspc = None
38 self.data_cspc = None
39
39
40 self.data_dc = None
40 self.data_dc = None
41
41
42 self.heights = None
42 self.heights = None
43
43
44 self.noData = True
44 self.noData = True
45
45
46 self.nProfiles = None
46 self.nProfiles = None
47
47
48 self.dataType = None
48 self.dataType = None
49
49
50 self.noise = None
51
50 def copy(self):
52 def copy(self):
51 obj = Spectra()
53 obj = Spectra()
52 obj.m_BasicHeader = self.m_BasicHeader.copy()
54 obj.m_BasicHeader = self.m_BasicHeader.copy()
53 obj.m_SystemHeader = self.m_SystemHeader.copy()
55 obj.m_SystemHeader = self.m_SystemHeader.copy()
54 obj.m_RadarControllerHeader = self.m_RadarControllerHeader.copy()
56 obj.m_RadarControllerHeader = self.m_RadarControllerHeader.copy()
55 obj.m_ProcessingHeader = self.m_ProcessingHeader.copy()
57 obj.m_ProcessingHeader = self.m_ProcessingHeader.copy()
56
58
57 obj.data_spc = self.data_spc
59 obj.data_spc = self.data_spc
58 obj.data_cspc = self.data_cspc
60 obj.data_cspc = self.data_cspc
59 obj.data_dc = self.data_dc
61 obj.data_dc = self.data_dc
60
62
61 obj.heights = self.heights
63 obj.heights = self.heights
62 obj.noData = self.noData
64 obj.noData = self.noData
63
65
64 obj.nProfiles = self.nProfiles
66 obj.nProfiles = self.nProfiles
65
67
68 obj.noise = self.noise
69
66 return obj
70 return obj
67 No newline at end of file
71
@@ -1,65 +1,69
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 os, sys
7 import os, sys
8
8
9 path = os.path.split(os.getcwd())[0]
9 path = os.path.split(os.getcwd())[0]
10 sys.path.append(path)
10 sys.path.append(path)
11
11
12 from Model.Data import Data
12 from Model.Data import Data
13 from IO.HeaderIO import *
13 from IO.HeaderIO import *
14
14
15 class Voltage(Data):
15 class Voltage(Data):
16 '''
16 '''
17 classdocs
17 classdocs
18 '''
18 '''
19
19
20 def __init__(self):
20 def __init__(self):
21 '''
21 '''
22 Constructor
22 Constructor
23 '''
23 '''
24
24
25 self.m_RadarControllerHeader= RadarControllerHeader()
25 self.m_RadarControllerHeader= RadarControllerHeader()
26
26
27 self.m_ProcessingHeader= ProcessingHeader()
27 self.m_ProcessingHeader= ProcessingHeader()
28
28
29 self.m_SystemHeader= SystemHeader()
29 self.m_SystemHeader= SystemHeader()
30
30
31 self.m_BasicHeader= BasicHeader()
31 self.m_BasicHeader= BasicHeader()
32
32
33 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
33 #data es un numpy array de 3 dmensiones (perfiles, alturas y canales)
34 self.data = None
34 self.data = None
35
35
36 self.heights = None
36 self.heights = None
37
37
38 self.flagNoData = True
38 self.flagNoData = True
39
39
40 self.nProfiles = None
40 self.nProfiles = None
41
41
42 self.idProfile = None
42 self.idProfile = None
43
43
44 self.dataType = None
44 self.dataType = None
45
45
46 self.flagResetProcessing = False
46 self.flagResetProcessing = False
47
47
48 self.noise = noise
49
48 def copy(self):
50 def copy(self):
49 obj = Voltage()
51 obj = Voltage()
50 obj.m_BasicHeader = self.m_BasicHeader.copy()
52 obj.m_BasicHeader = self.m_BasicHeader.copy()
51 obj.m_SystemHeader = self.m_SystemHeader.copy()
53 obj.m_SystemHeader = self.m_SystemHeader.copy()
52 obj.m_RadarControllerHeader = self.m_RadarControllerHeader.copy()
54 obj.m_RadarControllerHeader = self.m_RadarControllerHeader.copy()
53 obj.m_ProcessingHeader = self.m_ProcessingHeader.copy()
55 obj.m_ProcessingHeader = self.m_ProcessingHeader.copy()
54
56
55 obj.data = self.data
57 obj.data = self.data
56 obj.heights = self.heights
58 obj.heights = self.heights
57 obj.flagNoData = self.flagNoData
59 obj.flagNoData = self.flagNoData
58
60
59 obj.nProfiles = self.nProfiles
61 obj.nProfiles = self.nProfiles
60 obj.idProfile = self.idProfile
62 obj.idProfile = self.idProfile
61 obj.dataType = self.dataType
63 obj.dataType = self.dataType
62 obj.flagResetProcessing = self.flagResetProcessing
64 obj.flagResetProcessing = self.flagResetProcessing
63
65
66 obj.noise = self.noise
67
64 return obj
68 return obj
65 No newline at end of file
69
@@ -1,75 +1,75
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 '''
6 '''
7 import os, sys
7 import os, sys
8 import time, datetime
8 import time, datetime
9
9
10 from Model.Voltage import Voltage
10 from Model.Voltage import Voltage
11 from IO.VoltageIO import *
11 from IO.VoltageIO import *
12 from Graphics.VoltagePlot import Osciloscope
12 from Graphics.VoltagePlot import Osciloscope
13
13
14 from Model.Spectra import Spectra
14 from Model.Spectra import Spectra
15 from IO.SpectraIO import *
15 from IO.SpectraIO import *
16 from Graphics.SpectraPlot import Spectrum
16 from Graphics.SpectraPlot import Spectrum
17
17
18 class TestSChain():
18 class TestSChain():
19
19
20
20
21 def __init__(self):
21 def __init__(self):
22 self.setValues()
22 self.setValues()
23 self.createObjects()
23 self.createObjects()
24 self.testSChain()
24 self.testSChain()
25 pass
25 pass
26
26
27 def setValues(self):
27 def setValues(self):
28
28
29 self.path = '/home/roj-idl71/Data/RAWDATA/DP_Faraday/'
29 self.path = '/home/roj-idl71/Data/RAWDATA/DP_Faraday/'
30 self.path = '/Users/danielangelsuarezmunoz/Documents/Projects/testWR'
30 self.path = '/Users/danielangelsuarezmunoz/Documents/Projects/testWR'
31 self.path = '/home/roj-idl71/Data/RAWDATA/IMAGING'
31 self.path = '/home/roj-idl71/Data/RAWDATA/IMAGING'
32 # self.path = '/home/roj-idl71/tmp/data'
32 # self.path = '/home/roj-idl71/tmp/data'
33 #self.path = '/remote/puma/2004_11/DVD/'
33 #self.path = '/remote/puma/2004_11/DVD/'
34
34
35 self.ppath = "/home/roj-idl71/tmp/data"
35 self.ppath = "/home/roj-idl71/tmp/data"
36 self.startDateTime = datetime.datetime(2011,1,1,17,49,0)
36 self.startDateTime = datetime.datetime(2011,1,24,18,20,0)
37 self.endDateTime = datetime.datetime(2011,1,30,18,10,0)
37 self.endDateTime = datetime.datetime(2011,1,30,18,10,0)
38
38
39 def createObjects(self):
39 def createObjects(self):
40
40
41 self.Obj = Spectra()
41 self.Obj = Spectra()
42 self.readerObj = SpectraReader(self.Obj)
42 self.readerObj = SpectraReader(self.Obj)
43 self.plotObj = Spectrum(self.Obj)
43 self.plotObj = Spectrum(self.Obj)
44 # self.writerObj = SpectraWriter(self.Obj)
44 # self.writerObj = SpectraWriter(self.Obj)
45
45
46 if not(self.readerObj.setup(self.path, self.startDateTime, self.endDateTime, expLabel='')):
46 if not(self.readerObj.setup(self.path, self.startDateTime, self.endDateTime, expLabel='')):
47 sys.exit(0)
47 sys.exit(0)
48
48
49 # if not(self.writerObj.setup(self.ppath)):
49 # if not(self.writerObj.setup(self.ppath)):
50 # sys.exit(0)
50 # sys.exit(0)
51
51
52 def testSChain(self):
52 def testSChain(self):
53
53
54 ini = time.time()
54 ini = time.time()
55 while(True):
55 while(True):
56 self.readerObj.getData()
56 self.readerObj.getData()
57 self.plotObj.plotData(showColorbar=False, showPowerProfile=True)
57 self.plotObj.plotData(zmin=40, zmax=140, showColorbar=True, showPowerProfile=True)
58
58
59 # self.writerObj.putData()
59 # self.writerObj.putData()
60
60
61 if self.readerObj.noMoreFiles:
61 if self.readerObj.noMoreFiles:
62 break
62 break
63
63
64 if self.readerObj.flagIsNewBlock:
64 if self.readerObj.flagIsNewBlock:
65 print 'Block No %04d, Time: %s' %(self.readerObj.nReadBlocks,
65 print 'Block No %04d, Time: %s' %(self.readerObj.nReadBlocks,
66 datetime.datetime.fromtimestamp(self.readerObj.m_BasicHeader.utc),)
66 datetime.datetime.fromtimestamp(self.readerObj.m_BasicHeader.utc),)
67 fin = time.time()
67 fin = time.time()
68 print 'Tiempo de un bloque leido y escrito: [%6.5f]' %(fin - ini)
68 print 'Tiempo de un bloque leido y escrito: [%6.5f]' %(fin - ini)
69 ini = time.time()
69 ini = time.time()
70
70
71 #time.sleep(0.5)
71 #time.sleep(0.5)
72 self.plotObj.end()
72 self.plotObj.end()
73
73
74 if __name__ == '__main__':
74 if __name__ == '__main__':
75 TestSChain() No newline at end of file
75 TestSChain()
General Comments 0
You need to be logged in to leave comments. Login now