Changeset 1819 for trunk/python
- Timestamp:
- 08/02/10 17:28:20 (14 years ago)
- Location:
- trunk/python
- Files:
-
- 13 edited
- 10 copied
Legend:
- Unmodified
- Added
- Removed
-
trunk/python
-
Property svn:mergeinfo
set to
/branches/alma/python merged eligible
-
Property svn:mergeinfo
set to
-
trunk/python/__init__.py
r1739 r1819 9 9 from asap.compatibility import wraps as wraps_dec 10 10 11 # Set up AIPSPATH and first time use of asap i.e. ~/.asap/*11 # Set up CASAPATH and first time use of asap i.e. ~/.asap/* 12 12 plf = None 13 13 if sys.platform == "linux2": … … 26 26 if os.path.exists(os.environ["ASAPDATA"]): 27 27 asapdata = os.environ["ASAPDATA"] 28 # use AIPSPATH if defined and "data" dir present29 if not os.environ.has_key(" AIPSPATH") or \30 not os.path.exists(os.environ[" AIPSPATH"].split()[0]+"/data"):31 os.environ[" AIPSPATH"] = "%s %s somwhere" % ( asapdata, plf)28 # use CASAPATH if defined and "data" dir present 29 if not os.environ.has_key("CASAPATH") or \ 30 not os.path.exists(os.environ["CASAPATH"].split()[0]+"/data"): 31 os.environ["CASAPATH"] = "%s %s somwhere" % ( asapdata, plf) 32 32 # set up user space 33 33 userdir = os.environ["HOME"]+"/.asap" … … 35 35 print 'First time ASAP use. Setting up ~/.asap' 36 36 os.mkdir(userdir) 37 shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap") 38 shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 39 userdir+"/ipy_user_conf.py") 37 #shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap") 38 # commented out by TT on 2009.06.23 for casapy use 39 ##shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 40 ## userdir+"/ipy_user_conf.py") 40 41 f = file(userdir+"/asapuserfuncs.py", "w") 41 42 f.close() 42 43 f = file(userdir+"/ipythonrc", "w") 43 44 f.close() 44 else: 45 # commented out by TT on 2009.06.23 for casapy use 46 ##else: 45 47 # upgrade to support later ipython versions 46 if not os.path.exists(userdir+"/ipy_user_conf.py"):47 shutil.copyfile(asapdata+"/data/ipy_user_conf.py",48 userdir+"/ipy_user_conf.py")48 ##if not os.path.exists(userdir+"/ipy_user_conf.py"): 49 ## shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 50 ## userdir+"/ipy_user_conf.py") 49 51 50 52 # remove from namespace … … 110 112 'plotter.histogram' : [False, _validate_bool], 111 113 'plotter.papertype' : ['A4', str], 112 'plotter.axesformatting' : ['mpl', str], 114 ## for older Matplotlib version 115 #'plotter.axesformatting' : ['mpl', str], 116 'plotter.axesformatting' : ['asap', str], 113 117 114 118 # scantable … … 218 222 tup = line.split(':',1) 219 223 if len(tup) !=2: 220 print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname)) 224 #print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname)) 225 asaplog.push('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname)) 226 print_log('WARN') 221 227 continue 222 228 … … 224 230 key = key.strip() 225 231 if not defaultParams.has_key(key): 226 print ('Bad key "%s" on line %d in %s' % (key, cnt, fname)) 232 #print ('Bad key "%s" on line %d in %s' % (key, cnt, fname)) 233 asaplog.push('Bad key "%s" on line %d in %s' % (key, cnt, fname)) 234 print_log('WARN') 227 235 continue 228 236 … … 234 242 try: cval = converter(val) # try to convert to proper type or raise 235 243 except ValueError, msg: 236 print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg)) 244 #print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg)) 245 asaplog.push('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, str(msg))) 246 print_log('WARN') 237 247 continue 238 248 else: … … 366 376 return wrap_it 367 377 368 def print_log(): 369 log = asaplog.pop().strip() 370 if len(log) and rcParams['verbose']: print log 378 def print_log(level='INFO'): 379 from taskinit import casalog 380 log = asaplog.pop() 381 #if len(log) and rcParams['verbose']: print log 382 if len(log) and rcParams['verbose']: casalog.post( log, priority=level ) 371 383 return 372 384 … … 391 403 from simplelinefinder import simplelinefinder 392 404 from linecatalog import linecatalog 405 from interactivemask import interactivemask 393 406 from opacity import skydip 394 407 from opacity import model as opacity_model … … 400 413 if gui: 401 414 import matplotlib 402 matplotlib.use("TkAgg")415 if not matplotlib.sys.modules['matplotlib.backends']: matplotlib.use("TkAgg") 403 416 from matplotlib import pylab 404 417 xyplotter = pylab … … 406 419 del gui 407 420 except ImportError: 408 print "Matplotlib not installed. No plotting available" 421 #print "Matplotlib not installed. No plotting available" 422 asaplog.post( "Matplotlib not installed. No plotting available") 423 print_log('WARN') 409 424 410 425 __date__ = '$Date$'.split()[1] 411 __version__ = '$Revision$' 426 __version__ = '3.0.0 alma' 427 # nrao casapy specific, get revision number 428 #__revision__ = ' unknown ' 429 casapath=os.environ["CASAPATH"].split() 430 #svninfo.txt path 431 if os.path.isdir(casapath[0]+'/'+casapath[1]+'/python/2.5/asap'): 432 # for casa developer environment (linux or darwin) 433 revinfo=casapath[0]+'/'+casapath[1]+'/python/2.5/asap/svninfo.txt' 434 else: 435 # for end-user environments 436 if casapath[1]=='darwin': 437 revinfo=casapath[0]+'/Resources/python/asap/svninfo.txt' 438 else: 439 revinfo=casapath[0]+'/lib/python2.5/asap/svninfo.txt' 440 if os.path.isfile(revinfo): 441 f = file(revinfo) 442 f.readline() 443 revsionno=f.readline() 444 f.close() 445 del f 446 __revision__ = revsionno.rstrip() 447 else: 448 __revision__ = ' unknown ' 412 449 413 450 def is_ipython(): 414 451 return 'IPython' in sys.modules.keys() 415 416 452 if is_ipython(): 417 453 def version(): print "ASAP %s(%s)"% (__version__, __date__) -
trunk/python/asapfitter.py
r1739 r1819 1 1 import _asap 2 2 from asap import rcParams 3 from asap import print_log _dec3 from asap import print_log, print_log_dec 4 4 from asap import _n_bools 5 5 from asap import mask_and 6 from asap import asaplog 6 7 7 8 class fitter: … … 59 60 msg = "Please give a correct scan" 60 61 if rcParams['verbose']: 61 print msg 62 #print msg 63 asaplog.push(msg) 64 print_log('ERROR') 62 65 return 63 66 else: … … 79 82 lpoly: use polynomial of the order given with linear least squares fit 80 83 gauss: fit the number of gaussian specified 84 lorentz: fit the number of lorentzian specified 81 85 Example: 82 fitter.set_function(gauss=2) # will fit two gaussians83 86 fitter.set_function(poly=3) # will fit a 3rd order polynomial via nonlinear method 84 87 fitter.set_function(lpoly=3) # will fit a 3rd order polynomial via linear method 88 fitter.set_function(gauss=2) # will fit two gaussians 89 fitter.set_function(lorentz=2) # will fit two lorentzians 85 90 """ 86 91 #default poly order 0 … … 102 107 self.components = [ 3 for i in range(n) ] 103 108 self.uselinear = False 109 elif kwargs.has_key('lorentz'): 110 n = kwargs.get('lorentz') 111 self.fitfunc = 'lorentz' 112 self.fitfuncs = [ 'lorentz' for i in range(n) ] 113 self.components = [ 3 for i in range(n) ] 114 self.uselinear = False 104 115 else: 105 116 msg = "Invalid function type." 106 117 if rcParams['verbose']: 107 print msg 118 #print msg 119 asaplog.push(msg) 120 print_log('ERROR') 108 121 return 109 122 else: … … 135 148 msg = "Fitter not yet initialised. Please set data & fit function" 136 149 if rcParams['verbose']: 137 print msg 150 #print msg 151 asaplog.push(msg) 152 print_log('ERROR') 138 153 return 139 154 else: … … 145 160 self.y = self.data._getspectrum(row) 146 161 self.mask = mask_and(self.mask, self.data._getmask(row)) 147 from asap import asaplog148 162 asaplog.push("Fitting:") 149 163 i = row … … 155 169 asaplog.push(out,False) 156 170 self.fitter.setdata(self.x, self.y, self.mask) 157 if self.fitfunc == 'gauss' :171 if self.fitfunc == 'gauss' or self.fitfunc == 'lorentz': 158 172 ps = self.fitter.getparameters() 159 173 if len(ps) == 0 or estimate: … … 171 185 except RuntimeError, msg: 172 186 if rcParams['verbose']: 173 print msg 187 #print msg 188 print_log() 189 asaplog.push(str(msg)) 190 print_log('ERROR') 174 191 else: 175 192 raise 176 193 self._fittedrow = row 177 194 self.fitted = True 195 print_log() 178 196 return 179 197 … … 228 246 msg = "Please specify a fitting function first." 229 247 if rcParams['verbose']: 230 print msg 248 #print msg 249 asaplog.push(msg) 250 print_log('ERROR') 231 251 return 232 252 else: 233 253 raise RuntimeError(msg) 234 if self.fitfunc == "gauss"and component is not None:254 if (self.fitfunc == "gauss" or self.fitfunc == 'lorentz') and component is not None: 235 255 if not self.fitted and sum(self.fitter.getparameters()) == 0: 236 256 pars = _n_bools(len(self.components)*3, False) … … 247 267 if fixed is not None: 248 268 self.fitter.setfixedparameters(fixed) 269 print_log() 249 270 return 250 271 … … 269 290 msg = "Function only operates on Gaussian components." 270 291 if rcParams['verbose']: 271 print msg 292 #print msg 293 asaplog.push(msg) 294 print_log('ERROR') 272 295 return 273 296 else: … … 280 303 msg = "Please select a valid component." 281 304 if rcParams['verbose']: 282 print msg 305 #print msg 306 asaplog.push(msg) 307 print_log('ERROR') 283 308 return 284 309 else: 285 310 raise ValueError(msg) 286 311 312 def set_lorentz_parameters(self, peak, centre, fwhm, 313 peakfixed=0, centrefixed=0, 314 fwhmfixed=0, 315 component=0): 316 """ 317 Set the Parameters of a 'Lorentzian' component, set with set_function. 318 Parameters: 319 peak, centre, fwhm: The gaussian parameters 320 peakfixed, 321 centrefixed, 322 fwhmfixed: Optional parameters to indicate if 323 the paramters should be held fixed during 324 the fitting process. The default is to keep 325 all parameters flexible. 326 component: The number of the component (Default is the 327 component 0) 328 """ 329 if self.fitfunc != "lorentz": 330 msg = "Function only operates on Lorentzian components." 331 if rcParams['verbose']: 332 #print msg 333 asaplog.push(msg) 334 print_log('ERROR') 335 return 336 else: 337 raise ValueError(msg) 338 if 0 <= component < len(self.components): 339 d = {'params':[peak, centre, fwhm], 340 'fixed':[peakfixed, centrefixed, fwhmfixed]} 341 self.set_parameters(d, component) 342 else: 343 msg = "Please select a valid component." 344 if rcParams['verbose']: 345 #print msg 346 asaplog.push(msg) 347 print_log('ERROR') 348 return 349 else: 350 raise ValueError(msg) 351 287 352 def get_area(self, component=None): 288 353 """ 289 Return the area under the fitted gaussian component.290 Parameters: 291 component: the gaussian component selection,354 Return the area under the fitted gaussian/lorentzian component. 355 Parameters: 356 component: the gaussian/lorentzian component selection, 292 357 default (None) is the sum of all components 293 358 Note: 294 This will only work for gaussian fits.359 This will only work for gaussian/lorentzian fits. 295 360 """ 296 361 if not self.fitted: return 297 if self.fitfunc == "gauss" :362 if self.fitfunc == "gauss" or self.fitfunc == "lorentz": 298 363 pars = list(self.fitter.getparameters()) 299 364 from math import log,pi,sqrt 300 fac = sqrt(pi/log(16.0)) 365 if self.fitfunc == "gauss": 366 fac = sqrt(pi/log(16.0)) 367 elif self.fitfunc == "lorentz": 368 fac = pi/2.0 301 369 areas = [] 302 370 for i in range(len(self.components)): … … 321 389 msg = "Not yet fitted." 322 390 if rcParams['verbose']: 323 print msg 391 #print msg 392 asaplog.push(msg) 393 print_log('ERROR') 324 394 return 325 395 else: … … 328 398 cerrs = errs 329 399 if component is not None: 330 if self.fitfunc == "gauss" :400 if self.fitfunc == "gauss" or self.fitfunc == "lorentz": 331 401 i = 3*component 332 402 if i < len(errs): … … 344 414 msg = "Not yet fitted." 345 415 if rcParams['verbose']: 346 print msg 416 #print msg 417 asaplog.push(msg) 418 print_log('ERROR') 347 419 return 348 420 else: … … 353 425 area = [] 354 426 if component is not None: 355 if self.fitfunc == "gauss" :427 if self.fitfunc == "gauss" or self.fitfunc == "lorentz": 356 428 i = 3*component 357 429 cpars = pars[i:i+3] … … 368 440 cfixed = fixed 369 441 cerrs = errs 370 if self.fitfunc == "gauss" :442 if self.fitfunc == "gauss" or self.fitfunc == "lorentz": 371 443 for c in range(len(self.components)): 372 444 a = self.get_area(c) … … 374 446 fpars = self._format_pars(cpars, cfixed, errors and cerrs, area) 375 447 if rcParams['verbose']: 376 print fpars 448 #print fpars 449 asaplog.push(fpars) 450 print_log() 377 451 return {'params':cpars, 'fixed':cfixed, 'formatted': fpars, 378 452 'errors':cerrs} … … 391 465 c+=1 392 466 out = out[:-1] # remove trailing ',' 393 elif self.fitfunc == 'gauss' :467 elif self.fitfunc == 'gauss' or self.fitfunc == 'lorentz': 394 468 i = 0 395 469 c = 0 … … 415 489 fixed = self.fitter.getfixedparameters() 416 490 if rcParams['verbose']: 417 print self._format_pars(pars,fixed,None) 491 #print self._format_pars(pars,fixed,None) 492 asaplog.push(self._format_pars(pars,fixed,None)) 493 print_log() 418 494 return pars 419 495 … … 425 501 msg = "Not yet fitted." 426 502 if rcParams['verbose']: 427 print msg 503 #print msg 504 asaplog.push(msg) 505 print_log('ERROR') 428 506 return 429 507 else: … … 438 516 msg = "Not yet fitted." 439 517 if rcParams['verbose']: 440 print msg 518 #print msg 519 asaplog.push(msg) 520 print_log('ERROR') 441 521 return 442 522 else: … … 444 524 ch2 = self.fitter.getchi2() 445 525 if rcParams['verbose']: 446 print 'Chi^2 = %3.3f' % (ch2) 526 #print 'Chi^2 = %3.3f' % (ch2) 527 asaplog.push( 'Chi^2 = %3.3f' % (ch2) ) 528 print_log() 447 529 return ch2 448 530 … … 454 536 msg = "Not yet fitted." 455 537 if rcParams['verbose']: 456 print msg 538 #print msg 539 asaplog.push(msg) 540 print_log('ERROR') 457 541 return 458 542 else: … … 468 552 msg = "Not yet fitted." 469 553 if rcParams['verbose']: 470 print msg 554 #print msg 555 asaplog.push(msg) 556 print_log('ERROR') 471 557 return 472 558 else: … … 476 562 msg = "Not a scantable" 477 563 if rcParams['verbose']: 478 print msg 564 #print msg 565 asaplog.push(msg) 566 print_log('ERROR') 479 567 return 480 568 else: … … 482 570 scan = self.data.copy() 483 571 scan._setspectrum(self.fitter.getresidual()) 572 print_log() 484 573 return scan 485 574 … … 525 614 526 615 colours = ["#777777","#dddddd","red","orange","purple","green","magenta", "cyan"] 616 nomask=True 617 for i in range(len(m)): 618 nomask = nomask and m[i] 619 label0='Masked Region' 620 label1='Spectrum' 621 if ( nomask ): 622 label0=label1 623 else: 624 y = ma.masked_array( self.y, mask = m ) 625 self._p.palette(1,colours) 626 self._p.set_line( label = label1 ) 627 self._p.plot( self.x, y ) 527 628 self._p.palette(0,colours) 528 self._p.set_line(label= 'Spectrum')629 self._p.set_line(label=label0) 529 630 y = ma.masked_array(self.y,mask=logical_not(m)) 530 631 self._p.plot(self.x, y) 531 632 if residual: 532 self._p.palette( 1)633 self._p.palette(7) 533 634 self._p.set_line(label='Residual') 534 635 y = ma.masked_array(self.get_residual(), … … 571 672 if (not rcParams['plotter.gui']): 572 673 self._p.save(filename) 674 print_log() 573 675 574 676 @print_log_dec … … 583 685 msg = "Data is not a scantable" 584 686 if rcParams['verbose']: 585 print msg 687 #print msg 688 asaplog.push(msg) 689 print_log('ERROR') 586 690 return 587 691 else: … … 593 697 scan = self.data 594 698 rows = xrange(scan.nrow()) 595 from asap import asaplog 699 # Save parameters of baseline fits as a class attribute. 700 # NOTICE: This does not reflect changes in scantable! 701 if len(rows) > 0: self.blpars=[] 596 702 asaplog.push("Fitting:") 597 703 for r in rows: … … 608 714 self.fit() 609 715 x = self.get_parameters() 716 fpar = self.get_parameters() 610 717 if plot: 611 718 self.plot(residual=True) 612 719 x = raw_input("Accept fit ([y]/n): ") 613 720 if x.upper() == 'N': 721 self.blpars.append(None) 614 722 continue 615 723 scan._setspectrum(self.fitter.getresidual(), r) 724 self.blpars.append(fpar) 616 725 if plot: 617 726 self._p.unmap() 618 727 self._p = None 728 print_log() 619 729 return scan -
trunk/python/asaplot.py
r1564 r1819 6 6 7 7 from matplotlib.backends.backend_agg import FigureCanvasAgg 8 from matplotlib.backend_bases import FigureManagerBase 8 9 9 10 class asaplot(asaplotbase): … … 22 23 asaplotbase.__init__(self,**v) 23 24 self.canvas = FigureCanvasAgg(self.figure) 25 self.figmgr = FigureManagerBase(self.canvas,1) -
trunk/python/asaplotbase.py
r1739 r1819 21 21 from matplotlib.transforms import blend_xy_sep_transform as blended_transform_factory 22 22 23 from asap import asaplog 24 23 25 if int(matplotlib.__version__.split(".")[1]) < 87: 24 print "Warning: matplotlib version < 0.87. This might cause errors. Please upgrade." 26 #print "Warning: matplotlib version < 0.87. This might cause errors. Please upgrade." 27 asaplog.push( "matplotlib version < 0.87. This might cause errors. Please upgrade." ) 28 print_log( 'WARN' ) 25 29 26 30 class asaplotbase: … … 147 151 from numpy import array 148 152 from numpy.ma import MaskedArray 149 150 153 if x is None: 151 154 if y is None: return … … 168 171 ymsk = y.mask 169 172 ydat = y.data 170 171 173 for i in range(l2): 172 174 x2[i] = x[i/2] … … 304 306 305 307 def region_start(event): 306 height = self.canvas.figure.bbox.height() 307 self.rect = {'fig': None, 'height': height, 308 'x': event.x, 'y': height - event.y, 308 self.rect = {'x': event.x, 'y': event.y, 309 309 'world': [event.xdata, event.ydata, 310 310 event.xdata, event.ydata]} … … 314 314 315 315 def region_draw(event): 316 self.canvas._tkcanvas.delete(self.rect['fig']) 317 self.rect['fig'] = self.canvas._tkcanvas.create_rectangle( 318 self.rect['x'], self.rect['y'], 319 event.x, self.rect['height'] - event.y) 320 316 self.figmgr.toolbar.draw_rubberband(event, event.x, event.y, 317 self.rect['x'], self.rect['y']) 318 321 319 def region_disable(event): 322 320 self.register('motion_notify', None) 323 321 self.register('button_release', None) 324 325 self.canvas._tkcanvas.delete(self.rect['fig'])326 322 327 323 self.rect['world'][2:4] = [event.xdata, event.ydata] … … 329 325 self.rect['world'][1], self.rect['world'][2], 330 326 self.rect['world'][3]) 327 self.figmgr.toolbar.release(event) 331 328 332 329 self.register('button_press', region_start) … … 381 378 self.events[type] = None 382 379 383 # It seems to be necessary to return events to the toolbar. 384 if type == 'motion_notify':385 self.canvas.mpl_connect(type + '_event',386 self.figmgr.toolbar.mouse_move)387 elif type == 'button_press':388 self.canvas.mpl_connect(type + '_event',389 self.figmgr.toolbar.press)390 elif type == 'button_release':391 self.canvas.mpl_connect(type + '_event',392 self.figmgr.toolbar.release)380 # It seems to be necessary to return events to the toolbar. <-- Not ture. 2010.Jul.14.kana. 381 #if type == 'motion_notify': 382 # self.canvas.mpl_connect(type + '_event', 383 # self.figmgr.toolbar.mouse_move) 384 #elif type == 'button_press': 385 # self.canvas.mpl_connect(type + '_event', 386 # self.figmgr.toolbar.press) 387 #elif type == 'button_release': 388 # self.canvas.mpl_connect(type + '_event', 389 # self.figmgr.toolbar.release) 393 390 394 391 else: … … 459 456 print 'Written file %s' % (fname) 460 457 except IOError, msg: 461 print 'Failed to save %s: Error msg was\n\n%s' % (fname, msg) 458 #print 'Failed to save %s: Error msg was\n\n%s' % (fname, err) 459 print_log() 460 asaplog.push('Failed to save %s: Error msg was\n\n%s' % (fname, str(msg))) 461 print_log( 'ERROR' ) 462 462 return 463 463 else: 464 print "Invalid image type. Valid types are:" 465 print "'ps', 'eps', 'png'" 464 #print "Invalid image type. Valid types are:" 465 #print "'ps', 'eps', 'png'" 466 asaplog.push( "Invalid image type. Valid types are:" ) 467 asaplog.push( "'ps', 'eps', 'png'" ) 468 print_log('WARN') 466 469 467 470 … … 575 578 576 579 577 def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, ganged=True): 580 #def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, ganged=True): 581 def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, layout=None,ganged=True): 578 582 """ 579 583 Set the panel layout. … … 598 602 self.set_title() 599 603 604 if layout: 605 lef, bot, rig, top, wsp, hsp = layout 606 self.figure.subplots_adjust( 607 left=lef,bottom=bot,right=rig,top=top,wspace=wsp,hspace=hsp) 608 del lef,bot,rig,top,wsp,hsp 609 600 610 if rows < 1: rows = 1 601 611 … … 610 620 if 0 <= n < rows*cols: 611 621 i = len(self.subplots) 622 612 623 self.subplots.append({}) 613 624 … … 644 655 cols, i+1) 645 656 if asaprcParams['plotter.axesformatting'] != 'mpl': 646 657 647 658 self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter()) 648 659 else: … … 671 682 self.cols = cols 672 683 self.subplot(0) 684 del rows,cols,n,nplots,layout,ganged,i 673 685 674 686 def tidy(self): … … 725 737 sp['axes'].legend((' ')) 726 738 727 728 739 from matplotlib.artist import setp 729 740 fpx = FP(size=rcParams['xtick.labelsize']) … … 734 745 fpat = FP(size=rcParams['axes.titlesize']) 735 746 axsize = fpa.get_size_in_points() 736 tsize = fpat.get_size_in_points() 747 tsize = fpat.get_size_in_points()-(self.cols)/2 737 748 for sp in self.subplots: 738 749 ax = sp['axes'] 739 off = 0 740 if len(self.subplots) > 1: 741 off = self.cols+self.rows 742 ax.title.set_size(tsize-off) 750 ax.title.set_size(tsize) 743 751 setp(ax.get_xticklabels(), fontsize=xts) 744 752 setp(ax.get_yticklabels(), fontsize=yts) 745 753 off = 0 746 if self.cols > 1: 747 off = self.cols 754 if self.cols > 1: off = self.cols 748 755 ax.xaxis.label.set_size(axsize-off) 749 if self.rows > 1:750 756 off = 0 757 if self.rows > 1: off = self.rows 751 758 ax.yaxis.label.set_size(axsize-off) 752 759 -
trunk/python/asaplotgui.py
r1563 r1819 56 56 self.window.lift() 57 57 58 def position(self):59 """60 Use the mouse to get a position from a graph.61 """62 63 def position_disable(event):64 self.register('button_press', None)65 print '%.4f, %.4f' % (event.xdata, event.ydata)66 67 print 'Press any mouse button...'68 self.register('button_press', position_disable)69 70 71 58 def quit(self): 72 59 """ … … 74 61 """ 75 62 self.window.destroy() 76 77 78 def region(self):79 """80 Use the mouse to get a rectangular region from a plot.81 82 The return value is [x0, y0, x1, y1] in world coordinates.83 """84 85 def region_start(event):86 height = self.canvas.figure.bbox.height()87 self.rect = {'fig': None, 'height': height,88 'x': event.x, 'y': height - event.y,89 'world': [event.xdata, event.ydata,90 event.xdata, event.ydata]}91 self.register('button_press', None)92 self.register('motion_notify', region_draw)93 self.register('button_release', region_disable)94 95 def region_draw(event):96 self.canvas._tkcanvas.delete(self.rect['fig'])97 self.rect['fig'] = self.canvas._tkcanvas.create_rectangle(98 self.rect['x'], self.rect['y'],99 event.x, self.rect['height'] - event.y)100 101 def region_disable(event):102 self.register('motion_notify', None)103 self.register('button_release', None)104 105 self.canvas._tkcanvas.delete(self.rect['fig'])106 107 self.rect['world'][2:4] = [event.xdata, event.ydata]108 print '(%.2f, %.2f) (%.2f, %.2f)' % (self.rect['world'][0],109 self.rect['world'][1], self.rect['world'][2],110 self.rect['world'][3])111 112 self.register('button_press', region_start)113 114 # This has to be modified to block and return the result (currently115 # printed by region_disable) when that becomes possible in matplotlib.116 117 return [0.0, 0.0, 0.0, 0.0]118 119 120 def register(self, type=None, func=None):121 """122 Register, reregister, or deregister events of type 'button_press',123 'button_release', or 'motion_notify'.124 125 The specified callback function should have the following signature:126 127 def func(event)128 129 where event is an MplEvent instance containing the following data:130 131 name # Event name.132 canvas # FigureCanvas instance generating the event.133 x = None # x position - pixels from left of canvas.134 y = None # y position - pixels from bottom of canvas.135 button = None # Button pressed: None, 1, 2, 3.136 key = None # Key pressed: None, chr(range(255)), shift,137 win, or control138 inaxes = None # Axes instance if cursor within axes.139 xdata = None # x world coordinate.140 ydata = None # y world coordinate.141 142 For example:143 144 def mouse_move(event):145 print event.xdata, event.ydata146 147 a = asaplot()148 a.register('motion_notify', mouse_move)149 150 If func is None, the event is deregistered.151 152 Note that in TkAgg keyboard button presses don't generate an event.153 """154 155 if not self.events.has_key(type): return156 157 if func is None:158 if self.events[type] is not None:159 # It's not clear that this does anything.160 self.canvas.mpl_disconnect(self.events[type])161 self.events[type] = None162 163 # It seems to be necessary to return events to the toolbar.164 if type == 'motion_notify':165 self.canvas.mpl_connect(type + '_event',166 self.figmgr.toolbar.mouse_move)167 elif type == 'button_press':168 self.canvas.mpl_connect(type + '_event',169 self.figmgr.toolbar.press)170 elif type == 'button_release':171 self.canvas.mpl_connect(type + '_event',172 self.figmgr.toolbar.release)173 174 else:175 self.events[type] = self.canvas.mpl_connect(type + '_event', func)176 177 63 178 64 def show(self, hardrefresh=True): -
trunk/python/asaplotgui_gtk.py
r1563 r1819 57 57 #self.window.lift() 58 58 59 def position(self):60 """61 Use the mouse to get a position from a graph.62 """63 64 def position_disable(event):65 self.register('button_press', None)66 print '%.4f, %.4f' % (event.xdata, event.ydata)67 68 print 'Press any mouse button...'69 self.register('button_press', position_disable)59 # def position(self): 60 # """ 61 # Use the mouse to get a position from a graph. 62 # """ 63 64 # def position_disable(event): 65 # self.register('button_press', None) 66 # print '%.4f, %.4f' % (event.xdata, event.ydata) 67 68 # print 'Press any mouse button...' 69 # self.register('button_press', position_disable) 70 70 71 71 … … 77 77 78 78 79 def region(self):80 """81 Use the mouse to get a rectangular region from a plot.82 83 The return value is [x0, y0, x1, y1] in world coordinates.84 """85 86 def region_start(event):87 height = self.canvas.figure.bbox.height()88 self.rect = {'fig': None, 'height': height,89 'x': event.x, 'y': height - event.y,90 'world': [event.xdata, event.ydata,91 event.xdata, event.ydata]}92 self.register('button_press', None)93 self.register('motion_notify', region_draw)94 self.register('button_release', region_disable)95 96 def region_draw(event):97 self.canvas._tkcanvas.delete(self.rect['fig'])98 self.rect['fig'] = self.canvas._tkcanvas.create_rectangle(99 self.rect['x'], self.rect['y'],100 event.x, self.rect['height'] - event.y)101 102 def region_disable(event):103 self.register('motion_notify', None)104 self.register('button_release', None)105 106 self.canvas._tkcanvas.delete(self.rect['fig'])107 108 self.rect['world'][2:4] = [event.xdata, event.ydata]109 print '(%.2f, %.2f) (%.2f, %.2f)' % (self.rect['world'][0],110 self.rect['world'][1], self.rect['world'][2],111 self.rect['world'][3])112 113 self.register('button_press', region_start)114 115 # This has to be modified to block and return the result (currently116 # printed by region_disable) when that becomes possible in matplotlib.117 118 return [0.0, 0.0, 0.0, 0.0]119 120 121 def register(self, type=None, func=None):122 """123 Register, reregister, or deregister events of type 'button_press',124 'button_release', or 'motion_notify'.125 126 The specified callback function should have the following signature:127 128 def func(event)129 130 where event is an MplEvent instance containing the following data:131 132 name # Event name.133 canvas # FigureCanvas instance generating the event.134 x = None # x position - pixels from left of canvas.135 y = None # y position - pixels from bottom of canvas.136 button = None # Button pressed: None, 1, 2, 3.137 key = None # Key pressed: None, chr(range(255)), shift,138 win, or control139 inaxes = None # Axes instance if cursor within axes.140 xdata = None # x world coordinate.141 ydata = None # y world coordinate.142 143 For example:144 145 def mouse_move(event):146 print event.xdata, event.ydata147 148 a = asaplot()149 a.register('motion_notify', mouse_move)150 151 If func is None, the event is deregistered.152 153 Note that in TkAgg keyboard button presses don't generate an event.154 """155 156 if not self.events.has_key(type): return157 158 if func is None:159 if self.events[type] is not None:160 # It's not clear that this does anything.161 self.canvas.mpl_disconnect(self.events[type])162 self.events[type] = None163 164 # It seems to be necessary to return events to the toolbar.165 if type == 'motion_notify':166 self.canvas.mpl_connect(type + '_event',167 self.figmgr.toolbar.mouse_move)168 elif type == 'button_press':169 self.canvas.mpl_connect(type + '_event',170 self.figmgr.toolbar.press)171 elif type == 'button_release':172 self.canvas.mpl_connect(type + '_event',173 self.figmgr.toolbar.release)174 175 else:176 self.events[type] = self.canvas.mpl_connect(type + '_event', func)79 # def region(self): 80 # """ 81 # Use the mouse to get a rectangular region from a plot. 82 83 # The return value is [x0, y0, x1, y1] in world coordinates. 84 # """ 85 86 # def region_start(event): 87 # height = self.canvas.figure.bbox.height() 88 # self.rect = {'fig': None, 'height': height, 89 # 'x': event.x, 'y': height - event.y, 90 # 'world': [event.xdata, event.ydata, 91 # event.xdata, event.ydata]} 92 # self.register('button_press', None) 93 # self.register('motion_notify', region_draw) 94 # self.register('button_release', region_disable) 95 96 # def region_draw(event): 97 # self.canvas._tkcanvas.delete(self.rect['fig']) 98 # self.rect['fig'] = self.canvas._tkcanvas.create_rectangle( 99 # self.rect['x'], self.rect['y'], 100 # event.x, self.rect['height'] - event.y) 101 102 # def region_disable(event): 103 # self.register('motion_notify', None) 104 # self.register('button_release', None) 105 106 # self.canvas._tkcanvas.delete(self.rect['fig']) 107 108 # self.rect['world'][2:4] = [event.xdata, event.ydata] 109 # print '(%.2f, %.2f) (%.2f, %.2f)' % (self.rect['world'][0], 110 # self.rect['world'][1], self.rect['world'][2], 111 # self.rect['world'][3]) 112 113 # self.register('button_press', region_start) 114 115 # # This has to be modified to block and return the result (currently 116 # # printed by region_disable) when that becomes possible in matplotlib. 117 118 # return [0.0, 0.0, 0.0, 0.0] 119 120 121 # def register(self, type=None, func=None): 122 # """ 123 # Register, reregister, or deregister events of type 'button_press', 124 # 'button_release', or 'motion_notify'. 125 126 # The specified callback function should have the following signature: 127 128 # def func(event) 129 130 # where event is an MplEvent instance containing the following data: 131 132 # name # Event name. 133 # canvas # FigureCanvas instance generating the event. 134 # x = None # x position - pixels from left of canvas. 135 # y = None # y position - pixels from bottom of canvas. 136 # button = None # Button pressed: None, 1, 2, 3. 137 # key = None # Key pressed: None, chr(range(255)), shift, 138 # win, or control 139 # inaxes = None # Axes instance if cursor within axes. 140 # xdata = None # x world coordinate. 141 # ydata = None # y world coordinate. 142 143 # For example: 144 145 # def mouse_move(event): 146 # print event.xdata, event.ydata 147 148 # a = asaplot() 149 # a.register('motion_notify', mouse_move) 150 151 # If func is None, the event is deregistered. 152 153 # Note that in TkAgg keyboard button presses don't generate an event. 154 # """ 155 156 # if not self.events.has_key(type): return 157 158 # if func is None: 159 # if self.events[type] is not None: 160 # # It's not clear that this does anything. 161 # self.canvas.mpl_disconnect(self.events[type]) 162 # self.events[type] = None 163 164 # # It seems to be necessary to return events to the toolbar. 165 # if type == 'motion_notify': 166 # self.canvas.mpl_connect(type + '_event', 167 # self.figmgr.toolbar.mouse_move) 168 # elif type == 'button_press': 169 # self.canvas.mpl_connect(type + '_event', 170 # self.figmgr.toolbar.press) 171 # elif type == 'button_release': 172 # self.canvas.mpl_connect(type + '_event', 173 # self.figmgr.toolbar.release) 174 175 # else: 176 # self.events[type] = self.canvas.mpl_connect(type + '_event', func) 177 177 178 178 -
trunk/python/asapmath.py
r1591 r1819 1 1 from asap.scantable import scantable 2 2 from asap import rcParams 3 from asap import print_log _dec3 from asap import print_log, print_log_dec 4 4 from asap import selector 5 from asap import asaplog 6 from asap import asaplotgui 5 7 6 8 @print_log_dec … … 46 48 if kwargs.has_key('align'): 47 49 align = kwargs.get('align') 50 compel = False 51 if kwargs.has_key('compel'): 52 compel = kwargs.get('compel') 48 53 varlist = vars() 49 54 if isinstance(args[0],list): … … 64 69 msg = "Please give a list of scantables" 65 70 if rcParams['verbose']: 66 print msg 71 #print msg 72 asaplog.push(msg) 73 print_log('ERROR') 67 74 return 68 75 else: … … 87 94 del merged 88 95 else: 89 s = scantable(stm._average(alignedlst, mask, weight.upper(), scanav)) 96 #s = scantable(stm._average(alignedlst, mask, weight.upper(), scanav)) 97 s = scantable(stm._new_average(alignedlst, compel, mask, weight.upper(), scanav)) 90 98 s._add_history("average_time",varlist) 99 print_log() 91 100 return s 92 101 … … 111 120 s = scantable(stm._quotient(source, reference, preserve)) 112 121 s._add_history("quotient",varlist) 122 print_log() 113 123 return s 114 124 … … 129 139 s = scantable(stm._dototalpower(calon, caloff, tcalval)) 130 140 s._add_history("dototalpower",varlist) 141 print_log() 131 142 return s 132 143 … … 149 160 s = scantable(stm._dosigref(sig, ref, smooth, tsysval, tauval)) 150 161 s._add_history("dosigref",varlist) 162 print_log() 151 163 return s 152 164 153 165 @print_log_dec 154 def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0 ):166 def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 155 167 """ 156 168 Calibrate GBT position switched data … … 176 188 varlist = vars() 177 189 # check for the appropriate data 178 s = scantab.get_scan('*_ps*') 179 if s is None: 190 ## s = scantab.get_scan('*_ps*') 191 ## if s is None: 192 ## msg = "The input data appear to contain no position-switch mode data." 193 ## if rcParams['verbose']: 194 ## #print msg 195 ## asaplog.push(msg) 196 ## print_log('ERROR') 197 ## return 198 ## else: 199 ## raise TypeError(msg) 200 s = scantab.copy() 201 from asap._asap import srctype 202 sel = selector() 203 sel.set_types( srctype.pson ) 204 try: 205 scantab.set_selection( sel ) 206 except Exception, e: 180 207 msg = "The input data appear to contain no position-switch mode data." 181 208 if rcParams['verbose']: 182 print msg 209 #print msg 210 asaplog.push(msg) 211 print_log('ERROR') 183 212 return 184 213 else: 185 214 raise TypeError(msg) 215 s.set_selection() 216 sel.reset() 186 217 ssub = s.get_scan(scannos) 187 218 if ssub is None: 188 219 msg = "No data was found with given scan numbers!" 189 220 if rcParams['verbose']: 190 print msg 221 #print msg 222 asaplog.push(msg) 223 print_log('ERROR') 191 224 return 192 225 else: 193 226 raise TypeError(msg) 194 ssubon = ssub.get_scan('*calon') 195 ssuboff = ssub.get_scan('*[^calon]') 227 #ssubon = ssub.get_scan('*calon') 228 #ssuboff = ssub.get_scan('*[^calon]') 229 sel.set_types( [srctype.poncal,srctype.poffcal] ) 230 ssub.set_selection( sel ) 231 ssubon = ssub.copy() 232 ssub.set_selection() 233 sel.reset() 234 sel.set_types( [srctype.pson,srctype.psoff] ) 235 ssub.set_selection( sel ) 236 ssuboff = ssub.copy() 237 ssub.set_selection() 238 sel.reset() 196 239 if ssubon.nrow() != ssuboff.nrow(): 197 240 msg = "mismatch in numbers of CAL on/off scans. Cannot calibrate. Check the scan numbers." 198 241 if rcParams['verbose']: 199 print msg 242 #print msg 243 asaplog.push(msg) 244 print_log('ERROR') 200 245 return 201 246 else: 202 247 raise TypeError(msg) 203 248 cals = dototalpower(ssubon, ssuboff, tcalval) 204 sig = cals.get_scan('*ps') 205 ref = cals.get_scan('*psr') 249 #sig = cals.get_scan('*ps') 250 #ref = cals.get_scan('*psr') 251 sel.set_types( srctype.pson ) 252 cals.set_selection( sel ) 253 sig = cals.copy() 254 cals.set_selection() 255 sel.reset() 256 sel.set_types( srctype.psoff ) 257 cals.set_selection( sel ) 258 ref = cals.copy() 259 cals.set_selection() 260 sel.reset() 206 261 if sig.nscan() != ref.nscan(): 207 262 msg = "mismatch in numbers of on/off scans. Cannot calibrate. Check the scan numbers." 208 263 if rcParams['verbose']: 209 print msg 264 #print msg 265 asaplog.push(msg) 266 print_log('ERROR') 210 267 return 211 268 else: … … 217 274 msg = "Need to supply a valid tau to use the supplied Tsys" 218 275 if rcParams['verbose']: 219 print msg 276 #print msg 277 asaplog.push(msg) 278 print_log('ERROR') 220 279 return 221 280 else: … … 236 295 #ress = dosigref(sig, ref, smooth, tsysval) 237 296 ress = dosigref(sig, ref, smooth, tsysval, tauval) 297 ### 298 if verify: 299 # get data 300 import numpy 301 precal={} 302 postcal=[] 303 keys=['ps','ps_calon','psr','psr_calon'] 304 types=[srctype.pson,srctype.poncal,srctype.psoff,srctype.poffcal] 305 ifnos=list(ssub.getifnos()) 306 polnos=list(ssub.getpolnos()) 307 sel=selector() 308 for i in range(2): 309 #ss=ssuboff.get_scan('*'+keys[2*i]) 310 ll=[] 311 for j in range(len(ifnos)): 312 for k in range(len(polnos)): 313 sel.set_ifs(ifnos[j]) 314 sel.set_polarizations(polnos[k]) 315 sel.set_types(types[2*i]) 316 try: 317 #ss.set_selection(sel) 318 ssuboff.set_selection(sel) 319 except: 320 continue 321 #ll.append(numpy.array(ss._getspectrum(0))) 322 ll.append(numpy.array(ssuboff._getspectrum(0))) 323 sel.reset() 324 ssuboff.set_selection() 325 precal[keys[2*i]]=ll 326 #del ss 327 #ss=ssubon.get_scan('*'+keys[2*i+1]) 328 ll=[] 329 for j in range(len(ifnos)): 330 for k in range(len(polnos)): 331 sel.set_ifs(ifnos[j]) 332 sel.set_polarizations(polnos[k]) 333 sel.set_types(types[2*i+1]) 334 try: 335 #ss.set_selection(sel) 336 ssubon.set_selection(sel) 337 except: 338 continue 339 #ll.append(numpy.array(ss._getspectrum(0))) 340 ll.append(numpy.array(ssubon._getspectrum(0))) 341 sel.reset() 342 ssubon.set_selection() 343 precal[keys[2*i+1]]=ll 344 #del ss 345 for j in range(len(ifnos)): 346 for k in range(len(polnos)): 347 sel.set_ifs(ifnos[j]) 348 sel.set_polarizations(polnos[k]) 349 try: 350 ress.set_selection(sel) 351 except: 352 continue 353 postcal.append(numpy.array(ress._getspectrum(0))) 354 sel.reset() 355 ress.set_selection() 356 del sel 357 # plot 358 print_log() 359 asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.') 360 print_log('WARN') 361 p=asaplotgui.asaplotgui() 362 #nr=min(6,len(ifnos)*len(polnos)) 363 nr=len(ifnos)*len(polnos) 364 titles=[] 365 btics=[] 366 if nr<4: 367 p.set_panels(rows=nr,cols=2,nplots=2*nr,ganged=False) 368 for i in range(2*nr): 369 b=False 370 if i >= 2*nr-2: 371 b=True 372 btics.append(b) 373 elif nr==4: 374 p.set_panels(rows=2,cols=4,nplots=8,ganged=False) 375 for i in range(2*nr): 376 b=False 377 if i >= 2*nr-4: 378 b=True 379 btics.append(b) 380 elif nr<7: 381 p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False) 382 for i in range(2*nr): 383 if i >= 2*nr-4: 384 b=True 385 btics.append(b) 386 else: 387 print_log() 388 asaplog.push('Only first 6 [if,pol] pairs are plotted.') 389 print_log('WARN') 390 nr=6 391 for i in range(2*nr): 392 b=False 393 if i >= 2*nr-4: 394 b=True 395 btics.append(b) 396 p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False) 397 for i in range(nr): 398 p.subplot(2*i) 399 p.color=0 400 title='raw data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)]) 401 titles.append(title) 402 #p.set_axes('title',title,fontsize=40) 403 ymin=1.0e100 404 ymax=-1.0e100 405 nchan=s.nchan() 406 edge=int(nchan*0.01) 407 for j in range(4): 408 spmin=min(precal[keys[j]][i][edge:nchan-edge]) 409 spmax=max(precal[keys[j]][i][edge:nchan-edge]) 410 ymin=min(ymin,spmin) 411 ymax=max(ymax,spmax) 412 for j in range(4): 413 if i==0: 414 p.set_line(label=keys[j]) 415 else: 416 p.legend() 417 p.plot(precal[keys[j]][i]) 418 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 419 if not btics[2*i]: 420 p.axes.set_xticks([]) 421 p.subplot(2*i+1) 422 p.color=0 423 title='cal data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)]) 424 titles.append(title) 425 #p.set_axes('title',title) 426 p.legend() 427 ymin=postcal[i][edge:nchan-edge].min() 428 ymax=postcal[i][edge:nchan-edge].max() 429 p.plot(postcal[i]) 430 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 431 if not btics[2*i+1]: 432 p.axes.set_xticks([]) 433 for i in range(2*nr): 434 p.subplot(i) 435 p.set_axes('title',titles[i],fontsize='medium') 436 x=raw_input('Accept calibration ([y]/n): ' ) 437 if x.upper() == 'N': 438 p.unmap() 439 del p 440 return scabtab 441 p.unmap() 442 del p 443 ### 238 444 ress._add_history("calps", varlist) 445 print_log() 239 446 return ress 240 447 241 448 @print_log_dec 242 def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0 ):449 def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 243 450 """ 244 451 Do full (but a pair of scans at time) processing of GBT Nod data … … 255 462 varlist = vars() 256 463 from asap._asap import stmath 464 from asap._asap import srctype 257 465 stm = stmath() 258 466 stm._setinsitu(False) 259 467 260 468 # check for the appropriate data 261 s = scantab.get_scan('*_nod*') 262 if s is None: 469 ## s = scantab.get_scan('*_nod*') 470 ## if s is None: 471 ## msg = "The input data appear to contain no Nod observing mode data." 472 ## if rcParams['verbose']: 473 ## #print msg 474 ## asaplog.push(msg) 475 ## print_log('ERROR') 476 ## return 477 ## else: 478 ## raise TypeError(msg) 479 s = scantab.copy() 480 sel = selector() 481 sel.set_types( srctype.nod ) 482 try: 483 s.set_selection( sel ) 484 except Exception, e: 263 485 msg = "The input data appear to contain no Nod observing mode data." 264 486 if rcParams['verbose']: 265 print msg 487 #print msg 488 asaplog.push(msg) 489 print_log('ERROR') 266 490 return 267 491 else: 268 492 raise TypeError(msg) 493 sel.reset() 494 del sel 495 del s 269 496 270 497 # need check correspondance of each beam with sig-ref ... … … 300 527 msg = "Need to supply a valid tau to use the supplied Tsys" 301 528 if rcParams['verbose']: 302 print msg 529 #print msg 530 asaplog.push(msg) 531 print_log('ERROR') 303 532 return 304 533 else: … … 307 536 scantab.recalc_azel() 308 537 resspec = scantable(stm._donod(scantab, pairScans, smooth, tsysval,tauval,tcalval)) 538 ### 539 if verify: 540 # get data 541 import numpy 542 precal={} 543 postcal=[] 544 keys=['','_calon'] 545 types=[srctype.nod,srctype.nodcal] 546 ifnos=list(scantab.getifnos()) 547 polnos=list(scantab.getpolnos()) 548 sel=selector() 549 ss = scantab.copy() 550 for i in range(2): 551 #ss=scantab.get_scan('*'+keys[i]) 552 ll=[] 553 ll2=[] 554 for j in range(len(ifnos)): 555 for k in range(len(polnos)): 556 sel.set_ifs(ifnos[j]) 557 sel.set_polarizations(polnos[k]) 558 sel.set_scans(pairScans[0]) 559 sel.set_types(types[i]) 560 try: 561 ss.set_selection(sel) 562 except: 563 continue 564 ll.append(numpy.array(ss._getspectrum(0))) 565 sel.reset() 566 ss.set_selection() 567 sel.set_ifs(ifnos[j]) 568 sel.set_polarizations(polnos[k]) 569 sel.set_scans(pairScans[1]) 570 sel.set_types(types[i]) 571 try: 572 ss.set_selection(sel) 573 except: 574 ll.pop() 575 continue 576 ll2.append(numpy.array(ss._getspectrum(0))) 577 sel.reset() 578 ss.set_selection() 579 key='%s%s' %(pairScans[0],keys[i]) 580 precal[key]=ll 581 key='%s%s' %(pairScans[1],keys[i]) 582 precal[key]=ll2 583 #del ss 584 keys=precal.keys() 585 for j in range(len(ifnos)): 586 for k in range(len(polnos)): 587 sel.set_ifs(ifnos[j]) 588 sel.set_polarizations(polnos[k]) 589 sel.set_scans(pairScans[0]) 590 try: 591 resspec.set_selection(sel) 592 except: 593 continue 594 postcal.append(numpy.array(resspec._getspectrum(0))) 595 sel.reset() 596 resspec.set_selection() 597 del sel 598 # plot 599 print_log() 600 asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.') 601 print_log('WARN') 602 p=asaplotgui.asaplotgui() 603 #nr=min(6,len(ifnos)*len(polnos)) 604 nr=len(ifnos)*len(polnos) 605 titles=[] 606 btics=[] 607 if nr<4: 608 p.set_panels(rows=nr,cols=2,nplots=2*nr,ganged=False) 609 for i in range(2*nr): 610 b=False 611 if i >= 2*nr-2: 612 b=True 613 btics.append(b) 614 elif nr==4: 615 p.set_panels(rows=2,cols=4,nplots=8,ganged=False) 616 for i in range(2*nr): 617 b=False 618 if i >= 2*nr-4: 619 b=True 620 btics.append(b) 621 elif nr<7: 622 p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False) 623 for i in range(2*nr): 624 if i >= 2*nr-4: 625 b=True 626 btics.append(b) 627 else: 628 print_log() 629 asaplog.push('Only first 6 [if,pol] pairs are plotted.') 630 print_log('WARN') 631 nr=6 632 for i in range(2*nr): 633 b=False 634 if i >= 2*nr-4: 635 b=True 636 btics.append(b) 637 p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False) 638 for i in range(nr): 639 p.subplot(2*i) 640 p.color=0 641 title='raw data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)]) 642 titles.append(title) 643 #p.set_axes('title',title,fontsize=40) 644 ymin=1.0e100 645 ymax=-1.0e100 646 nchan=scantab.nchan() 647 edge=int(nchan*0.01) 648 for j in range(4): 649 spmin=min(precal[keys[j]][i][edge:nchan-edge]) 650 spmax=max(precal[keys[j]][i][edge:nchan-edge]) 651 ymin=min(ymin,spmin) 652 ymax=max(ymax,spmax) 653 for j in range(4): 654 if i==0: 655 p.set_line(label=keys[j]) 656 else: 657 p.legend() 658 p.plot(precal[keys[j]][i]) 659 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 660 if not btics[2*i]: 661 p.axes.set_xticks([]) 662 p.subplot(2*i+1) 663 p.color=0 664 title='cal data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)]) 665 titles.append(title) 666 #p.set_axes('title',title) 667 p.legend() 668 ymin=postcal[i][edge:nchan-edge].min() 669 ymax=postcal[i][edge:nchan-edge].max() 670 p.plot(postcal[i]) 671 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 672 if not btics[2*i+1]: 673 p.axes.set_xticks([]) 674 for i in range(2*nr): 675 p.subplot(i) 676 p.set_axes('title',titles[i],fontsize='medium') 677 x=raw_input('Accept calibration ([y]/n): ' ) 678 if x.upper() == 'N': 679 p.unmap() 680 del p 681 return scabtab 682 p.unmap() 683 del p 684 ### 309 685 resspec._add_history("calnod",varlist) 686 print_log() 310 687 return resspec 311 688 312 689 @print_log_dec 313 def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0 ):690 def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 314 691 """ 315 692 Calibrate GBT frequency switched data. … … 333 710 varlist = vars() 334 711 from asap._asap import stmath 712 from asap._asap import srctype 335 713 stm = stmath() 336 714 stm._setinsitu(False) … … 348 726 349 727 resspec = scantable(stm._dofs(s, scannos, smooth, tsysval,tauval,tcalval)) 728 ### 729 if verify: 730 # get data 731 ssub = s.get_scan(scannos) 732 #ssubon = ssub.get_scan('*calon') 733 #ssuboff = ssub.get_scan('*[^calon]') 734 sel = selector() 735 sel.set_types( [srctype.foncal,srctype.foffcal] ) 736 ssub.set_selection( sel ) 737 ssubon = ssub.copy() 738 ssub.set_selection() 739 sel.reset() 740 sel.set_types( [srctype.fson,srctype.fsoff] ) 741 ssub.set_selection( sel ) 742 ssuboff = ssub.copy() 743 ssub.set_selection() 744 sel.reset() 745 import numpy 746 precal={} 747 postcal=[] 748 keys=['fs','fs_calon','fsr','fsr_calon'] 749 types=[srctype.fson,srctype.foncal,srctype.fsoff,srctype.foffcal] 750 ifnos=list(ssub.getifnos()) 751 polnos=list(ssub.getpolnos()) 752 for i in range(2): 753 #ss=ssuboff.get_scan('*'+keys[2*i]) 754 ll=[] 755 for j in range(len(ifnos)): 756 for k in range(len(polnos)): 757 sel.set_ifs(ifnos[j]) 758 sel.set_polarizations(polnos[k]) 759 sel.set_types(types[2*i]) 760 try: 761 #ss.set_selection(sel) 762 ssuboff.set_selection(sel) 763 except: 764 continue 765 ll.append(numpy.array(ss._getspectrum(0))) 766 sel.reset() 767 #ss.set_selection() 768 ssuboff.set_selection() 769 precal[keys[2*i]]=ll 770 #del ss 771 #ss=ssubon.get_scan('*'+keys[2*i+1]) 772 ll=[] 773 for j in range(len(ifnos)): 774 for k in range(len(polnos)): 775 sel.set_ifs(ifnos[j]) 776 sel.set_polarizations(polnos[k]) 777 sel.set_types(types[2*i+1]) 778 try: 779 #ss.set_selection(sel) 780 ssubon.set_selection(sel) 781 except: 782 continue 783 ll.append(numpy.array(ss._getspectrum(0))) 784 sel.reset() 785 #ss.set_selection() 786 ssubon.set_selection() 787 precal[keys[2*i+1]]=ll 788 #del ss 789 #sig=resspec.get_scan('*_fs') 790 #ref=resspec.get_scan('*_fsr') 791 sel.set_types( srctype.fson ) 792 resspec.set_selection( sel ) 793 sig=resspec.copy() 794 resspec.set_selection() 795 sel.reset() 796 sel.set_type( srctype.fsoff ) 797 resspec.set_selection( sel ) 798 ref=resspec.copy() 799 resspec.set_selection() 800 sel.reset() 801 for k in range(len(polnos)): 802 for j in range(len(ifnos)): 803 sel.set_ifs(ifnos[j]) 804 sel.set_polarizations(polnos[k]) 805 try: 806 sig.set_selection(sel) 807 postcal.append(numpy.array(sig._getspectrum(0))) 808 except: 809 ref.set_selection(sel) 810 postcal.append(numpy.array(ref._getspectrum(0))) 811 sel.reset() 812 resspec.set_selection() 813 del sel 814 # plot 815 print_log() 816 asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.') 817 print_log('WARN') 818 p=asaplotgui.asaplotgui() 819 #nr=min(6,len(ifnos)*len(polnos)) 820 nr=len(ifnos)/2*len(polnos) 821 titles=[] 822 btics=[] 823 if nr>3: 824 print_log() 825 asaplog.push('Only first 3 [if,pol] pairs are plotted.') 826 print_log('WARN') 827 nr=3 828 p.set_panels(rows=nr,cols=3,nplots=3*nr,ganged=False) 829 for i in range(3*nr): 830 b=False 831 if i >= 3*nr-3: 832 b=True 833 btics.append(b) 834 for i in range(nr): 835 p.subplot(3*i) 836 p.color=0 837 title='raw data IF%s,%s POL%s' % (ifnos[2*int(i/len(polnos))],ifnos[2*int(i/len(polnos))+1],polnos[i%len(polnos)]) 838 titles.append(title) 839 #p.set_axes('title',title,fontsize=40) 840 ymin=1.0e100 841 ymax=-1.0e100 842 nchan=s.nchan() 843 edge=int(nchan*0.01) 844 for j in range(4): 845 spmin=min(precal[keys[j]][i][edge:nchan-edge]) 846 spmax=max(precal[keys[j]][i][edge:nchan-edge]) 847 ymin=min(ymin,spmin) 848 ymax=max(ymax,spmax) 849 for j in range(4): 850 if i==0: 851 p.set_line(label=keys[j]) 852 else: 853 p.legend() 854 p.plot(precal[keys[j]][i]) 855 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 856 if not btics[3*i]: 857 p.axes.set_xticks([]) 858 p.subplot(3*i+1) 859 p.color=0 860 title='sig data IF%s POL%s' % (ifnos[2*int(i/len(polnos))],polnos[i%len(polnos)]) 861 titles.append(title) 862 #p.set_axes('title',title) 863 p.legend() 864 ymin=postcal[2*i][edge:nchan-edge].min() 865 ymax=postcal[2*i][edge:nchan-edge].max() 866 p.plot(postcal[2*i]) 867 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 868 if not btics[3*i+1]: 869 p.axes.set_xticks([]) 870 p.subplot(3*i+2) 871 p.color=0 872 title='ref data IF%s POL%s' % (ifnos[2*int(i/len(polnos))+1],polnos[i%len(polnos)]) 873 titles.append(title) 874 #p.set_axes('title',title) 875 p.legend() 876 ymin=postcal[2*i+1][edge:nchan-edge].min() 877 ymax=postcal[2*i+1][edge:nchan-edge].max() 878 p.plot(postcal[2*i+1]) 879 p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax)) 880 if not btics[3*i+2]: 881 p.axes.set_xticks([]) 882 for i in range(3*nr): 883 p.subplot(i) 884 p.set_axes('title',titles[i],fontsize='medium') 885 x=raw_input('Accept calibration ([y]/n): ' ) 886 if x.upper() == 'N': 887 p.unmap() 888 del p 889 return scabtab 890 p.unmap() 891 del p 892 ### 350 893 resspec._add_history("calfs",varlist) 894 print_log() 351 895 return resspec 352 353 896 354 897 @print_log_dec … … 380 923 msg = "Please give a list of scantables" 381 924 if rcParams['verbose']: 382 print msg 925 #print msg 926 asaplog.push(msg) 927 print_log('ERROR') 383 928 return 384 929 else: … … 386 931 s = scantable(stm._merge(lst)) 387 932 s._add_history("merge", varlist) 933 print_log() 388 934 return s 935 936 def calibrate( scantab, scannos=[], calmode='none', verify=None ): 937 """ 938 Calibrate data. 939 940 Parameters: 941 scantab: scantable 942 scannos: list of scan number 943 calmode: calibration mode 944 verify: verify calibration 945 """ 946 antname = scantab.get_antennaname() 947 if ( calmode == 'nod' ): 948 asaplog.push( 'Calibrating nod data.' ) 949 print_log() 950 scal = calnod( scantab, scannos=scannos, verify=verify ) 951 elif ( calmode == 'quotient' ): 952 asaplog.push( 'Calibrating using quotient.' ) 953 print_log() 954 scal = scantab.auto_quotient( verify=verify ) 955 elif ( calmode == 'ps' ): 956 asaplog.push( 'Calibrating %s position-switched data.' % antname ) 957 print_log() 958 if ( antname.find( 'APEX' ) != -1 ): 959 scal = apexcal( scantab, scannos, calmode, verify ) 960 elif ( antname.find( 'ALMA' ) != -1 or antname.find( 'OSF' ) != -1 ): 961 scal = almacal( scantab, scannos, calmode, verify ) 962 else: 963 scal = calps( scantab, scannos=scannos, verify=verify ) 964 elif ( calmode == 'fs' or calmode == 'fsotf' ): 965 asaplog.push( 'Calibrating %s frequency-switched data.' % antname ) 966 print_log() 967 if ( antname.find( 'APEX' ) != -1 ): 968 scal = apexcal( scantab, scannos, calmode, verify ) 969 elif ( antname.find( 'ALMA' ) != -1 or antname.find( 'OSF' ) != -1 ): 970 scal = almacal( scantab, scannos, calmode, verify ) 971 else: 972 scal = calfs( scantab, scannos=scannos, verify=verify ) 973 elif ( calmode == 'otf' ): 974 asaplog.push( 'Calibrating %s On-The-Fly data.' % antname ) 975 print_log() 976 scal = almacal( scantab, scannos, calmode, verify ) 977 else: 978 asaplog.push( 'No calibration.' ) 979 scal = scantab.copy() 980 981 return scal 982 983 def apexcal( scantab, scannos=[], calmode='none', verify=False ): 984 """ 985 Calibrate APEX data 986 987 Parameters: 988 scantab: scantable 989 scannos: list of scan number 990 calmode: calibration mode 991 992 verify: verify calibration 993 """ 994 from asap._asap import stmath 995 stm = stmath() 996 antname = scantab.get_antennaname() 997 ssub = scantab.get_scan( scannos ) 998 scal = scantable( stm.cwcal( ssub, calmode, antname ) ) 999 return scal 1000 1001 def almacal( scantab, scannos=[], calmode='none', verify=False ): 1002 """ 1003 Calibrate ALMA data 1004 1005 Parameters: 1006 scantab: scantable 1007 scannos: list of scan number 1008 calmode: calibration mode 1009 1010 verify: verify calibration 1011 """ 1012 from asap._asap import stmath 1013 stm = stmath() 1014 ssub = scantab.get_scan( scannos ) 1015 scal = scantable( stm.almacal( ssub, calmode ) ) 1016 return scal 1017 1018 def splitant(filename, outprefix='',overwrite=False): 1019 """ 1020 Split Measurement set by antenna name, save data as a scantables, 1021 and return a list of filename. 1022 Notice this method can only be available from CASA. 1023 Prameter 1024 filename: the name of Measurement set to be read. 1025 outprefix: the prefix of output scantable name. 1026 the names of output scantable will be 1027 outprefix.antenna1, outprefix.antenna2, .... 1028 If not specified, outprefix = filename is assumed. 1029 overwrite If the file should be overwritten if it exists. 1030 The default False is to return with warning 1031 without writing the output. USE WITH CARE. 1032 1033 """ 1034 # Import the table toolkit from CASA 1035 try: 1036 import casac 1037 except ImportError: 1038 if rcParams['verbose']: 1039 #print "failed to load casa" 1040 print_log() 1041 asaplog.push("failed to load casa") 1042 print_log('ERROR') 1043 else: raise 1044 return False 1045 try: 1046 tbtool = casac.homefinder.find_home_by_name('tableHome') 1047 tb = tbtool.create() 1048 tb2 = tbtool.create() 1049 except: 1050 if rcParams['verbose']: 1051 #print "failed to load a table tool:\n", e 1052 print_log() 1053 asaplog.push("failed to load table tool") 1054 print_log('ERROR') 1055 else: raise 1056 return False 1057 # Check the input filename 1058 if isinstance(filename, str): 1059 import os.path 1060 filename = os.path.expandvars(filename) 1061 filename = os.path.expanduser(filename) 1062 if not os.path.exists(filename): 1063 s = "File '%s' not found." % (filename) 1064 if rcParams['verbose']: 1065 print_log() 1066 asaplog.push(s) 1067 print_log('ERROR') 1068 return 1069 raise IOError(s) 1070 # check if input file is MS 1071 if not os.path.isdir(filename) \ 1072 or not os.path.exists(filename+'/ANTENNA') \ 1073 or not os.path.exists(filename+'/table.f1'): 1074 s = "File '%s' is not a Measurement set." % (filename) 1075 if rcParams['verbose']: 1076 print_log() 1077 asaplog.push(s) 1078 print_log('ERROR') 1079 return 1080 raise IOError(s) 1081 else: 1082 s = "The filename should be string. " 1083 if rcParams['verbose']: 1084 print_log() 1085 asaplog.push(s) 1086 print_log('ERROR') 1087 return 1088 raise TypeError(s) 1089 # Check out put file name 1090 outname='' 1091 if len(outprefix) > 0: prefix=outprefix+'.' 1092 else: 1093 prefix=filename.rstrip('/') 1094 # Now do the actual splitting. 1095 outfiles=[] 1096 tb.open(tablename=filename+'/ANTENNA',nomodify=True) 1097 nant=tb.nrows() 1098 antnames=tb.getcol('NAME',0,nant,1) 1099 antpos=tb.getcol('POSITION',0,nant,1).transpose() 1100 tb.close() 1101 tb.open(tablename=filename,nomodify=True) 1102 ant1=tb.getcol('ANTENNA1',0,-1,1) 1103 tb.close() 1104 for antid in set(ant1): 1105 scan=scantable(filename,average=False,getpt=True,antenna=int(antid)) 1106 outname=prefix+antnames[antid]+'.asap' 1107 scan.save(outname,format='ASAP',overwrite=overwrite) 1108 del scan 1109 outfiles.append(outname) 1110 del tb, tb2 1111 return outfiles 1112 1113 def _array2dOp( scan, value, mode="ADD", tsys=False ): 1114 """ 1115 This function is workaround on the basic operation of scantable 1116 with 2 dimensional float list. 1117 1118 scan: scantable operand 1119 value: float list operand 1120 mode: operation mode (ADD, SUB, MUL, DIV) 1121 tsys: if True, operate tsys as well 1122 """ 1123 nrow = scan.nrow() 1124 s = None 1125 if len( value ) == 1: 1126 from asap._asap import stmath 1127 stm = stmath() 1128 s = scantable( stm._arrayop( scan.copy(), value[0], mode, tsys ) ) 1129 del stm 1130 elif len( value ) != nrow: 1131 asaplog.push( 'len(value) must be 1 or conform to scan.nrow()' ) 1132 print_log( 'ERROR' ) 1133 else: 1134 from asap._asap import stmath 1135 stm = stmath() 1136 # insitu must be True 1137 stm._setinsitu( True ) 1138 s = scan.copy() 1139 sel = selector() 1140 for irow in range( nrow ): 1141 sel.set_rows( irow ) 1142 s.set_selection( sel ) 1143 if len( value[irow] ) == 1: 1144 stm._unaryop( s, value[irow][0], mode, tsys ) 1145 else: 1146 stm._arrayop( s, value[irow], mode, tsys, 'channel' ) 1147 s.set_selection() 1148 sel.reset() 1149 del sel 1150 del stm 1151 return s 1152 1153 1154 -
trunk/python/asapplotter.py
r1739 r1819 1 1 from asap import rcParams, print_log, print_log_dec 2 2 from asap import selector, scantable 3 from asap import asaplog 3 4 import matplotlib.axes 4 5 from matplotlib.font_manager import FontProperties … … 21 22 self._visible = visible 22 23 self._plotter = self._newplotter(**kwargs) 24 # additional tool bar 25 self._plotter.figmgr.casabar=self._newcasabar() 23 26 24 27 self._panelling = None … … 43 46 self._hist = rcParams['plotter.histogram'] 44 47 self._fp = FontProperties() 48 self._panellayout = self.set_panellayout(refresh=False) 45 49 46 50 def _translate(self, instr): … … 53 57 54 58 def _newplotter(self, **kwargs): 55 if self._visible: 59 backend=matplotlib.get_backend() 60 if not self._visible: 61 from asap.asaplot import asaplot 62 elif backend == 'TkAgg': 56 63 from asap.asaplotgui import asaplotgui as asaplot 64 elif backend == 'Qt4Agg': 65 from asap.asaplotgui_qt4 import asaplotgui as asaplot 66 elif backend == 'GTkAgg': 67 from asap.asaplotgui_gtk import asaplotgui as asaplot 57 68 else: 58 69 from asap.asaplot import asaplot 59 70 return asaplot(**kwargs) 71 72 def _newcasabar(self): 73 backend=matplotlib.get_backend() 74 if self._visible and backend == "TkAgg": 75 from asap.casatoolbar import CustomToolbarTkAgg 76 return CustomToolbarTkAgg(self) 77 else: return None 60 78 61 79 @print_log_dec … … 72 90 """ 73 91 if self._plotter.is_dead: 92 if hasattr(self._plotter.figmgr,'casabar'): 93 del self._plotter.figmgr.casabar 74 94 self._plotter = self._newplotter() 95 self._plotter.figmgr.casabar=self._newcasabar() 75 96 self._plotter.hold() 76 97 self._plotter.clear() 77 from asap import scantable78 98 if not self._data and not scan: 79 99 msg = "Input is not a scantable" 80 100 if rcParams['verbose']: 81 print msg 101 #print msg 102 asaplog.push( msg ) 103 print_log( 'ERROR' ) 82 104 return 83 105 raise TypeError(msg) 84 if isinstance(scan, scantable): 85 if self._data is not None: 86 if scan != self._data: 87 self._data = scan 88 # reset 89 self._reset() 90 else: 91 self._data = scan 92 self._reset() 93 # ranges become invalid when unit changes 94 if self._abcunit and self._abcunit != self._data.get_unit(): 95 self._minmaxx = None 96 self._minmaxy = None 97 self._abcunit = self._data.get_unit() 98 self._datamask = None 106 if scan: self.set_data(scan,refresh=False) 99 107 self._plot(self._data) 100 108 if self._minmaxy is not None: 101 109 self._plotter.set_limits(ylim=self._minmaxy) 110 if self._plotter.figmgr.casabar: self._plotter.figmgr.casabar.enable_button() 102 111 self._plotter.release() 103 112 self._plotter.tidy() 104 113 self._plotter.show(hardrefresh=False) 114 print_log() 105 115 return 106 116 … … 238 248 dpos = (pos[0][1], pos[1][1]) 239 249 args = dpos + args 240 241 250 self._axes_callback("axhspan", *args, **kwargs) 242 251 # hack to preventy mpl from redrawing the patch … … 265 274 # end matplotlib.axes fowarding functions 266 275 267 268 def set_mode(self, stacking=None, panelling=None): 276 def set_data(self, scan, refresh=True): 277 """ 278 Set a scantable to plot. 279 Parameters: 280 scan: a scantable 281 refresh: True (default) or False. If True, the plot is 282 replotted based on the new parameter setting(s). 283 Otherwise,the parameter(s) are set without replotting. 284 Note: 285 The user specified masks and data selections will be reset 286 if a new scantable is set. This method should be called before 287 setting data selections (set_selection) and/or masks (set_mask). 288 """ 289 from asap import scantable 290 if isinstance(scan, scantable): 291 if self._data is not None: 292 if scan != self._data: 293 self._data = scan 294 # reset 295 self._reset() 296 msg = "A new scantable is set to the plotter. The masks and data selections are reset." 297 asaplog.push( msg ) 298 print_log( 'INFO' ) 299 else: 300 self._data = scan 301 self._reset() 302 else: 303 msg = "Input is not a scantable" 304 if rcParams['verbose']: 305 #print msg 306 asaplog.push( msg ) 307 print_log( 'ERROR' ) 308 return 309 raise TypeError(msg) 310 311 # ranges become invalid when unit changes 312 if self._abcunit and self._abcunit != self._data.get_unit(): 313 self._minmaxx = None 314 self._minmaxy = None 315 self._abcunit = self._data.get_unit() 316 self._datamask = None 317 if refresh: self.plot() 318 319 320 def set_mode(self, stacking=None, panelling=None, refresh=True): 269 321 """ 270 322 Set the plots look and feel, i.e. what you want to see on the plot. … … 274 326 panelling: tell the plotter which variable to plot 275 327 across multiple panels (default 'scan' 328 refresh: True (default) or False. If True, the plot is 329 replotted based on the new parameter setting(s). 330 Otherwise,the parameter(s) are set without replotting. 276 331 Note: 277 332 Valid modes are: … … 286 341 not self.set_stacking(stacking): 287 342 if rcParams['verbose']: 288 print msg 343 #print msg 344 asaplog.push( msg ) 345 print_log( 'ERROR' ) 289 346 return 290 347 else: 291 348 raise TypeError(msg) 292 if self._data: self.plot(self._data)349 if refresh and self._data: self.plot(self._data) 293 350 return 294 351 … … 304 361 return False 305 362 306 def set_layout(self,rows=None,cols=None ):363 def set_layout(self,rows=None,cols=None,refresh=True): 307 364 """ 308 365 Set the multi-panel layout, i.e. how many rows and columns plots … … 311 368 rows: The number of rows of plots 312 369 cols: The number of columns of plots 370 refresh: True (default) or False. If True, the plot is 371 replotted based on the new parameter setting(s). 372 Otherwise,the parameter(s) are set without replotting. 313 373 Note: 314 374 If no argument is given, the potter reverts to its auto-plot … … 317 377 self._rows = rows 318 378 self._cols = cols 319 if self._data: self.plot(self._data)379 if refresh and self._data: self.plot(self._data) 320 380 return 321 381 … … 331 391 return False 332 392 333 def set_range(self,xstart=None,xend=None,ystart=None,yend=None ):393 def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True): 334 394 """ 335 395 Set the range of interest on the abcissa of the plot 336 396 Parameters: 337 397 [x,y]start,[x,y]end: The start and end points of the 'zoom' window 398 refresh: True (default) or False. If True, the plot is 399 replotted based on the new parameter setting(s). 400 Otherwise,the parameter(s) are set without replotting. 338 401 Note: 339 402 These become non-sensical when the unit changes. … … 349 412 else: 350 413 self._minmaxy = [ystart,yend] 351 if self._data: self.plot(self._data)414 if refresh and self._data: self.plot(self._data) 352 415 return 353 416 354 def set_legend(self, mp=None, fontsize = None, mode = 0 ):417 def set_legend(self, mp=None, fontsize = None, mode = 0, refresh=True): 355 418 """ 356 419 Specify a mapping for the legend instead of using the default … … 376 439 9: upper center 377 440 10: center 441 refresh: True (default) or False. If True, the plot is 442 replotted based on the new parameter setting(s). 443 Otherwise,the parameter(s) are set without replotting. 378 444 379 445 Example: … … 390 456 from matplotlib import rc as rcp 391 457 rcp('legend', fontsize=fontsize) 392 if self._data: 393 self.plot(self._data) 458 if refresh and self._data: self.plot(self._data) 394 459 return 395 460 396 def set_title(self, title=None, fontsize=None ):461 def set_title(self, title=None, fontsize=None, refresh=True): 397 462 """ 398 463 Set the title of the plot. If multiple panels are plotted, 399 464 multiple titles have to be specified. 465 Parameters: 466 refresh: True (default) or False. If True, the plot is 467 replotted based on the new parameter setting(s). 468 Otherwise,the parameter(s) are set without replotting. 400 469 Example: 401 470 # two panels are visible on the plotter … … 406 475 from matplotlib import rc as rcp 407 476 rcp('axes', titlesize=fontsize) 408 if self._data: self.plot(self._data)477 if refresh and self._data: self.plot(self._data) 409 478 return 410 479 411 def set_ordinate(self, ordinate=None, fontsize=None ):480 def set_ordinate(self, ordinate=None, fontsize=None, refresh=True): 412 481 """ 413 482 Set the y-axis label of the plot. If multiple panels are plotted, … … 416 485 ordinate: a list of ordinate labels. None (default) let 417 486 data determine the labels 487 refresh: True (default) or False. If True, the plot is 488 replotted based on the new parameter setting(s). 489 Otherwise,the parameter(s) are set without replotting. 418 490 Example: 419 491 # two panels are visible on the plotter … … 425 497 rcp('axes', labelsize=fontsize) 426 498 rcp('ytick', labelsize=fontsize) 427 if self._data: self.plot(self._data)499 if refresh and self._data: self.plot(self._data) 428 500 return 429 501 430 def set_abcissa(self, abcissa=None, fontsize=None ):502 def set_abcissa(self, abcissa=None, fontsize=None, refresh=True): 431 503 """ 432 504 Set the x-axis label of the plot. If multiple panels are plotted, … … 435 507 abcissa: a list of abcissa labels. None (default) let 436 508 data determine the labels 509 refresh: True (default) or False. If True, the plot is 510 replotted based on the new parameter setting(s). 511 Otherwise,the parameter(s) are set without replotting. 437 512 Example: 438 513 # two panels are visible on the plotter … … 444 519 rcp('axes', labelsize=fontsize) 445 520 rcp('xtick', labelsize=fontsize) 446 if self._data: self.plot(self._data)521 if refresh and self._data: self.plot(self._data) 447 522 return 448 523 449 def set_colors(self, colmap ):524 def set_colors(self, colmap, refresh=True): 450 525 """ 451 526 Set the colours to be used. The plotter will cycle through … … 453 528 Parameters: 454 529 colmap: a list of colour names 530 refresh: True (default) or False. If True, the plot is 531 replotted based on the new parameter setting(s). 532 Otherwise,the parameter(s) are set without replotting. 455 533 Example: 456 534 plotter.set_colors("red green blue") … … 462 540 colmap = colmap.split() 463 541 self._plotter.palette(0, colormap=colmap) 464 if self._data: self.plot(self._data)542 if refresh and self._data: self.plot(self._data) 465 543 466 544 # alias for english speakers 467 545 set_colours = set_colors 468 546 469 def set_histogram(self, hist=True, linewidth=None ):547 def set_histogram(self, hist=True, linewidth=None, refresh=True): 470 548 """ 471 549 Enable/Disable histogram-like plotting. … … 474 552 is taken from the .asaprc setting 475 553 plotter.histogram 554 refresh: True (default) or False. If True, the plot is 555 replotted based on the new parameter setting(s). 556 Otherwise,the parameter(s) are set without replotting. 476 557 """ 477 558 self._hist = hist … … 479 560 from matplotlib import rc as rcp 480 561 rcp('lines', linewidth=linewidth) 481 if self._data: self.plot(self._data)482 483 def set_linestyles(self, linestyles=None, linewidth=None ):562 if refresh and self._data: self.plot(self._data) 563 564 def set_linestyles(self, linestyles=None, linewidth=None, refresh=True): 484 565 """ 485 566 Set the linestyles to be used. The plotter will cycle through … … 491 572 'dashdotdot' and 'dashdashdot' are 492 573 possible 493 574 refresh: True (default) or False. If True, the plot is 575 replotted based on the new parameter setting(s). 576 Otherwise,the parameter(s) are set without replotting. 494 577 Example: 495 578 plotter.set_colors("black") … … 505 588 from matplotlib import rc as rcp 506 589 rcp('lines', linewidth=linewidth) 507 if self._data: self.plot(self._data)508 509 def set_font(self, **kwargs):590 if refresh and self._data: self.plot(self._data) 591 592 def set_font(self, refresh=True,**kwargs): 510 593 """ 511 594 Set font properties. … … 516 599 size: the 'general' font size, individual elements can be adjusted 517 600 seperately 601 refresh: True (default) or False. If True, the plot is 602 replotted based on the new parameter setting(s). 603 Otherwise,the parameter(s) are set without replotting. 518 604 """ 519 605 from matplotlib import rc as rcp … … 523 609 fdict[k] = v 524 610 self._fp = FontProperties(**fdict) 525 if self._data: 526 self.plot() 611 if refresh and self._data: self.plot(self._data) 612 613 def set_panellayout(self,layout=[],refresh=True): 614 """ 615 Set the layout of subplots. 616 Parameters: 617 layout: a list of subplots layout in figure coordinate (0-1), 618 i.e., fraction of the figure width or height. 619 The order of elements should be: 620 [left, bottom, right, top, horizontal space btw panels, 621 vertical space btw panels]. 622 refresh: True (default) or False. If True, the plot is 623 replotted based on the new parameter setting(s). 624 Otherwise,the parameter(s) are set without replotting. 625 Note 626 * When layout is not specified, the values are reset to the defaults 627 of matplotlib. 628 * If any element is set to be None, the current value is adopted. 629 """ 630 if layout == []: self._panellayout=self._reset_panellayout() 631 else: 632 self._panellayout=[None]*6 633 self._panellayout[0:len(layout)]=layout 634 #print "panel layout set to ",self._panellayout 635 if refresh and self._data: self.plot(self._data) 636 637 def _reset_panellayout(self): 638 ks=map(lambda x: 'figure.subplot.'+x, 639 ['left','bottom','right','top','hspace','wspace']) 640 return map(matplotlib.rcParams.get,ks) 527 641 528 642 def plot_lines(self, linecat=None, doppler=0.0, deltachan=10, rotate=90.0, … … 622 736 623 737 624 def set_mask(self, mask=None, selection=None ):738 def set_mask(self, mask=None, selection=None, refresh=True): 625 739 """ 626 740 Set a plotting mask for a specific polarization. … … 629 743 mask: a mask from scantable.create_mask 630 744 selection: the spectra to apply the mask to. 745 refresh: True (default) or False. If True, the plot is 746 replotted based on the new parameter setting(s). 747 Otherwise,the parameter(s) are set without replotting. 631 748 Example: 632 749 select = selector() … … 637 754 msg = "Can only set mask after a first call to plot()" 638 755 if rcParams['verbose']: 639 print msg 756 #print msg 757 asaplog.push( msg ) 758 print_log( 'ERROR' ) 640 759 return 641 760 else: … … 657 776 else: 658 777 self._maskselection = None 659 self.plot(self._data)778 if refresh: self.plot(self._data) 660 779 661 780 def _slice_indeces(self, data): … … 671 790 inc = -1 672 791 # find min index 673 while start > 0 and data[start] < mn: 674 start+= inc 792 #while start > 0 and data[start] < mn: 793 # start+= inc 794 minind=start 795 for ind in xrange(start,end+inc,inc): 796 if data[ind] > mn: break 797 minind=ind 675 798 # find max index 676 while end > 0 and data[end] > mx: 677 end-=inc 678 if end > 0: end +=1 799 #while end > 0 and data[end] > mx: 800 # end-=inc 801 #if end > 0: end +=1 802 maxind=end 803 for ind in xrange(end,start-inc,-inc): 804 if data[ind] < mx: break 805 maxind=ind 806 start=minind 807 end=maxind 679 808 if start > end: 680 return end,start 681 return start,end 809 return end,start+1 810 elif start < end: 811 return start,end+1 812 else: 813 return start,end 682 814 683 815 def _reset(self): … … 708 840 maxpanel, maxstack = 16,16 709 841 if n > maxpanel or nstack > maxstack: 710 from asap import asaplog711 842 maxn = 0 712 843 if nstack > maxstack: maxn = maxstack … … 715 846 "Selecting first %d selections..." % (maxn, maxn) 716 847 asaplog.push(msg) 717 print_log( )848 print_log('WARN') 718 849 n = min(n,maxpanel) 719 850 nstack = min(nstack,maxstack) 720 851 if n > 1: 721 852 ganged = rcParams['plotter.ganged'] 853 if self._panelling == 'i': 854 ganged = False 722 855 if self._rows and self._cols: 723 856 n = min(n,self._rows*self._cols) 724 857 self._plotter.set_panels(rows=self._rows,cols=self._cols, 725 nplots=n,ganged=ganged) 858 # nplots=n,ganged=ganged) 859 nplots=n,layout=self._panellayout,ganged=ganged) 726 860 else: 727 self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged) 861 # self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged) 862 self._plotter.set_panels(rows=n,cols=0,nplots=n,layout=self._panellayout,ganged=ganged) 728 863 else: 729 self._plotter.set_panels() 864 # self._plotter.set_panels() 865 self._plotter.set_panels(layout=self._panellayout) 730 866 r=0 731 867 nr = scan.nrow() … … 799 935 ylim= self._minmaxy or [ma.minimum(y),ma.maximum(y)] 800 936 allylim += ylim 937 else: 938 xlim = self._minmaxx or [] 939 allxlim += xlim 940 ylim= self._minmaxy or [] 941 allylim += ylim 801 942 stackcount += 1 802 943 # last in colour stack -> autoscale x 803 if stackcount == nstack :944 if stackcount == nstack and len(allxlim) > 0: 804 945 allxlim.sort() 805 self._plotter. axes.set_xlim([allxlim[0],allxlim[-1]])946 self._plotter.subplots[panelcount-1]['axes'].set_xlim([allxlim[0],allxlim[-1]]) 806 947 # clear 807 948 allxlim =[] … … 813 954 if (panelcount == n) and (stackcount == nstack): 814 955 # last panel -> autoscale y if ganged 815 if rcParams['plotter.ganged'] :956 if rcParams['plotter.ganged'] and len(allylim) > 0: 816 957 allylim.sort() 817 958 self._plotter.set_limits(ylim=[allylim[0],allylim[-1]]) … … 820 961 #reset the selector to the scantable's original 821 962 scan.set_selection(savesel) 822 if self._fp is not None: 963 964 #temporary switch-off for older matplotlib 965 #if self._fp is not None: 966 if self._fp is not None and getattr(self._plotter.figure,'findobj',False): 823 967 for o in self._plotter.figure.findobj(Text): 824 968 o.set_fontproperties(self._fp) 825 969 826 827 970 def set_selection(self, selection=None, refresh=True, **kw): 971 """ 972 Parameters: 973 selection: a selector object (default unset the selection) 974 refresh: True (default) or False. If True, the plot is 975 replotted based on the new parameter setting(s). 976 Otherwise,the parameter(s) are set without replotting. 977 """ 828 978 if selection is None: 829 979 # reset … … 845 995 order = [d0[self._panelling],d0[self._stacking]] 846 996 self._selection.set_order(order) 847 if self._data and refresh: self.plot(self._data)997 if refresh and self._data: self.plot(self._data) 848 998 849 999 def _get_selected_n(self, scan): … … 868 1018 poleval = scan._getpollabel(scan.getpol(row),scan.poltype()) 869 1019 d = {'b': "Beam "+str(scan.getbeam(row)), 870 's': scan._getsourcename(row), 1020 #'s': scan._getsourcename(row), 1021 's': "Scan "+str(scan.getscan(row))+\ 1022 " ("+str(scan._getsourcename(row))+")", 871 1023 'i': "IF"+str(scan.getif(row)), 872 1024 'p': poleval, … … 874 1026 return userlabel or d[mode] 875 1027 876 def plotazel(self): 1028 def plotazel(self, scan=None, outfile=None): 1029 #def plotazel(self): 877 1030 """ 878 1031 plot azimuth and elevation versus time of a scantable … … 883 1036 from matplotlib.ticker import MultipleLocator 884 1037 from numpy import array, pi 1038 self._data = scan 1039 self._outfile = outfile 885 1040 dates = self._data.get_time(asdatetime=True) 886 1041 t = PL.date2num(dates) … … 889 1044 PL.ioff() 890 1045 PL.clf() 1046 # Adjust subplot layouts 1047 if len(self._panellayout) !=6: self.set_panellayout(refresh=False) 1048 lef, bot, rig, top, wsp, hsp = self._panellayout 1049 PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top, 1050 wspace=wsp,hspace=hsp) 1051 891 1052 tdel = max(t) - min(t) 892 1053 ax = PL.subplot(2,1,1) … … 910 1071 911 1072 PL.title(dstr) 912 PL.plot_date(t,el,'b,', tz=tz) 1073 if tdel == 0.0: 1074 th = (t - PL.floor(t))*24.0 1075 PL.plot(th,el,'o',markersize=2, markerfacecolor='b', markeredgecolor='b') 1076 else: 1077 PL.plot_date(t,el,'o', markersize=2, markerfacecolor='b', markeredgecolor='b',tz=tz) 1078 #ax.grid(True) 1079 ax.xaxis.set_major_formatter(timefmt) 1080 ax.xaxis.set_major_locator(majloc) 1081 ax.xaxis.set_minor_locator(minloc) 913 1082 ax.yaxis.grid(True) 914 1083 yloc = MultipleLocator(30) 1084 ax.set_ylim(0,90) 1085 ax.yaxis.set_major_locator(yloc) 915 1086 if tdel > 1.0: 916 1087 labels = ax.get_xticklabels() 917 1088 # PL.setp(labels, fontsize=10, rotation=45) 918 1089 PL.setp(labels, fontsize=10) 1090 919 1091 # Az plot 920 1092 az = array(self._data.get_azimuth())*180./pi … … 923 1095 if az[irow] < 0: az[irow] += 360.0 924 1096 925 ax2 = ax.figure.add_subplot(2,1,2, sharex=ax) 926 ax2.set_xlabel('Time (UT)') 927 ax2.set_ylabel('Az [deg.]') 928 ax2.plot_date(t,az,'b,', tz=tz) 1097 ax2 = PL.subplot(2,1,2) 1098 #PL.xlabel('Time (UT [hour])') 1099 PL.ylabel('Az [deg.]') 1100 if tdel == 0.0: 1101 PL.plot(th,az,'o',markersize=2, markeredgecolor='b',markerfacecolor='b') 1102 else: 1103 PL.plot_date(t,az,'o', markersize=2,markeredgecolor='b',markerfacecolor='b',tz=tz) 1104 ax2.xaxis.set_major_formatter(timefmt) 1105 ax2.xaxis.set_major_locator(majloc) 1106 ax2.xaxis.set_minor_locator(minloc) 1107 #ax2.grid(True) 1108 ax2.set_ylim(0,360) 929 1109 ax2.yaxis.grid(True) 930 # set this last as x axis is shared 931 ax.xaxis.set_major_formatter(timefmt) 932 ax.xaxis.set_major_locator(majloc) 933 ax.xaxis.set_minor_locator(minloc) 1110 #hfmt = DateFormatter('%H') 1111 #hloc = HourLocator() 1112 yloc = MultipleLocator(60) 1113 ax2.yaxis.set_major_locator(yloc) 1114 if tdel > 1.0: 1115 labels = ax2.get_xticklabels() 1116 PL.setp(labels, fontsize=10) 1117 PL.xlabel('Time (UT [day])') 1118 else: 1119 PL.xlabel('Time (UT [hour])') 1120 934 1121 PL.ion() 935 1122 PL.draw() 936 937 def plotpointing(self): 1123 if (self._outfile is not None): 1124 PL.savefig(self._outfile) 1125 1126 def plotpointing(self, scan=None, outfile=None): 1127 #def plotpointing(self): 938 1128 """ 939 1129 plot telescope pointings 940 1130 """ 941 1131 from matplotlib import pylab as PL 942 from numpy import array 1132 from numpy import array, pi 1133 self._data = scan 1134 self._outfile = outfile 943 1135 dir = array(self._data.get_directionval()).transpose() 944 1136 ra = dir[0]*180./pi 945 1137 dec = dir[1]*180./pi 946 1138 PL.cla() 947 PL.ioff()1139 #PL.ioff() 948 1140 PL.clf() 949 ax = PL.axes([0.1,0.1,0.8,0.8]) 950 ax = PL.axes([0.1,0.1,0.8,0.8]) 1141 # Adjust subplot layouts 1142 if len(self._panellayout) !=6: self.set_panellayout(refresh=False) 1143 lef, bot, rig, top, wsp, hsp = self._panellayout 1144 PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top, 1145 wspace=wsp,hspace=hsp) 1146 ax = PL.gca() 1147 #ax = PL.axes([0.1,0.1,0.8,0.8]) 1148 #ax = PL.axes([0.1,0.1,0.8,0.8]) 951 1149 ax.set_aspect('equal') 952 1150 PL.plot(ra, dec, 'b,') … … 956 1154 [xmin,xmax,ymin,ymax] = PL.axis() 957 1155 PL.axis([xmax,xmin,ymin,ymax]) 958 PL.ion()1156 #PL.ion() 959 1157 PL.draw() 1158 if (self._outfile is not None): 1159 PL.savefig(self._outfile) 1160 1161 # plot total power data 1162 # plotting in time is not yet implemented.. 1163 def plottp(self, scan=None, outfile=None): 1164 if self._plotter.is_dead: 1165 if hasattr(self._plotter.figmgr,'casabar'): 1166 del self._plotter.figmgr.casabar 1167 self._plotter = self._newplotter() 1168 self._plotter.figmgr.casabar=self._newcasabar() 1169 self._plotter.hold() 1170 self._plotter.clear() 1171 from asap import scantable 1172 if not self._data and not scan: 1173 msg = "Input is not a scantable" 1174 if rcParams['verbose']: 1175 #print msg 1176 asaplog.push( msg ) 1177 print_log( 'ERROR' ) 1178 return 1179 raise TypeError(msg) 1180 if isinstance(scan, scantable): 1181 if self._data is not None: 1182 if scan != self._data: 1183 self._data = scan 1184 # reset 1185 self._reset() 1186 else: 1187 self._data = scan 1188 self._reset() 1189 # ranges become invalid when abcissa changes? 1190 #if self._abcunit and self._abcunit != self._data.get_unit(): 1191 # self._minmaxx = None 1192 # self._minmaxy = None 1193 # self._abcunit = self._data.get_unit() 1194 # self._datamask = None 1195 1196 # Adjust subplot layouts 1197 if len(self._panellayout) !=6: self.set_panellayout(refresh=False) 1198 lef, bot, rig, top, wsp, hsp = self._panellayout 1199 self._plotter.figure.subplots_adjust( 1200 left=lef,bottom=bot,right=rig,top=top,wspace=wsp,hspace=hsp) 1201 if self._plotter.figmgr.casabar: self._plotter.figmgr.casabar.disable_button() 1202 self._plottp(self._data) 1203 if self._minmaxy is not None: 1204 self._plotter.set_limits(ylim=self._minmaxy) 1205 self._plotter.release() 1206 self._plotter.tidy() 1207 self._plotter.show(hardrefresh=False) 1208 print_log() 1209 return 1210 1211 def _plottp(self,scan): 1212 """ 1213 private method for plotting total power data 1214 """ 1215 from numpy import ma, array, arange, logical_not 1216 r=0 1217 nr = scan.nrow() 1218 a0,b0 = -1,-1 1219 allxlim = [] 1220 allylim = [] 1221 y=[] 1222 self._plotter.set_panels() 1223 self._plotter.palette(0) 1224 #title 1225 #xlab = self._abcissa and self._abcissa[panelcount] \ 1226 # or scan._getabcissalabel() 1227 #ylab = self._ordinate and self._ordinate[panelcount] \ 1228 # or scan._get_ordinate_label() 1229 xlab = self._abcissa or 'row number' #or Time 1230 ylab = self._ordinate or scan._get_ordinate_label() 1231 self._plotter.set_axes('xlabel',xlab) 1232 self._plotter.set_axes('ylabel',ylab) 1233 lbl = self._get_label(scan, r, 's', self._title) 1234 if isinstance(lbl, list) or isinstance(lbl, tuple): 1235 # if 0 <= panelcount < len(lbl): 1236 # lbl = lbl[panelcount] 1237 # else: 1238 # get default label 1239 lbl = self._get_label(scan, r, self._panelling, None) 1240 self._plotter.set_axes('title',lbl) 1241 y=array(scan._get_column(scan._getspectrum,-1)) 1242 m = array(scan._get_column(scan._getmask,-1)) 1243 y = ma.masked_array(y,mask=logical_not(array(m,copy=False))) 1244 x = arange(len(y)) 1245 # try to handle spectral data somewhat... 1246 l,m = y.shape 1247 if m > 1: 1248 y=y.mean(axis=1) 1249 plotit = self._plotter.plot 1250 llbl = self._get_label(scan, r, self._stacking, None) 1251 self._plotter.set_line(label=llbl) 1252 if len(x) > 0: 1253 plotit(x,y) 1254 1255 1256 # forwards to matplotlib.Figure.text 1257 def figtext(self, *args, **kwargs): 1258 """ 1259 Add text to figure at location x,y (relative 0-1 coords). 1260 This method forwards *args and **kwargs to a Matplotlib method, 1261 matplotlib.Figure.text. 1262 See the method help for detailed information. 1263 """ 1264 self._plotter.text(*args, **kwargs) 1265 # end matplotlib.Figure.text forwarding function 1266 1267 1268 # printing header information 1269 def print_header(self, plot=True, fontsize=9, logger=False, selstr='', extrastr=''): 1270 """ 1271 print data (scantable) header on the plot and/or logger. 1272 Parameters: 1273 plot: whether or not print header info on the plot. 1274 fontsize: header font size (valid only plot=True) 1275 autoscale: whether or not autoscale the plot (valid only plot=True) 1276 logger: whether or not print header info on the logger. 1277 selstr: additional selection string (not verified) 1278 extrastr: additional string to print (not verified) 1279 """ 1280 if not plot and not logger: return 1281 if not self._data: raise RuntimeError("No scantable has been set yet.") 1282 # Now header will be printed on plot and/or logger. 1283 # Get header information and format it. 1284 ssum=self._data.__str__() 1285 # Print Observation header to the upper-left corner of plot 1286 if plot: 1287 headstr=[ssum[ssum.find('Observer:'):ssum.find('Flux Unit:')]] 1288 headstr.append(ssum[ssum.find('Beams:'):ssum.find('Observer:')] 1289 +ssum[ssum.find('Rest Freqs:'):ssum.find('Abcissa:')]) 1290 if extrastr != '': headstr[0]=extrastr+'\n'+headstr[0] 1291 #headstr[1]='Data File: '+(filestr or 'unknown')+'\n'+headstr[1] 1292 ssel='***Selections***\n'+(selstr+self._data.get_selection().__str__() or 'none') 1293 headstr.append(ssel) 1294 nstcol=len(headstr) 1295 1296 self._plotter.hold() 1297 for i in range(nstcol): 1298 self._plotter.figure.text(0.03+float(i)/nstcol,0.98, 1299 headstr[i], 1300 horizontalalignment='left', 1301 verticalalignment='top', 1302 fontsize=fontsize) 1303 import time 1304 self._plotter.figure.text(0.99,0.0, 1305 time.strftime("%a %d %b %Y %H:%M:%S %Z"), 1306 horizontalalignment='right', 1307 verticalalignment='bottom',fontsize=8) 1308 self._plotter.release() 1309 del headstr, ssel 1310 if logger: 1311 asaplog.push("----------------\n Plot Summary\n----------------") 1312 asaplog.push(extrastr) 1313 asaplog.push(ssum[ssum.find('Beams:'):]) 1314 print_log() 1315 del ssum 1316 1317 -
trunk/python/asapreader.py
r1695 r1819 1 1 from asap._asap import stfiller 2 from asap import print_log _dec2 from asap import print_log, print_log_dec 3 3 4 4 class reader(stfiller): … … 46 46 filename = expandvars(filename) 47 47 stfiller.__init__(self, filename, theif, thebeam) 48 print_log() 48 49 49 50 @print_log_dec … … 59 60 if self.unit is not None: 60 61 tbl.set_fluxunit(self.unit) 62 print_log() 61 63 return scantable(tbl) 62 64 -
trunk/python/linecatalog.py
r1534 r1819 8 8 from asap._asap import linecatalog as lcbase 9 9 from asap import rcParams 10 from asap import asaplog 10 11 import os 11 12 … … 30 31 msg = "File '%s' not found" % fpath 31 32 if rcParams['verbose']: 32 print msg 33 #print msg 34 asaplog.push( msg ) 35 print_log( 'ERROR' ) 33 36 return 34 37 else: … … 97 100 msg = "File %s exists." % name 98 101 if rcParams['verbose']: 99 print msg 102 #print msg 103 asaplog.push( msg ) 104 print_log( 'ERROR' ) 100 105 return 101 106 else: -
trunk/python/scantable.py
r1731 r1819 35 35 The ASAP container for scans 36 36 """ 37 @print_log_dec 38 def __init__(self, filename, average=None, unit=None, parallactify=None): 37 38 @print_log_dec 39 def __init__(self, filename, average=None, unit=None, getpt=None, antenna=None, parallactify=None): 39 40 """ 40 41 Create a scantable from a saved one or make a reference … … 54 55 (input rpfits/sdfits/ms) or replaces the value 55 56 in existing scantables 57 getpt: for MeasurementSet input data only: 58 If True, all pointing data are filled. 59 The deafult is False, which makes time to load 60 the MS data faster in some cases. 61 antenna: Antenna selection. integer (id) or string (name 62 or id). 56 63 parallactify: Indcicate that the data had been parallatified. 57 64 Default is taken form rc file. … … 59 66 if average is None: 60 67 average = rcParams['scantable.autoaverage'] 68 if getpt is None: 69 getpt = True 70 if antenna is None: 71 antenna = '' 72 elif type(antenna) == int: 73 antenna = '%s'%antenna 74 elif type(antenna) == list: 75 tmpstr = '' 76 for i in range( len(antenna) ): 77 if type(antenna[i]) == int: 78 tmpstr = tmpstr + ('%s,'%(antenna[i])) 79 elif type(antenna[i]) == str: 80 tmpstr=tmpstr+antenna[i]+',' 81 else: 82 asaplog.push('Bad antenna selection.') 83 print_log('ERROR') 84 return 85 antenna = tmpstr.rstrip(',') 61 86 parallactify = parallactify or rcParams['scantable.parallactify'] 62 87 varlist = vars() 63 88 from asap._asap import stmath 64 self._math = stmath( )89 self._math = stmath( rcParams['insitu'] ) 65 90 if isinstance(filename, Scantable): 66 91 Scantable.__init__(self, filename) … … 73 98 if rcParams['verbose']: 74 99 asaplog.push(s) 100 print_log('ERROR') 75 101 return 76 102 raise IOError(s) … … 80 106 if unit is not None: 81 107 self.set_fluxunit(unit) 82 self.set_freqframe(rcParams['scantable.freqframe']) 108 # do not reset to the default freqframe 109 #self.set_freqframe(rcParams['scantable.freqframe']) 110 elif os.path.isdir(filename) \ 111 and not os.path.exists(filename+'/table.f1'): 112 msg = "The given file '%s'is not a valid " \ 113 "asap table." % (filename) 114 if rcParams['verbose']: 115 #print msg 116 asaplog.push( msg ) 117 print_log( 'ERROR' ) 118 return 119 else: 120 raise IOError(msg) 83 121 else: 84 self._fill([filename], unit, average )122 self._fill([filename], unit, average, getpt, antenna) 85 123 elif (isinstance(filename, list) or isinstance(filename, tuple)) \ 86 124 and isinstance(filename[-1], str): 87 self._fill(filename, unit, average )125 self._fill(filename, unit, average, getpt, antenna) 88 126 self.parallactify(parallactify) 89 127 self._add_history("scantable", varlist) 128 print_log() 90 129 91 130 @print_log_dec … … 126 165 msg = "File %s exists." % name 127 166 if rcParams['verbose']: 128 print msg 167 #print msg 168 asaplog.push( msg ) 169 print_log( 'ERROR' ) 129 170 return 130 171 else: … … 137 178 writer = stw(format2) 138 179 writer.write(self, name) 180 print_log() 139 181 return 140 182 … … 164 206 if not _is_valid(scanid): 165 207 if rcParams['verbose']: 166 print "Please specify a scanno to drop from the scantable" 208 #print "Please specify a scanno to drop from the scantable" 209 asaplog.push( 'Please specify a scanno to drop from the scantable' ) 210 print_log( 'ERROR' ) 167 211 return 168 212 else: … … 176 220 except ValueError: 177 221 if rcParams['verbose']: 178 print "Couldn't find any match." 222 #print "Couldn't find any match." 223 print_log() 224 asaplog.push( "Couldn't find any match." ) 225 print_log( 'ERROR' ) 179 226 return 180 227 else: raise … … 184 231 except RuntimeError: 185 232 if rcParams['verbose']: 186 print "Couldn't find any match." 233 #print "Couldn't find any match." 234 print_log() 235 asaplog.push( "Couldn't find any match." ) 236 print_log( 'ERROR' ) 187 237 else: 188 238 raise … … 215 265 if scanid is None: 216 266 if rcParams['verbose']: 217 print "Please specify a scan no or name to " \ 218 "retrieve from the scantable" 267 #print "Please specify a scan no or name to " \ 268 # "retrieve from the scantable" 269 asaplog.push( 'Please specify a scan no or name to retrieve from the scantable' ) 270 print_log( 'ERROR' ) 219 271 return 220 272 else: … … 236 288 msg = "Illegal scanid type, use 'int' or 'list' if ints." 237 289 if rcParams['verbose']: 238 print msg 290 #print msg 291 asaplog.push( msg ) 292 print_log( 'ERROR' ) 239 293 else: 240 294 raise TypeError(msg) 241 295 except RuntimeError: 242 if rcParams['verbose']: print "Couldn't find any match." 296 if rcParams['verbose']: 297 #print "Couldn't find any match." 298 print_log() 299 asaplog.push( "Couldn't find any match." ) 300 print_log( 'ERROR' ) 243 301 else: raise 244 302 … … 266 324 msg = "Illegal file name '%s'." % (filename) 267 325 if rcParams['verbose']: 268 print msg 326 #print msg 327 asaplog.push( msg ) 328 print_log( 'ERROR' ) 269 329 else: 270 330 raise IOError(msg) … … 367 427 self._setselection(selection) 368 428 369 def stats(self, stat='stddev', mask=None): 429 def get_row(self, row=0, insitu=None): 430 """ 431 Select a row in the scantable. 432 Return a scantable with single row. 433 Parameters: 434 row: row no of integration, default is 0. 435 insitu: if False a new scantable is returned. 436 Otherwise, the scaling is done in-situ 437 The default is taken from .asaprc (False) 438 """ 439 if insitu is None: insitu = rcParams['insitu'] 440 if not insitu: 441 workscan = self.copy() 442 else: 443 workscan = self 444 # Select a row 445 sel=selector() 446 sel.set_scans([workscan.getscan(row)]) 447 sel.set_cycles([workscan.getcycle(row)]) 448 sel.set_beams([workscan.getbeam(row)]) 449 sel.set_ifs([workscan.getif(row)]) 450 sel.set_polarisations([workscan.getpol(row)]) 451 sel.set_name(workscan._getsourcename(row)) 452 workscan.set_selection(sel) 453 if not workscan.nrow() == 1: 454 msg = "Cloud not identify single row. %d rows selected."%(workscan.nrow()) 455 raise RuntimeError(msg) 456 del sel 457 if insitu: 458 self._assign(workscan) 459 else: 460 return workscan 461 462 #def stats(self, stat='stddev', mask=None): 463 def stats(self, stat='stddev', mask=None, form='3.3f'): 370 464 """ 371 465 Determine the specified statistic of the current beam/if/pol … … 373 467 channels should be excluded. 374 468 Parameters: 375 stat: 'min', 'max', ' sumsq', 'sum', 'mean'376 ' var', 'stddev', 'avdev', 'rms', 'median'469 stat: 'min', 'max', 'min_abc', 'max_abc', 'sumsq', 'sum', 470 'mean', 'var', 'stddev', 'avdev', 'rms', 'median' 377 471 mask: an optional mask specifying where the statistic 378 472 should be determined. 473 form: format string to print statistic values 379 474 Example: 380 475 scan.set_unit('channel') … … 387 482 "number of channels. Please use setselection() " 388 483 "to select individual IFs") 389 390 statvals = self._math._stats(self, mask, stat) 391 def cb(i): 392 return statvals[i] 393 394 return self._row_callback(cb, stat) 484 rtnabc = False 485 if stat.lower().endswith('_abc'): rtnabc = True 486 getchan = False 487 if stat.lower().startswith('min') or stat.lower().startswith('max'): 488 chan = self._math._minmaxchan(self, mask, stat) 489 getchan = True 490 statvals = [] 491 if not rtnabc: statvals = self._math._stats(self, mask, stat) 492 493 #def cb(i): 494 # return statvals[i] 495 496 #return self._row_callback(cb, stat) 497 498 label=stat 499 #callback=cb 500 out = "" 501 #outvec = [] 502 sep = '-'*50 503 for i in range(self.nrow()): 504 refstr = '' 505 statunit= '' 506 if getchan: 507 qx, qy = self.chan2data(rowno=i, chan=chan[i]) 508 if rtnabc: 509 statvals.append(qx['value']) 510 refstr = ('(value: %'+form) % (qy['value'])+' ['+qy['unit']+'])' 511 statunit= '['+qx['unit']+']' 512 else: 513 refstr = ('(@ %'+form) % (qx['value'])+' ['+qx['unit']+'])' 514 515 tm = self._gettime(i) 516 src = self._getsourcename(i) 517 out += 'Scan[%d] (%s) ' % (self.getscan(i), src) 518 out += 'Time[%s]:\n' % (tm) 519 if self.nbeam(-1) > 1: 520 out += ' Beam[%d] ' % (self.getbeam(i)) 521 if self.nif(-1) > 1: out += ' IF[%d] ' % (self.getif(i)) 522 if self.npol(-1) > 1: out += ' Pol[%d] ' % (self.getpol(i)) 523 #outvec.append(callback(i)) 524 #out += ('= %'+form) % (outvec[i]) +' '+refstr+'\n' 525 out += ('= %'+form) % (statvals[i]) +' '+refstr+'\n' 526 out += sep+"\n" 527 528 if rcParams['verbose']: 529 import os 530 if os.environ.has_key( 'USER' ): 531 usr=os.environ['USER'] 532 else: 533 import commands 534 usr=commands.getoutput( 'whoami' ) 535 tmpfile='/tmp/tmp_'+usr+'_casapy_asap_scantable_stats' 536 f=open(tmpfile,'w') 537 print >> f, sep 538 print >> f, ' %s %s' % (label, statunit) 539 print >> f, sep 540 print >> f, out 541 f.close() 542 f=open(tmpfile,'r') 543 x=f.readlines() 544 f.close() 545 blanc='' 546 asaplog.push(blanc.join(x), False) 547 #for xx in x: 548 # asaplog.push( xx, False ) 549 print_log() 550 return statvals 551 552 def chan2data(self, rowno=0, chan=0): 553 """ 554 Returns channel/frequency/velocity and spectral value 555 at an arbitrary row and channel in the scantable. 556 Parameters: 557 rowno: a row number in the scantable. Default is the 558 first row, i.e. rowno=0 559 chan: a channel in the scantable. Default is the first 560 channel, i.e. pos=0 561 """ 562 if isinstance(rowno, int) and isinstance(chan, int): 563 qx = {'unit': self.get_unit(), 564 'value': self._getabcissa(rowno)[chan]} 565 qy = {'unit': self.get_fluxunit(), 566 'value': self._getspectrum(rowno)[chan]} 567 return qx, qy 395 568 396 569 def stddev(self, mask=None): … … 462 635 out += sep+'\n' 463 636 if rcParams['verbose']: 464 print sep 465 print " %s" % (label) 466 print sep 467 print out 637 asaplog.push(sep) 638 asaplog.push(" %s" % (label)) 639 asaplog.push(sep) 640 asaplog.push(out) 641 print_log() 468 642 return outvec 469 643 … … 474 648 return [callback(i) for i in range(self.nrow())] 475 649 else: 476 if 0 <= row < self.nrow():650 if 0 <= row < self.nrow(): 477 651 return callback(row) 478 652 … … 604 778 self._setInstrument(instr) 605 779 self._add_history("set_instument", vars()) 780 print_log() 606 781 607 782 @print_log_dec … … 614 789 self._setfeedtype(feedtype) 615 790 self._add_history("set_feedtype", vars()) 791 print_log() 616 792 617 793 @print_log_dec … … 627 803 self._setcoordinfo(inf) 628 804 self._add_history("set_doppler", vars()) 805 print_log() 629 806 630 807 @print_log_dec … … 634 811 Parameters: 635 812 frame: an optional frame type, default 'LSRK'. Valid frames are: 636 ' REST', 'TOPO', 'LSRD', 'LSRK', 'BARY',813 'TOPO', 'LSRD', 'LSRK', 'BARY', 637 814 'GEO', 'GALACTO', 'LGROUP', 'CMB' 638 815 Examples: … … 641 818 frame = frame or rcParams['scantable.freqframe'] 642 819 varlist = vars() 643 valid = ['REST', 'TOPO', 'LSRD', 'LSRK', 'BARY', \ 820 # "REST" is not implemented in casacore 821 #valid = ['REST', 'TOPO', 'LSRD', 'LSRK', 'BARY', \ 822 # 'GEO', 'GALACTO', 'LGROUP', 'CMB'] 823 valid = ['TOPO', 'LSRD', 'LSRK', 'BARY', \ 644 824 'GEO', 'GALACTO', 'LGROUP', 'CMB'] 645 825 … … 652 832 msg = "Please specify a valid freq type. Valid types are:\n", valid 653 833 if rcParams['verbose']: 654 print msg 834 #print msg 835 asaplog.push( msg ) 836 print_log( 'ERROR' ) 655 837 else: 656 838 raise TypeError(msg) 839 print_log() 657 840 658 841 def set_dirframe(self, frame=""): … … 670 853 except RuntimeError, msg: 671 854 if rcParams['verbose']: 672 print msg 855 #print msg 856 print_log() 857 asaplog.push( str(msg) ) 858 print_log( 'ERROR' ) 673 859 else: 674 860 raise … … 698 884 abc = self._getabcissa(rowno) 699 885 lbl = self._getabcissalabel(rowno) 886 print_log() 700 887 return abc, lbl 701 888 702 def flag(self, mask=None ):889 def flag(self, mask=None, unflag=False): 703 890 """ 704 891 Flag the selected data using an optional channel mask. … … 706 893 mask: an optional channel mask, created with create_mask. Default 707 894 (no mask) is all channels. 895 unflag: if True, unflag the data 708 896 """ 709 897 varlist = vars() 710 898 mask = mask or [] 711 899 try: 712 self._flag(mask )900 self._flag(mask, unflag) 713 901 except RuntimeError, msg: 714 902 if rcParams['verbose']: 715 print msg 903 #print msg 904 print_log() 905 asaplog.push( str(msg) ) 906 print_log( 'ERROR' ) 716 907 return 717 908 else: raise 718 909 self._add_history("flag", varlist) 719 910 911 def flag_row(self, rows=[], unflag=False): 912 """ 913 Flag the selected data in row-based manner. 914 Parameters: 915 rows: list of row numbers to be flagged. Default is no row (must be explicitly specified to execute row-based flagging). 916 unflag: if True, unflag the data. 917 """ 918 varlist = vars() 919 try: 920 self._flag_row(rows, unflag) 921 except RuntimeError, msg: 922 if rcParams['verbose']: 923 print_log() 924 asaplog.push( str(msg) ) 925 print_log('ERROR') 926 return 927 else: raise 928 self._add_history("flag_row", varlist) 929 930 def clip(self, uthres=None, dthres=None, clipoutside=True, unflag=False): 931 """ 932 Flag the selected data outside a specified range (in channel-base) 933 Parameters: 934 uthres: upper threshold. 935 dthres: lower threshold 936 clipoutside: True for flagging data outside the range [dthres:uthres]. 937 False for glagging data inside the range. 938 unflag : if True, unflag the data. 939 """ 940 varlist = vars() 941 try: 942 self._clip(uthres, dthres, clipoutside, unflag) 943 except RuntimeError, msg: 944 if rcParams['verbose']: 945 print_log() 946 asaplog.push(str(msg)) 947 print_log('ERROR') 948 return 949 else: raise 950 self._add_history("clip", varlist) 951 720 952 @print_log_dec 721 953 def lag_flag(self, start, end, unit="MHz", insitu=None): 954 #def lag_flag(self, frequency, width=0.0, unit="GHz", insitu=None): 722 955 """ 723 956 Flag the data in 'lag' space by providing a frequency to remove. … … 748 981 except RuntimeError, msg: 749 982 if rcParams['verbose']: 750 print msg 983 #print msg 984 print_log() 985 asaplog.push( str(msg) ) 986 print_log( 'ERROR' ) 751 987 return 752 988 else: raise 753 989 s._add_history("lag_flag", varlist) 990 print_log() 754 991 if insitu: 755 992 self._assign(s) … … 819 1056 if kwargs.get('invert'): 820 1057 msk = mask_not(msk) 1058 print_log() 821 1059 return msk 822 1060 823 def get_restfreqs(self): 1061 def get_masklist(self, mask=None, row=0): 1062 """ 1063 Compute and return a list of mask windows, [min, max]. 1064 Parameters: 1065 mask: channel mask, created with create_mask. 1066 row: calcutate the masklist using the specified row 1067 for unit conversions, default is row=0 1068 only necessary if frequency varies over rows. 1069 Returns: 1070 [min, max], [min2, max2], ... 1071 Pairs of start/end points (inclusive)specifying 1072 the masked regions 1073 """ 1074 if not (isinstance(mask,list) or isinstance(mask, tuple)): 1075 raise TypeError("The mask should be list or tuple.") 1076 if len(mask) < 2: 1077 raise TypeError("The mask elements should be > 1") 1078 if self.nchan() != len(mask): 1079 msg = "Number of channels in scantable != number of mask elements" 1080 raise TypeError(msg) 1081 data = self._getabcissa(row) 1082 u = self._getcoordinfo()[0] 1083 if rcParams['verbose']: 1084 if u == "": u = "channel" 1085 msg = "The current mask window unit is %s" % u 1086 i = self._check_ifs() 1087 if not i: 1088 msg += "\nThis mask is only valid for IF=%d" % (self.getif(i)) 1089 asaplog.push(msg) 1090 masklist=[] 1091 ist, ien = None, None 1092 ist, ien=self.get_mask_indices(mask) 1093 if ist is not None and ien is not None: 1094 for i in xrange(len(ist)): 1095 range=[data[ist[i]],data[ien[i]]] 1096 range.sort() 1097 masklist.append([range[0],range[1]]) 1098 return masklist 1099 1100 def get_mask_indices(self, mask=None): 1101 """ 1102 Compute and Return lists of mask start indices and mask end indices. 1103 Parameters: 1104 mask: channel mask, created with create_mask. 1105 Returns: 1106 List of mask start indices and that of mask end indices, 1107 i.e., [istart1,istart2,....], [iend1,iend2,....]. 1108 """ 1109 if not (isinstance(mask,list) or isinstance(mask, tuple)): 1110 raise TypeError("The mask should be list or tuple.") 1111 if len(mask) < 2: 1112 raise TypeError("The mask elements should be > 1") 1113 istart=[] 1114 iend=[] 1115 if mask[0]: istart.append(0) 1116 for i in range(len(mask)-1): 1117 if not mask[i] and mask[i+1]: 1118 istart.append(i+1) 1119 elif mask[i] and not mask[i+1]: 1120 iend.append(i) 1121 if mask[len(mask)-1]: iend.append(len(mask)-1) 1122 if len(istart) != len(iend): 1123 raise RuntimeError("Numbers of mask start != mask end.") 1124 for i in range(len(istart)): 1125 if istart[i] > iend[i]: 1126 raise RuntimeError("Mask start index > mask end index") 1127 break 1128 return istart,iend 1129 1130 # def get_restfreqs(self): 1131 # """ 1132 # Get the restfrequency(s) stored in this scantable. 1133 # The return value(s) are always of unit 'Hz' 1134 # Parameters: 1135 # none 1136 # Returns: 1137 # a list of doubles 1138 # """ 1139 # return list(self._getrestfreqs()) 1140 1141 def get_restfreqs(self, ids=None): 824 1142 """ 825 1143 Get the restfrequency(s) stored in this scantable. 826 1144 The return value(s) are always of unit 'Hz' 827 1145 Parameters: 828 none 1146 ids: (optional) a list of MOLECULE_ID for that restfrequency(s) to 1147 be retrieved 829 1148 Returns: 830 a list of doubles 831 """ 832 return list(self._getrestfreqs()) 833 1149 dictionary containing ids and a list of doubles for each id 1150 """ 1151 if ids is None: 1152 rfreqs={} 1153 idlist = self.getmolnos() 1154 for i in idlist: 1155 rfreqs[i]=list(self._getrestfreqs(i)) 1156 return rfreqs 1157 else: 1158 if type(ids)==list or type(ids)==tuple: 1159 rfreqs={} 1160 for i in ids: 1161 rfreqs[i]=list(self._getrestfreqs(i)) 1162 return rfreqs 1163 else: 1164 return list(self._getrestfreqs(ids)) 1165 #return list(self._getrestfreqs(ids)) 834 1166 835 1167 def set_restfreqs(self, freqs=None, unit='Hz'): 836 1168 """ 1169 ********NEED TO BE UPDATED begin************ 837 1170 Set or replace the restfrequency specified and 838 1171 If the 'freqs' argument holds a scalar, … … 846 1179 E.g. 'freqs=[1e9, 2e9]' would mean IF 0 gets restfreq 1e9 and 847 1180 IF 1 gets restfreq 2e9. 1181 ********NEED TO BE UPDATED end************ 848 1182 You can also specify the frequencies via a linecatalog. 849 1183 … … 853 1187 854 1188 Example: 855 # set the given restfrequency for the whole table1189 # set the given restfrequency for the all currently selected IFs 856 1190 scan.set_restfreqs(freqs=1.4e9) 857 # If thee number of IFs in the data is >= 2 IF0 gets the first 858 # value IF1 the second... 859 scan.set_restfreqs(freqs=[1.4e9, 1.67e9]) 1191 # set multiple restfrequencies to all the selected data 1192 scan.set_restfreqs(freqs=[1.4e9, 1.41e9, 1.42e9]) 1193 # If the number of IFs in the data is >= 2 the IF0 gets the first 1194 # value IF1 the second... NOTE that freqs needs to be 1195 # specified in list of list (e.g. [[],[],...] ). 1196 scan.set_restfreqs(freqs=[[1.4e9],[1.67e9]]) 860 1197 #set the given restfrequency for the whole table (by name) 861 1198 scan.set_restfreqs(freqs="OH1667") … … 877 1214 # simple value 878 1215 if isinstance(freqs, int) or isinstance(freqs, float): 879 self._setrestfreqs(freqs, "",unit) 1216 # TT mod 1217 #self._setrestfreqs(freqs, "",unit) 1218 self._setrestfreqs([freqs], [""],unit) 880 1219 # list of values 881 1220 elif isinstance(freqs, list) or isinstance(freqs, tuple): 882 1221 # list values are scalars 883 1222 if isinstance(freqs[-1], int) or isinstance(freqs[-1], float): 1223 self._setrestfreqs(freqs, [""], unit) 1224 # list values are tuples, (value, name) 1225 elif isinstance(freqs[-1], dict): 1226 #sel = selector() 1227 #savesel = self._getselection() 1228 #iflist = self.getifnos() 1229 #for i in xrange(len(freqs)): 1230 # sel.set_ifs(iflist[i]) 1231 # self._setselection(sel) 1232 # self._setrestfreqs(freqs[i], "",unit) 1233 #self._setselection(savesel) 1234 self._setrestfreqs(freqs["value"], 1235 freqs["name"], unit) 1236 elif isinstance(freqs[-1], list) or isinstance(freqs[-1], tuple): 884 1237 sel = selector() 885 1238 savesel = self._getselection() 886 1239 iflist = self.getifnos() 1240 if len(freqs)>len(iflist): 1241 raise ValueError("number of elements in list of list exeeds the current IF selections") 887 1242 for i in xrange(len(freqs)): 888 1243 sel.set_ifs(iflist[i]) 889 1244 self._setselection(sel) 890 self._setrestfreqs(freqs[i], "",unit) 891 self._setselection(savesel) 892 # list values are tuples, (value, name) 893 elif isinstance(freqs[-1], dict): 894 sel = selector() 895 savesel = self._getselection() 896 iflist = self.getifnos() 897 for i in xrange(len(freqs)): 898 sel.set_ifs(iflist[i]) 899 self._setselection(sel) 900 self._setrestfreqs(freqs[i]["value"], 901 freqs[i]["name"], "MHz") 1245 self._setrestfreqs(freqs[i], [""], unit) 902 1246 self._setselection(savesel) 903 1247 # freqs are to be taken from a linecatalog … … 905 1249 sel = selector() 906 1250 savesel = self._getselection() 907 iflist = self.getifnos()908 1251 for i in xrange(freqs.nrow()): 909 1252 sel.set_ifs(iflist[i]) … … 963 1306 msg = "Illegal file name '%s'." % (filename) 964 1307 if rcParams['verbose']: 965 print msg 1308 #print msg 1309 asaplog.push( msg ) 1310 print_log( 'ERROR' ) 966 1311 else: 967 1312 raise IOError(msg) … … 1020 1365 except RuntimeError, msg: 1021 1366 if rcParams['verbose']: 1022 print msg 1367 #print msg 1368 print_log() 1369 asaplog.push( str(msg) ) 1370 print_log( 'ERROR' ) 1023 1371 return 1024 1372 else: raise 1025 1373 s._add_history("average_time", varlist) 1374 print_log() 1026 1375 return s 1027 1376 … … 1051 1400 s = scantable(self._math._convertflux(self, d, eta, jyperk)) 1052 1401 s._add_history("convert_flux", varlist) 1402 print_log() 1053 1403 if insitu: self._assign(s) 1054 1404 else: return s … … 1103 1453 s = scantable(self._math._gainel(self, poly, filename, method)) 1104 1454 s._add_history("gain_el", varlist) 1455 print_log() 1105 1456 if insitu: 1106 1457 self._assign(s) … … 1130 1481 s = scantable(self._math._freq_align(self, reftime, method)) 1131 1482 s._add_history("freq_align", varlist) 1483 print_log() 1132 1484 if insitu: self._assign(s) 1133 1485 else: return s … … 1158 1510 s = scantable(self._math._opacity(self, tau)) 1159 1511 s._add_history("opacity", varlist) 1512 print_log() 1160 1513 if insitu: self._assign(s) 1161 1514 else: return s … … 1176 1529 s = scantable(self._math._bin(self, width)) 1177 1530 s._add_history("bin", varlist) 1531 print_log() 1178 1532 if insitu: 1179 1533 self._assign(s) … … 1200 1554 s = scantable(self._math._resample(self, method, width)) 1201 1555 s._add_history("resample", varlist) 1556 print_log() 1202 1557 if insitu: self._assign(s) 1203 1558 else: return s … … 1218 1573 s = scantable(self._math._averagepol(self, mask, weight.upper())) 1219 1574 s._add_history("average_pol", varlist) 1575 print_log() 1220 1576 return s 1221 1577 … … 1235 1591 s = scantable(self._math._averagebeams(self, mask, weight.upper())) 1236 1592 s._add_history("average_beam", varlist) 1593 print_log() 1237 1594 return s 1238 1595 … … 1263 1620 except RuntimeError, msg: 1264 1621 if rcParams['verbose']: 1265 print msg 1622 #print msg 1623 print_log() 1624 asaplog.push( str(msg) ) 1625 print_log( 'ERROR' ) 1266 1626 return 1267 1627 else: 1268 1628 raise 1269 1629 s._add_history("convert_pol", varlist) 1630 print_log() 1270 1631 return s 1271 1632 1272 1633 @print_log_dec 1273 def smooth(self, kernel="hanning", width=5.0, order=2, insitu=None):1634 def smooth(self, kernel="hanning", width=5.0, order=2, plot=False, insitu=None): 1274 1635 """ 1275 1636 Smooth the spectrum by the specified kernel (conserving flux). … … 1286 1647 specify the order of the polnomial. Ignored by all other 1287 1648 kernels. 1649 plot: plot the original and the smoothed spectra. 1650 In this each indivual fit has to be approved, by 1651 typing 'y' or 'n' 1288 1652 insitu: if False a new scantable is returned. 1289 1653 Otherwise, the scaling is done in-situ … … 1295 1659 self._math._setinsitu(insitu) 1296 1660 varlist = vars() 1661 1662 if plot: orgscan = self.copy() 1663 1297 1664 s = scantable(self._math._smooth(self, kernel.lower(), width, order)) 1298 1665 s._add_history("smooth", varlist) 1666 1667 if plot: 1668 if rcParams['plotter.gui']: 1669 from asap.asaplotgui import asaplotgui as asaplot 1670 else: 1671 from asap.asaplot import asaplot 1672 self._p=asaplot() 1673 self._p.set_panels() 1674 ylab=s._get_ordinate_label() 1675 #self._p.palette(0,["#777777","red"]) 1676 for r in xrange(s.nrow()): 1677 xsm=s._getabcissa(r) 1678 ysm=s._getspectrum(r) 1679 xorg=orgscan._getabcissa(r) 1680 yorg=orgscan._getspectrum(r) 1681 self._p.clear() 1682 self._p.hold() 1683 self._p.set_axes('ylabel',ylab) 1684 self._p.set_axes('xlabel',s._getabcissalabel(r)) 1685 self._p.set_axes('title',s._getsourcename(r)) 1686 self._p.set_line(label='Original',color="#777777") 1687 self._p.plot(xorg,yorg) 1688 self._p.set_line(label='Smoothed',color="red") 1689 self._p.plot(xsm,ysm) 1690 ### Ugly part for legend 1691 for i in [0,1]: 1692 self._p.subplots[0]['lines'].append([self._p.subplots[0]['axes'].lines[i]]) 1693 self._p.release() 1694 ### Ugly part for legend 1695 self._p.subplots[0]['lines']=[] 1696 res = raw_input("Accept smoothing ([y]/n): ") 1697 if res.upper() == 'N': 1698 s._setspectrum(yorg, r) 1699 self._p.unmap() 1700 self._p = None 1701 del orgscan 1702 1703 print_log() 1299 1704 if insitu: self._assign(s) 1300 1705 else: return s … … 1321 1726 """ 1322 1727 if insitu is None: insitu = rcParams['insitu'] 1728 if not insitu: 1729 workscan = self.copy() 1730 else: 1731 workscan = self 1323 1732 varlist = vars() 1324 1733 if mask is None: 1325 1734 mask = [True for i in xrange(self.nchan(-1))] 1735 1326 1736 from asap.asapfitter import fitter 1327 1737 try: 1328 1738 f = fitter() 1329 f.set_scan(self, mask)1330 #f.set_function(poly=order)1331 1739 if uselin: 1332 1740 f.set_function(lpoly=order) 1333 1741 else: 1334 1742 f.set_function(poly=order) 1335 s = f.auto_fit(insitu, plot=plot) 1336 s._add_history("poly_baseline", varlist) 1337 if insitu: self._assign(s) 1338 else: return s 1743 1744 rows = range(workscan.nrow()) 1745 if len(rows) > 0: 1746 self.blpars = [] 1747 1748 for r in rows: 1749 # take into account flagtra info (CAS-1434) 1750 flagtra = workscan._getmask(r) 1751 actualmask = mask[:] 1752 if len(actualmask) == 0: 1753 actualmask = list(flagtra[:]) 1754 else: 1755 if len(actualmask) != len(flagtra): 1756 raise RuntimeError, "Mask and flagtra have different length" 1757 else: 1758 for i in range(0, len(actualmask)): 1759 actualmask[i] = actualmask[i] and flagtra[i] 1760 f.set_scan(workscan, actualmask) 1761 f.x = workscan._getabcissa(r) 1762 f.y = workscan._getspectrum(r) 1763 f.data = None 1764 f.fit() 1765 if plot: 1766 f.plot(residual=True) 1767 x = raw_input("Accept fit ( [y]/n ): ") 1768 if x.upper() == 'N': 1769 self.blpars.append(None) 1770 continue 1771 workscan._setspectrum(f.fitter.getresidual(), r) 1772 self.blpars.append(f.get_parameters()) 1773 1774 if plot: 1775 f._p.unmap() 1776 f._p = None 1777 workscan._add_history("poly_baseline", varlist) 1778 print_log() 1779 if insitu: self._assign(workscan) 1780 else: return workscan 1339 1781 except RuntimeError: 1340 1782 msg = "The fit failed, possibly because it didn't converge." 1341 1783 if rcParams['verbose']: 1342 print msg 1784 #print msg 1785 print_log() 1786 asaplog.push( str(msg) ) 1787 print_log( 'ERROR' ) 1343 1788 return 1344 1789 else: 1345 1790 raise RuntimeError(msg) 1791 1346 1792 1347 1793 def auto_poly_baseline(self, mask=[], edge=(0, 0), order=0, … … 1427 1873 1428 1874 rows = range(workscan.nrow()) 1875 # Save parameters of baseline fits & masklists as a class attribute. 1876 # NOTICE: It does not reflect changes in scantable! 1877 if len(rows) > 0: 1878 self.blpars=[] 1879 self.masklists=[] 1429 1880 asaplog.push("Processing:") 1430 1881 for r in rows: … … 1441 1892 curedge = edge[workscan.getif(r)] 1442 1893 1894 # take into account flagtra info (CAS-1434) 1895 flagtra = workscan._getmask(r) 1896 actualmask = mask[:] 1897 if len(actualmask) == 0: 1898 actualmask = list(flagtra[:]) 1899 else: 1900 if len(actualmask) != len(flagtra): 1901 raise RuntimeError, "Mask and flagtra have different length" 1902 else: 1903 for i in range(0, len(actualmask)): 1904 actualmask[i] = actualmask[i] and flagtra[i] 1905 1443 1906 # setup line finder 1444 fl.find_lines(r, mask, curedge) 1445 f.set_data(workscan._getabcissa(r), workscan._getspectrum(r), 1446 mask_and(workscan._getmask(r), fl.get_mask())) 1907 fl.find_lines(r, actualmask, curedge) 1908 outmask=fl.get_mask() 1909 f.set_scan(workscan, fl.get_mask()) 1910 f.x = workscan._getabcissa(r) 1911 f.y = workscan._getspectrum(r) 1912 f.data = None 1447 1913 f.fit() 1448 x = f.get_parameters() 1914 1915 # Show mask list 1916 masklist=workscan.get_masklist(fl.get_mask(),row=r) 1917 msg = "mask range: "+str(masklist) 1918 asaplog.push(msg, False) 1919 1449 1920 if plot: 1450 1921 f.plot(residual=True) 1451 1922 x = raw_input("Accept fit ( [y]/n ): ") 1452 1923 if x.upper() == 'N': 1924 self.blpars.append(None) 1925 self.masklists.append(None) 1453 1926 continue 1927 1454 1928 workscan._setspectrum(f.fitter.getresidual(), r) 1929 self.blpars.append(f.get_parameters()) 1930 self.masklists.append(masklist) 1455 1931 if plot: 1456 1932 f._p.unmap() … … 1476 1952 self._math._rotate_linpolphase(self, angle) 1477 1953 self._add_history("rotate_linpolphase", varlist) 1954 print_log() 1478 1955 return 1479 1956 … … 1492 1969 self._math._rotate_xyphase(self, angle) 1493 1970 self._add_history("rotate_xyphase", varlist) 1971 print_log() 1494 1972 return 1495 1973 … … 1503 1981 self._math._swap_linears(self) 1504 1982 self._add_history("swap_linears", varlist) 1983 print_log() 1505 1984 return 1506 1985 … … 1513 1992 self._math._invert_phase(self) 1514 1993 self._add_history("invert_phase", varlist) 1994 print_log() 1515 1995 return 1516 1996 … … 1530 2010 s = scantable(self._math._unaryop(self, offset, "ADD", False)) 1531 2011 s._add_history("add", varlist) 2012 print_log() 1532 2013 if insitu: 1533 2014 self._assign(s) … … 1540 2021 Return a scan where all spectra are scaled by the give 'factor' 1541 2022 Parameters: 1542 factor: the scaling factor 2023 factor: the scaling factor (float or 1D float list) 1543 2024 insitu: if False a new scantable is returned. 1544 2025 Otherwise, the scaling is done in-situ … … 1550 2031 self._math._setinsitu(insitu) 1551 2032 varlist = vars() 1552 s = scantable(self._math._unaryop(self, factor, "MUL", tsys)) 2033 s = None 2034 import numpy 2035 if isinstance(factor, list) or isinstance(factor, numpy.ndarray): 2036 if isinstance(factor[0], list) or isinstance(factor[0], numpy.ndarray): 2037 from asapmath import _array2dOp 2038 s = _array2dOp( self.copy(), factor, "MUL", tsys ) 2039 else: 2040 s = scantable( self._math._arrayop( self.copy(), factor, "MUL", tsys ) ) 2041 else: 2042 s = scantable(self._math._unaryop(self.copy(), factor, "MUL", tsys)) 1553 2043 s._add_history("scale", varlist) 2044 print_log() 1554 2045 if insitu: 1555 2046 self._assign(s) … … 1594 2085 1595 2086 @print_log_dec 1596 def auto_quotient(self, preserve=True, mode='paired' ):2087 def auto_quotient(self, preserve=True, mode='paired', verify=False): 1597 2088 """ 1598 2089 This function allows to build quotients automatically. 1599 It assumes the observation to have the same num er of2090 It assumes the observation to have the same number of 1600 2091 "ons" and "offs" 1601 2092 Parameters: … … 1634 2125 s = scantable(self._math._auto_quotient(self, mode, preserve)) 1635 2126 s._add_history("auto_quotient", varlist) 2127 print_log() 1636 2128 return s 1637 2129 … … 1656 2148 q = quotient(on, off, preserve) 1657 2149 q._add_history("mx_quotient", varlist) 2150 print_log() 1658 2151 return q 1659 2152 … … 1674 2167 s = scantable(self._math._freqswitch(self)) 1675 2168 s._add_history("freq_switch", varlist) 2169 print_log() 1676 2170 if insitu: self._assign(s) 1677 2171 else: return s … … 1688 2182 self._recalcazel() 1689 2183 self._add_history("recalc_azel", varlist) 2184 print_log() 1690 2185 return 1691 2186 … … 1765 2260 fit = asapfit(self._getfit(row)) 1766 2261 if rcParams['verbose']: 1767 print fit 2262 #print fit 2263 asaplog.push( '%s' %(fit) ) 2264 print_log() 1768 2265 return 1769 2266 else: … … 1862 2359 return (sum(nchans)/len(nchans) == nchans[0]) 1863 2360 1864 def _fill(self, names, unit, average ):2361 def _fill(self, names, unit, average, getpt, antenna): 1865 2362 import os 1866 2363 from asap._asap import stfiller … … 1874 2371 if rcParams['verbose']: 1875 2372 asaplog.push(msg) 1876 print asaplog.pop().strip() 2373 #print asaplog.pop().strip() 2374 print_log( 'ERROR' ) 1877 2375 return 1878 2376 raise IOError(msg) … … 1889 2387 asaplog.push(msg, False) 1890 2388 print_log() 1891 r._open(name, -1, -1)2389 r._open(name, antenna, -1, -1, getpt) 1892 2390 r._read() 1893 2391 if average: … … 1901 2399 if unit is not None: 1902 2400 self.set_fluxunit(unit) 1903 self.set_freqframe(rcParams['scantable.freqframe'])2401 #self.set_freqframe(rcParams['scantable.freqframe']) 1904 2402 1905 2403 def __getitem__(self, key): -
trunk/python/selector.py
r1596 r1819 160 160 """ 161 161 self._setorder(order) 162 163 def set_rows(self, rows=[]): 164 """ 165 Set a sequence of row numbers (0-based). Power users Only! 166 NOTICE row numbers can be changed easily by sorting, 167 prior selection, etc. 168 Parameters: 169 rows: a list of integers. Default [] is to unset the selection. 170 """ 171 vec = _to_list(rows, int) 172 if isinstance(vec,list): 173 self._setrows(vec) 174 else: 175 raise TypeError('Unknown row number type. Use lists of integers.') 176 177 def set_types(self, types=[]): 178 """ 179 Set a sequence of source types. 180 Parameters: 181 types: a list of integers. Default [] is to unset the selection. 182 """ 183 vec = _to_list(types, int) 184 if isinstance(vec,list): 185 self._settypes(vec) 186 else: 187 raise TypeError('Unknown row number type. Use lists of integers.') 162 188 163 189 def get_scans(self): … … 175 201 def get_order(self): 176 202 return list(self._getorder()) 203 def get_types(self): 204 return list(self._gettypes()) 177 205 def get_query(self): 178 206 prefix = "SELECT FROM $1 WHERE "
Note:
See TracChangeset
for help on using the changeset viewer.