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