Changeset 1779 for branches/mergetest/python
- Timestamp:
- 07/29/10 19:13:46 (15 years ago)
- Location:
- branches/mergetest
- Files:
-
- 13 edited
- 8 copied
Legend:
- Unmodified
- Added
- Removed
-
branches/mergetest
- Property svn:mergeinfo changed
-
branches/mergetest/python/__init__.py
r1739 r1779 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__) -
branches/mergetest/python/asapfitter.py
r1739 r1779 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: … … 114 127 return 115 128 116 @print_log_dec129 #@print_log_dec 117 130 def fit(self, row=0, estimate=False): 118 131 """ … … 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 … … 204 222 self.data._addfit(fit,self._fittedrow) 205 223 206 @print_log_dec224 #@print_log_dec 207 225 def set_parameters(self,*args,**kwargs): 208 226 """ … … 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: … … 460 544 return self.fitter.getfit() 461 545 462 @print_log_dec546 #@print_log_dec 463 547 def commit(self): 464 548 """ … … 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 486 @print_log_dec575 #@print_log_dec 487 576 def plot(self, residual=False, components=None, plotparms=False, 488 577 filename=None): … … 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) 573 574 @print_log_dec 674 print_log() 675 676 #@print_log_dec 575 677 def auto_fit(self, insitu=None, plot=False): 576 678 """ … … 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 -
branches/mergetest/python/asaplot.py
r1564 r1779 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) -
branches/mergetest/python/asaplotbase.py
r1739 r1779 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] … … 280 282 281 283 282 def get_region(self):283 pos = []284 print "Please select the bottom/left point"285 pos.append(self.figure.ginput(n=1, show_clicks=False)[0])286 print "Please select the top/right point"287 pos.append(self.figure.ginput(n=1, show_clicks=False)[0])288 return pos289 290 def get_point(self):291 print "Please select the point"292 pt = self.figure.ginput(n=1, show_clicks=False)293 if pt:294 return pt[0]295 else:296 return None284 # def get_region(self): 285 # pos = [] 286 # print "Please select the bottom/left point" 287 # pos.append(self.figure.ginput(n=1, show_clicks=False)[0]) 288 # print "Please select the top/right point" 289 # pos.append(self.figure.ginput(n=1, show_clicks=False)[0]) 290 # return pos 291 292 # def get_point(self): 293 # print "Please select the point" 294 # pt = self.figure.ginput(n=1, show_clicks=False) 295 # if pt: 296 # return pt[0] 297 # else: 298 # return None 297 299 298 300 def region(self): … … 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 -
branches/mergetest/python/asaplotgui.py
r1563 r1779 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): -
branches/mergetest/python/asaplotgui_gtk.py
r1563 r1779 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 -
branches/mergetest/python/asapmath.py
r1591 r1779 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 6 @print_log_dec 5 from asap import asaplog 6 from asap import asaplotgui 7 8 #@print_log_dec 7 9 def average_time(*args, **kwargs): 8 10 """ … … 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 115 @print_log_dec125 #@print_log_dec 116 126 def dototalpower(calon, caloff, tcalval=0.0): 117 127 """ … … 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 133 @print_log_dec144 #@print_log_dec 134 145 def dosigref(sig, ref, smooth, tsysval=0.0, tauval=0.0): 135 146 """ … … 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 @print_log_dec154 def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0 ):165 #@print_log_dec 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 @print_log_dec242 def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0 ):448 #@print_log_dec 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 @print_log_dec313 def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0 ):689 #@print_log_dec 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 896 353 354 @print_log_dec 897 #@print_log_dec 355 898 def merge(*args): 356 899 """ … … 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 -
branches/mergetest/python/asapplotter.py
r1739 r1779 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) 60 71 61 @print_log_dec 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 78 79 #@print_log_dec 62 80 def plot(self, scan=None): 63 81 """ … … 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 … … 170 180 def text(self, *args, **kwargs): 171 181 if kwargs.has_key("interactive"): 172 if kwargs.pop("interactive"): 173 pos = self._plotter.get_point() 174 args = tuple(pos)+args 182 #if kwargs.pop("interactive"): 183 # pos = self._plotter.get_point() 184 # args = tuple(pos)+args 185 kwargs.pop("interactive") 175 186 self._axes_callback("text", *args, **kwargs) 176 187 … … 179 190 def arrow(self, *args, **kwargs): 180 191 if kwargs.has_key("interactive"): 181 if kwargs.pop("interactive"): 182 pos = self._plotter.get_region() 183 dpos = (pos[0][0], pos[0][1], 184 pos[1][0]-pos[0][0], 185 pos[1][1] - pos[0][1]) 186 args = dpos + args 192 #if kwargs.pop("interactive"): 193 # pos = self._plotter.get_region() 194 # dpos = (pos[0][0], pos[0][1], 195 # pos[1][0]-pos[0][0], 196 # pos[1][1] - pos[0][1]) 197 # args = dpos + args 198 kwargs.pop("interactive") 187 199 self._axes_callback("arrow", *args, **kwargs) 188 200 … … 191 203 def annotate(self, text, xy=None, xytext=None, **kwargs): 192 204 if kwargs.has_key("interactive"): 193 if kwargs.pop("interactive"): 194 xy = self._plotter.get_point() 195 xytext = self._plotter.get_point() 205 #if kwargs.pop("interactive"): 206 # xy = self._plotter.get_point() 207 # xytext = self._plotter.get_point() 208 kwargs.pop("interactive") 196 209 if not kwargs.has_key("arrowprops"): 197 210 kwargs["arrowprops"] = dict(arrowstyle="->") … … 202 215 def axvline(self, *args, **kwargs): 203 216 if kwargs.has_key("interactive"): 204 if kwargs.pop("interactive"): 205 pos = self._plotter.get_point() 206 args = (pos[0],)+args 217 #if kwargs.pop("interactive"): 218 # pos = self._plotter.get_point() 219 # args = (pos[0],)+args 220 kwargs.pop("interactive") 207 221 self._axes_callback("axvline", *args, **kwargs) 208 222 … … 211 225 def axhline(self, *args, **kwargs): 212 226 if kwargs.has_key("interactive"): 213 if kwargs.pop("interactive"): 214 pos = self._plotter.get_point() 215 args = (pos[1],)+args 227 #if kwargs.pop("interactive"): 228 # pos = self._plotter.get_point() 229 # args = (pos[1],)+args 230 kwargs.pop("interactive") 216 231 self._axes_callback("axhline", *args, **kwargs) 217 232 … … 220 235 def axvspan(self, *args, **kwargs): 221 236 if kwargs.has_key("interactive"): 222 if kwargs.pop("interactive"): 223 pos = self._plotter.get_region() 224 dpos = (pos[0][0], pos[1][0]) 225 args = dpos + args 237 #if kwargs.pop("interactive"): 238 # pos = self._plotter.get_region() 239 # dpos = (pos[0][0], pos[1][0]) 240 # args = dpos + args 241 kwargs.pop("interactive") 226 242 self._axes_callback("axvspan", *args, **kwargs) 227 243 # hack to preventy mpl from redrawing the patch … … 234 250 def axhspan(self, *args, **kwargs): 235 251 if kwargs.has_key("interactive"): 236 if kwargs.pop("interactive"):237 pos = self._plotter.get_region()238 dpos = (pos[0][1], pos[1][1])239 args = dpos + args240 252 #if kwargs.pop("interactive"): 253 # pos = self._plotter.get_region() 254 # dpos = (pos[0][1], pos[1][1]) 255 # args = dpos + args 256 kwargs.pop("interactive") 241 257 self._axes_callback("axhspan", *args, **kwargs) 242 258 # hack to preventy mpl from redrawing the patch … … 265 281 # end matplotlib.axes fowarding functions 266 282 267 268 def set_mode(self, stacking=None, panelling=None): 283 def set_data(self, scan, refresh=True): 284 """ 285 Set a scantable to plot. 286 Parameters: 287 scan: a scantable 288 refresh: True (default) or False. If True, the plot is 289 replotted based on the new parameter setting(s). 290 Otherwise,the parameter(s) are set without replotting. 291 Note: 292 The user specified masks and data selections will be reset 293 if a new scantable is set. This method should be called before 294 setting data selections (set_selection) and/or masks (set_mask). 295 """ 296 from asap import scantable 297 if isinstance(scan, scantable): 298 if self._data is not None: 299 if scan != self._data: 300 self._data = scan 301 # reset 302 self._reset() 303 msg = "A new scantable is set to the plotter. The masks and data selections are reset." 304 asaplog.push( msg ) 305 print_log( 'INFO' ) 306 else: 307 self._data = scan 308 self._reset() 309 else: 310 msg = "Input is not a scantable" 311 if rcParams['verbose']: 312 #print msg 313 asaplog.push( msg ) 314 print_log( 'ERROR' ) 315 return 316 raise TypeError(msg) 317 318 # ranges become invalid when unit changes 319 if self._abcunit and self._abcunit != self._data.get_unit(): 320 self._minmaxx = None 321 self._minmaxy = None 322 self._abcunit = self._data.get_unit() 323 self._datamask = None 324 if refresh: self.plot() 325 326 327 def set_mode(self, stacking=None, panelling=None, refresh=True): 269 328 """ 270 329 Set the plots look and feel, i.e. what you want to see on the plot. … … 274 333 panelling: tell the plotter which variable to plot 275 334 across multiple panels (default 'scan' 335 refresh: True (default) or False. If True, the plot is 336 replotted based on the new parameter setting(s). 337 Otherwise,the parameter(s) are set without replotting. 276 338 Note: 277 339 Valid modes are: … … 286 348 not self.set_stacking(stacking): 287 349 if rcParams['verbose']: 288 print msg 350 #print msg 351 asaplog.push( msg ) 352 print_log( 'ERROR' ) 289 353 return 290 354 else: 291 355 raise TypeError(msg) 292 if self._data: self.plot(self._data)356 if refresh and self._data: self.plot(self._data) 293 357 return 294 358 … … 304 368 return False 305 369 306 def set_layout(self,rows=None,cols=None ):370 def set_layout(self,rows=None,cols=None,refresh=True): 307 371 """ 308 372 Set the multi-panel layout, i.e. how many rows and columns plots … … 311 375 rows: The number of rows of plots 312 376 cols: The number of columns of plots 377 refresh: True (default) or False. If True, the plot is 378 replotted based on the new parameter setting(s). 379 Otherwise,the parameter(s) are set without replotting. 313 380 Note: 314 381 If no argument is given, the potter reverts to its auto-plot … … 317 384 self._rows = rows 318 385 self._cols = cols 319 if self._data: self.plot(self._data)386 if refresh and self._data: self.plot(self._data) 320 387 return 321 388 … … 331 398 return False 332 399 333 def set_range(self,xstart=None,xend=None,ystart=None,yend=None ):400 def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True): 334 401 """ 335 402 Set the range of interest on the abcissa of the plot 336 403 Parameters: 337 404 [x,y]start,[x,y]end: The start and end points of the 'zoom' window 405 refresh: True (default) or False. If True, the plot is 406 replotted based on the new parameter setting(s). 407 Otherwise,the parameter(s) are set without replotting. 338 408 Note: 339 409 These become non-sensical when the unit changes. … … 349 419 else: 350 420 self._minmaxy = [ystart,yend] 351 if self._data: self.plot(self._data)421 if refresh and self._data: self.plot(self._data) 352 422 return 353 423 354 def set_legend(self, mp=None, fontsize = None, mode = 0 ):424 def set_legend(self, mp=None, fontsize = None, mode = 0, refresh=True): 355 425 """ 356 426 Specify a mapping for the legend instead of using the default … … 376 446 9: upper center 377 447 10: center 448 refresh: True (default) or False. If True, the plot is 449 replotted based on the new parameter setting(s). 450 Otherwise,the parameter(s) are set without replotting. 378 451 379 452 Example: … … 390 463 from matplotlib import rc as rcp 391 464 rcp('legend', fontsize=fontsize) 392 if self._data: 393 self.plot(self._data) 465 if refresh and self._data: self.plot(self._data) 394 466 return 395 467 396 def set_title(self, title=None, fontsize=None ):468 def set_title(self, title=None, fontsize=None, refresh=True): 397 469 """ 398 470 Set the title of the plot. If multiple panels are plotted, 399 471 multiple titles have to be specified. 472 Parameters: 473 refresh: True (default) or False. If True, the plot is 474 replotted based on the new parameter setting(s). 475 Otherwise,the parameter(s) are set without replotting. 400 476 Example: 401 477 # two panels are visible on the plotter … … 406 482 from matplotlib import rc as rcp 407 483 rcp('axes', titlesize=fontsize) 408 if self._data: self.plot(self._data)484 if refresh and self._data: self.plot(self._data) 409 485 return 410 486 411 def set_ordinate(self, ordinate=None, fontsize=None ):487 def set_ordinate(self, ordinate=None, fontsize=None, refresh=True): 412 488 """ 413 489 Set the y-axis label of the plot. If multiple panels are plotted, … … 416 492 ordinate: a list of ordinate labels. None (default) let 417 493 data determine the labels 494 refresh: True (default) or False. If True, the plot is 495 replotted based on the new parameter setting(s). 496 Otherwise,the parameter(s) are set without replotting. 418 497 Example: 419 498 # two panels are visible on the plotter … … 425 504 rcp('axes', labelsize=fontsize) 426 505 rcp('ytick', labelsize=fontsize) 427 if self._data: self.plot(self._data)506 if refresh and self._data: self.plot(self._data) 428 507 return 429 508 430 def set_abcissa(self, abcissa=None, fontsize=None ):509 def set_abcissa(self, abcissa=None, fontsize=None, refresh=True): 431 510 """ 432 511 Set the x-axis label of the plot. If multiple panels are plotted, … … 435 514 abcissa: a list of abcissa labels. None (default) let 436 515 data determine the labels 516 refresh: True (default) or False. If True, the plot is 517 replotted based on the new parameter setting(s). 518 Otherwise,the parameter(s) are set without replotting. 437 519 Example: 438 520 # two panels are visible on the plotter … … 444 526 rcp('axes', labelsize=fontsize) 445 527 rcp('xtick', labelsize=fontsize) 446 if self._data: self.plot(self._data)528 if refresh and self._data: self.plot(self._data) 447 529 return 448 530 449 def set_colors(self, colmap ):531 def set_colors(self, colmap, refresh=True): 450 532 """ 451 533 Set the colours to be used. The plotter will cycle through … … 453 535 Parameters: 454 536 colmap: a list of colour names 537 refresh: True (default) or False. If True, the plot is 538 replotted based on the new parameter setting(s). 539 Otherwise,the parameter(s) are set without replotting. 455 540 Example: 456 541 plotter.set_colors("red green blue") … … 462 547 colmap = colmap.split() 463 548 self._plotter.palette(0, colormap=colmap) 464 if self._data: self.plot(self._data)549 if refresh and self._data: self.plot(self._data) 465 550 466 551 # alias for english speakers 467 552 set_colours = set_colors 468 553 469 def set_histogram(self, hist=True, linewidth=None ):554 def set_histogram(self, hist=True, linewidth=None, refresh=True): 470 555 """ 471 556 Enable/Disable histogram-like plotting. … … 474 559 is taken from the .asaprc setting 475 560 plotter.histogram 561 refresh: True (default) or False. If True, the plot is 562 replotted based on the new parameter setting(s). 563 Otherwise,the parameter(s) are set without replotting. 476 564 """ 477 565 self._hist = hist … … 479 567 from matplotlib import rc as rcp 480 568 rcp('lines', linewidth=linewidth) 481 if self._data: self.plot(self._data)482 483 def set_linestyles(self, linestyles=None, linewidth=None ):569 if refresh and self._data: self.plot(self._data) 570 571 def set_linestyles(self, linestyles=None, linewidth=None, refresh=True): 484 572 """ 485 573 Set the linestyles to be used. The plotter will cycle through … … 491 579 'dashdotdot' and 'dashdashdot' are 492 580 possible 493 581 refresh: True (default) or False. If True, the plot is 582 replotted based on the new parameter setting(s). 583 Otherwise,the parameter(s) are set without replotting. 494 584 Example: 495 585 plotter.set_colors("black") … … 505 595 from matplotlib import rc as rcp 506 596 rcp('lines', linewidth=linewidth) 507 if self._data: self.plot(self._data)508 509 def set_font(self, **kwargs):597 if refresh and self._data: self.plot(self._data) 598 599 def set_font(self, refresh=True,**kwargs): 510 600 """ 511 601 Set font properties. … … 516 606 size: the 'general' font size, individual elements can be adjusted 517 607 seperately 608 refresh: True (default) or False. If True, the plot is 609 replotted based on the new parameter setting(s). 610 Otherwise,the parameter(s) are set without replotting. 518 611 """ 519 612 from matplotlib import rc as rcp … … 523 616 fdict[k] = v 524 617 self._fp = FontProperties(**fdict) 525 if self._data: 526 self.plot() 618 if refresh and self._data: self.plot(self._data) 619 620 def set_panellayout(self,layout=[],refresh=True): 621 """ 622 Set the layout of subplots. 623 Parameters: 624 layout: a list of subplots layout in figure coordinate (0-1), 625 i.e., fraction of the figure width or height. 626 The order of elements should be: 627 [left, bottom, right, top, horizontal space btw panels, 628 vertical space btw panels]. 629 refresh: True (default) or False. If True, the plot is 630 replotted based on the new parameter setting(s). 631 Otherwise,the parameter(s) are set without replotting. 632 Note 633 * When layout is not specified, the values are reset to the defaults 634 of matplotlib. 635 * If any element is set to be None, the current value is adopted. 636 """ 637 if layout == []: self._panellayout=self._reset_panellayout() 638 else: 639 self._panellayout=[None]*6 640 self._panellayout[0:len(layout)]=layout 641 #print "panel layout set to ",self._panellayout 642 if refresh and self._data: self.plot(self._data) 643 644 def _reset_panellayout(self): 645 ks=map(lambda x: 'figure.subplot.'+x, 646 ['left','bottom','right','top','hspace','wspace']) 647 return map(matplotlib.rcParams.get,ks) 527 648 528 649 def plot_lines(self, linecat=None, doppler=0.0, deltachan=10, rotate=90.0, … … 622 743 623 744 624 def set_mask(self, mask=None, selection=None ):745 def set_mask(self, mask=None, selection=None, refresh=True): 625 746 """ 626 747 Set a plotting mask for a specific polarization. … … 629 750 mask: a mask from scantable.create_mask 630 751 selection: the spectra to apply the mask to. 752 refresh: True (default) or False. If True, the plot is 753 replotted based on the new parameter setting(s). 754 Otherwise,the parameter(s) are set without replotting. 631 755 Example: 632 756 select = selector() … … 637 761 msg = "Can only set mask after a first call to plot()" 638 762 if rcParams['verbose']: 639 print msg 763 #print msg 764 asaplog.push( msg ) 765 print_log( 'ERROR' ) 640 766 return 641 767 else: … … 657 783 else: 658 784 self._maskselection = None 659 self.plot(self._data)785 if refresh: self.plot(self._data) 660 786 661 787 def _slice_indeces(self, data): … … 671 797 inc = -1 672 798 # find min index 673 while start > 0 and data[start] < mn: 674 start+= inc 799 #while start > 0 and data[start] < mn: 800 # start+= inc 801 minind=start 802 for ind in xrange(start,end+inc,inc): 803 if data[ind] > mn: break 804 minind=ind 675 805 # find max index 676 while end > 0 and data[end] > mx: 677 end-=inc 678 if end > 0: end +=1 806 #while end > 0 and data[end] > mx: 807 # end-=inc 808 #if end > 0: end +=1 809 maxind=end 810 for ind in xrange(end,start-inc,-inc): 811 if data[ind] < mx: break 812 maxind=ind 813 start=minind 814 end=maxind 679 815 if start > end: 680 return end,start 681 return start,end 816 return end,start+1 817 elif start < end: 818 return start,end+1 819 else: 820 return start,end 682 821 683 822 def _reset(self): … … 708 847 maxpanel, maxstack = 16,16 709 848 if n > maxpanel or nstack > maxstack: 710 from asap import asaplog711 849 maxn = 0 712 850 if nstack > maxstack: maxn = maxstack … … 715 853 "Selecting first %d selections..." % (maxn, maxn) 716 854 asaplog.push(msg) 717 print_log( )855 print_log('WARN') 718 856 n = min(n,maxpanel) 719 857 nstack = min(nstack,maxstack) 720 858 if n > 1: 721 859 ganged = rcParams['plotter.ganged'] 860 if self._panelling == 'i': 861 ganged = False 722 862 if self._rows and self._cols: 723 863 n = min(n,self._rows*self._cols) 724 864 self._plotter.set_panels(rows=self._rows,cols=self._cols, 725 nplots=n,ganged=ganged) 865 # nplots=n,ganged=ganged) 866 nplots=n,layout=self._panellayout,ganged=ganged) 726 867 else: 727 self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged) 868 # self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged) 869 self._plotter.set_panels(rows=n,cols=0,nplots=n,layout=self._panellayout,ganged=ganged) 728 870 else: 729 self._plotter.set_panels() 871 # self._plotter.set_panels() 872 self._plotter.set_panels(layout=self._panellayout) 730 873 r=0 731 874 nr = scan.nrow() … … 799 942 ylim= self._minmaxy or [ma.minimum(y),ma.maximum(y)] 800 943 allylim += ylim 944 else: 945 xlim = self._minmaxx or [] 946 allxlim += xlim 947 ylim= self._minmaxy or [] 948 allylim += ylim 801 949 stackcount += 1 802 950 # last in colour stack -> autoscale x 803 if stackcount == nstack :951 if stackcount == nstack and len(allxlim) > 0: 804 952 allxlim.sort() 805 self._plotter. axes.set_xlim([allxlim[0],allxlim[-1]])953 self._plotter.subplots[panelcount-1]['axes'].set_xlim([allxlim[0],allxlim[-1]]) 806 954 # clear 807 955 allxlim =[] … … 813 961 if (panelcount == n) and (stackcount == nstack): 814 962 # last panel -> autoscale y if ganged 815 if rcParams['plotter.ganged'] :963 if rcParams['plotter.ganged'] and len(allylim) > 0: 816 964 allylim.sort() 817 965 self._plotter.set_limits(ylim=[allylim[0],allylim[-1]]) … … 820 968 #reset the selector to the scantable's original 821 969 scan.set_selection(savesel) 822 if self._fp is not None: 970 971 #temporary switch-off for older matplotlib 972 #if self._fp is not None: 973 if self._fp is not None and getattr(self._plotter.figure,'findobj',False): 823 974 for o in self._plotter.figure.findobj(Text): 824 975 o.set_fontproperties(self._fp) 825 976 826 827 977 def set_selection(self, selection=None, refresh=True, **kw): 978 """ 979 Parameters: 980 selection: a selector object (default unset the selection) 981 refresh: True (default) or False. If True, the plot is 982 replotted based on the new parameter setting(s). 983 Otherwise,the parameter(s) are set without replotting. 984 """ 828 985 if selection is None: 829 986 # reset … … 845 1002 order = [d0[self._panelling],d0[self._stacking]] 846 1003 self._selection.set_order(order) 847 if self._data and refresh: self.plot(self._data)1004 if refresh and self._data: self.plot(self._data) 848 1005 849 1006 def _get_selected_n(self, scan): … … 868 1025 poleval = scan._getpollabel(scan.getpol(row),scan.poltype()) 869 1026 d = {'b': "Beam "+str(scan.getbeam(row)), 870 's': scan._getsourcename(row), 1027 #'s': scan._getsourcename(row), 1028 's': "Scan "+str(scan.getscan(row))+\ 1029 " ("+str(scan._getsourcename(row))+")", 871 1030 'i': "IF"+str(scan.getif(row)), 872 1031 'p': poleval, … … 874 1033 return userlabel or d[mode] 875 1034 876 def plotazel(self): 1035 def plotazel(self, scan=None, outfile=None): 1036 #def plotazel(self): 877 1037 """ 878 1038 plot azimuth and elevation versus time of a scantable … … 883 1043 from matplotlib.ticker import MultipleLocator 884 1044 from numpy import array, pi 1045 self._data = scan 1046 self._outfile = outfile 885 1047 dates = self._data.get_time(asdatetime=True) 886 1048 t = PL.date2num(dates) … … 889 1051 PL.ioff() 890 1052 PL.clf() 1053 # Adjust subplot layouts 1054 if len(self._panellayout) !=6: self.set_panellayout(refresh=False) 1055 lef, bot, rig, top, wsp, hsp = self._panellayout 1056 PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top, 1057 wspace=wsp,hspace=hsp) 1058 891 1059 tdel = max(t) - min(t) 892 1060 ax = PL.subplot(2,1,1) … … 910 1078 911 1079 PL.title(dstr) 912 PL.plot_date(t,el,'b,', tz=tz) 1080 if tdel == 0.0: 1081 th = (t - PL.floor(t))*24.0 1082 PL.plot(th,el,'o',markersize=2, markerfacecolor='b', markeredgecolor='b') 1083 else: 1084 PL.plot_date(t,el,'o', markersize=2, markerfacecolor='b', markeredgecolor='b',tz=tz) 1085 #ax.grid(True) 1086 ax.xaxis.set_major_formatter(timefmt) 1087 ax.xaxis.set_major_locator(majloc) 1088 ax.xaxis.set_minor_locator(minloc) 913 1089 ax.yaxis.grid(True) 914 1090 yloc = MultipleLocator(30) 1091 ax.set_ylim(0,90) 1092 ax.yaxis.set_major_locator(yloc) 915 1093 if tdel > 1.0: 916 1094 labels = ax.get_xticklabels() 917 1095 # PL.setp(labels, fontsize=10, rotation=45) 918 1096 PL.setp(labels, fontsize=10) 1097 919 1098 # Az plot 920 1099 az = array(self._data.get_azimuth())*180./pi … … 923 1102 if az[irow] < 0: az[irow] += 360.0 924 1103 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) 1104 ax2 = PL.subplot(2,1,2) 1105 #PL.xlabel('Time (UT [hour])') 1106 PL.ylabel('Az [deg.]') 1107 if tdel == 0.0: 1108 PL.plot(th,az,'o',markersize=2, markeredgecolor='b',markerfacecolor='b') 1109 else: 1110 PL.plot_date(t,az,'o', markersize=2,markeredgecolor='b',markerfacecolor='b',tz=tz) 1111 ax2.xaxis.set_major_formatter(timefmt) 1112 ax2.xaxis.set_major_locator(majloc) 1113 ax2.xaxis.set_minor_locator(minloc) 1114 #ax2.grid(True) 1115 ax2.set_ylim(0,360) 929 1116 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) 1117 #hfmt = DateFormatter('%H') 1118 #hloc = HourLocator() 1119 yloc = MultipleLocator(60) 1120 ax2.yaxis.set_major_locator(yloc) 1121 if tdel > 1.0: 1122 labels = ax2.get_xticklabels() 1123 PL.setp(labels, fontsize=10) 1124 PL.xlabel('Time (UT [day])') 1125 else: 1126 PL.xlabel('Time (UT [hour])') 1127 934 1128 PL.ion() 935 1129 PL.draw() 936 937 def plotpointing(self): 1130 if (self._outfile is not None): 1131 PL.savefig(self._outfile) 1132 1133 def plotpointing(self, scan=None, outfile=None): 1134 #def plotpointing(self): 938 1135 """ 939 1136 plot telescope pointings 940 1137 """ 941 1138 from matplotlib import pylab as PL 942 from numpy import array 1139 from numpy import array, pi 1140 self._data = scan 1141 self._outfile = outfile 943 1142 dir = array(self._data.get_directionval()).transpose() 944 1143 ra = dir[0]*180./pi 945 1144 dec = dir[1]*180./pi 946 1145 PL.cla() 947 PL.ioff()1146 #PL.ioff() 948 1147 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]) 1148 # Adjust subplot layouts 1149 if len(self._panellayout) !=6: self.set_panellayout(refresh=False) 1150 lef, bot, rig, top, wsp, hsp = self._panellayout 1151 PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top, 1152 wspace=wsp,hspace=hsp) 1153 ax = PL.gca() 1154 #ax = PL.axes([0.1,0.1,0.8,0.8]) 1155 #ax = PL.axes([0.1,0.1,0.8,0.8]) 951 1156 ax.set_aspect('equal') 952 1157 PL.plot(ra, dec, 'b,') … … 956 1161 [xmin,xmax,ymin,ymax] = PL.axis() 957 1162 PL.axis([xmax,xmin,ymin,ymax]) 958 PL.ion()1163 #PL.ion() 959 1164 PL.draw() 1165 if (self._outfile is not None): 1166 PL.savefig(self._outfile) 1167 1168 # plot total power data 1169 # plotting in time is not yet implemented.. 1170 def plottp(self, scan=None, outfile=None): 1171 if self._plotter.is_dead: 1172 if hasattr(self._plotter.figmgr,'casabar'): 1173 del self._plotter.figmgr.casabar 1174 self._plotter = self._newplotter() 1175 self._plotter.figmgr.casabar=self._newcasabar() 1176 self._plotter.hold() 1177 self._plotter.clear() 1178 from asap import scantable 1179 if not self._data and not scan: 1180 msg = "Input is not a scantable" 1181 if rcParams['verbose']: 1182 #print msg 1183 asaplog.push( msg ) 1184 print_log( 'ERROR' ) 1185 return 1186 raise TypeError(msg) 1187 if isinstance(scan, scantable): 1188 if self._data is not None: 1189 if scan != self._data: 1190 self._data = scan 1191 # reset 1192 self._reset() 1193 else: 1194 self._data = scan 1195 self._reset() 1196 # ranges become invalid when abcissa changes? 1197 #if self._abcunit and self._abcunit != self._data.get_unit(): 1198 # self._minmaxx = None 1199 # self._minmaxy = None 1200 # self._abcunit = self._data.get_unit() 1201 # self._datamask = None 1202 1203 # Adjust subplot layouts 1204 if len(self._panellayout) !=6: self.set_panellayout(refresh=False) 1205 lef, bot, rig, top, wsp, hsp = self._panellayout 1206 self._plotter.figure.subplots_adjust( 1207 left=lef,bottom=bot,right=rig,top=top,wspace=wsp,hspace=hsp) 1208 if self._plotter.figmgr.casabar: self._plotter.figmgr.casabar.disable_button() 1209 self._plottp(self._data) 1210 if self._minmaxy is not None: 1211 self._plotter.set_limits(ylim=self._minmaxy) 1212 self._plotter.release() 1213 self._plotter.tidy() 1214 self._plotter.show(hardrefresh=False) 1215 print_log() 1216 return 1217 1218 def _plottp(self,scan): 1219 """ 1220 private method for plotting total power data 1221 """ 1222 from matplotlib.numerix import ma, array, arange, logical_not 1223 r=0 1224 nr = scan.nrow() 1225 a0,b0 = -1,-1 1226 allxlim = [] 1227 allylim = [] 1228 y=[] 1229 self._plotter.set_panels() 1230 self._plotter.palette(0) 1231 #title 1232 #xlab = self._abcissa and self._abcissa[panelcount] \ 1233 # or scan._getabcissalabel() 1234 #ylab = self._ordinate and self._ordinate[panelcount] \ 1235 # or scan._get_ordinate_label() 1236 xlab = self._abcissa or 'row number' #or Time 1237 ylab = self._ordinate or scan._get_ordinate_label() 1238 self._plotter.set_axes('xlabel',xlab) 1239 self._plotter.set_axes('ylabel',ylab) 1240 lbl = self._get_label(scan, r, 's', self._title) 1241 if isinstance(lbl, list) or isinstance(lbl, tuple): 1242 # if 0 <= panelcount < len(lbl): 1243 # lbl = lbl[panelcount] 1244 # else: 1245 # get default label 1246 lbl = self._get_label(scan, r, self._panelling, None) 1247 self._plotter.set_axes('title',lbl) 1248 y=array(scan._get_column(scan._getspectrum,-1)) 1249 m = array(scan._get_column(scan._getmask,-1)) 1250 y = ma.masked_array(y,mask=logical_not(array(m,copy=False))) 1251 x = arange(len(y)) 1252 # try to handle spectral data somewhat... 1253 l,m = y.shape 1254 if m > 1: 1255 y=y.mean(axis=1) 1256 plotit = self._plotter.plot 1257 llbl = self._get_label(scan, r, self._stacking, None) 1258 self._plotter.set_line(label=llbl) 1259 if len(x) > 0: 1260 plotit(x,y) 1261 1262 1263 # forwards to matplotlib.Figure.text 1264 def figtext(self, *args, **kwargs): 1265 """ 1266 Add text to figure at location x,y (relative 0-1 coords). 1267 This method forwards *args and **kwargs to a Matplotlib method, 1268 matplotlib.Figure.text. 1269 See the method help for detailed information. 1270 """ 1271 self._plotter.text(*args, **kwargs) 1272 # end matplotlib.Figure.text forwarding function 1273 1274 1275 # printing header information 1276 def print_header(self, plot=True, fontsize=9, logger=False, selstr='', extrastr=''): 1277 """ 1278 print data (scantable) header on the plot and/or logger. 1279 Parameters: 1280 plot: whether or not print header info on the plot. 1281 fontsize: header font size (valid only plot=True) 1282 autoscale: whether or not autoscale the plot (valid only plot=True) 1283 logger: whether or not print header info on the logger. 1284 selstr: additional selection string (not verified) 1285 extrastr: additional string to print (not verified) 1286 """ 1287 if not plot and not logger: return 1288 if not self._data: raise RuntimeError("No scantable has been set yet.") 1289 # Now header will be printed on plot and/or logger. 1290 # Get header information and format it. 1291 ssum=self._data.__str__() 1292 # Print Observation header to the upper-left corner of plot 1293 if plot: 1294 headstr=[ssum[ssum.find('Observer:'):ssum.find('Flux Unit:')]] 1295 headstr.append(ssum[ssum.find('Beams:'):ssum.find('Observer:')] 1296 +ssum[ssum.find('Rest Freqs:'):ssum.find('Abcissa:')]) 1297 if extrastr != '': headstr[0]=extrastr+'\n'+headstr[0] 1298 #headstr[1]='Data File: '+(filestr or 'unknown')+'\n'+headstr[1] 1299 ssel='***Selections***\n'+(selstr+self._data.get_selection().__str__() or 'none') 1300 headstr.append(ssel) 1301 nstcol=len(headstr) 1302 1303 self._plotter.hold() 1304 for i in range(nstcol): 1305 self._plotter.figure.text(0.03+float(i)/nstcol,0.98, 1306 headstr[i], 1307 horizontalalignment='left', 1308 verticalalignment='top', 1309 fontsize=fontsize) 1310 import time 1311 self._plotter.figure.text(0.99,0.0, 1312 time.strftime("%a %d %b %Y %H:%M:%S %Z"), 1313 horizontalalignment='right', 1314 verticalalignment='bottom',fontsize=8) 1315 self._plotter.release() 1316 del headstr, ssel 1317 if logger: 1318 asaplog.push("----------------\n Plot Summary\n----------------") 1319 asaplog.push(extrastr) 1320 asaplog.push(ssum[ssum.find('Beams:'):]) 1321 print_log() 1322 del ssum 1323 1324 -
branches/mergetest/python/asapreader.py
r1695 r1779 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): … … 25 25 rpfits ONLY. 26 26 """ 27 @print_log_dec27 #@print_log_dec 28 28 def __init__(self, filename, unit=None, theif=None, thebeam=None): 29 29 self.unit = unit … … 46 46 filename = expandvars(filename) 47 47 stfiller.__init__(self, filename, theif, thebeam) 48 print_log() 48 49 49 @print_log_dec50 #@print_log_dec 50 51 def read(self): 51 52 """ … … 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 -
branches/mergetest/python/linecatalog.py
r1534 r1779 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: -
branches/mergetest/python/scantable.py
r1731 r1779 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) 90 91 @print_log_dec 128 print_log() 129 130 #@print_log_dec 92 131 def save(self, name=None, format=None, overwrite=False): 93 132 """ … … 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 … … 578 752 return self._get_column(self._getdirectionvec, row) 579 753 580 @print_log_dec754 #@print_log_dec 581 755 def set_unit(self, unit='channel'): 582 756 """ … … 594 768 self._add_history("set_unit", varlist) 595 769 596 @print_log_dec770 #@print_log_dec 597 771 def set_instrument(self, instr): 598 772 """ … … 604 778 self._setInstrument(instr) 605 779 self._add_history("set_instument", vars()) 606 607 @print_log_dec 780 print_log() 781 782 #@print_log_dec 608 783 def set_feedtype(self, feedtype): 609 784 """ … … 614 789 self._setfeedtype(feedtype) 615 790 self._add_history("set_feedtype", vars()) 616 617 @print_log_dec 791 print_log() 792 793 #@print_log_dec 618 794 def set_doppler(self, doppler='RADIO'): 619 795 """ … … 627 803 self._setcoordinfo(inf) 628 804 self._add_history("set_doppler", vars()) 629 630 @print_log_dec 805 print_log() 806 807 #@print_log_dec 631 808 def set_freqframe(self, frame=None): 632 809 """ … … 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 720 @print_log_dec 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 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) … … 757 994 return s 758 995 759 @print_log_dec996 #@print_log_dec 760 997 def create_mask(self, *args, **kwargs): 761 998 """ … … 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"], "MHz") 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() 887 for i in xrange(len(freqs)): 888 sel.set_ifs(iflist[i]) 889 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() 1240 if len(freqs)>len(iflist): 1241 raise ValueError("number of elements in list of list exeeds the current IF selections") 897 1242 for i in xrange(len(freqs)): 898 1243 sel.set_ifs(iflist[i]) … … 905 1250 sel = selector() 906 1251 savesel = self._getselection() 907 iflist = self.getifnos()908 1252 for i in xrange(freqs.nrow()): 909 1253 sel.set_ifs(iflist[i]) … … 963 1307 msg = "Illegal file name '%s'." % (filename) 964 1308 if rcParams['verbose']: 965 print msg 1309 #print msg 1310 asaplog.push( msg ) 1311 print_log( 'ERROR' ) 966 1312 else: 967 1313 raise IOError(msg) … … 978 1324 # Maths business 979 1325 # 980 @print_log_dec1326 #@print_log_dec 981 1327 def average_time(self, mask=None, scanav=False, weight='tint', align=False): 982 1328 """ … … 1020 1366 except RuntimeError, msg: 1021 1367 if rcParams['verbose']: 1022 print msg 1368 #print msg 1369 print_log() 1370 asaplog.push( str(msg) ) 1371 print_log( 'ERROR' ) 1023 1372 return 1024 1373 else: raise 1025 1374 s._add_history("average_time", varlist) 1375 print_log() 1026 1376 return s 1027 1377 1028 @print_log_dec1378 #@print_log_dec 1029 1379 def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None): 1030 1380 """ … … 1051 1401 s = scantable(self._math._convertflux(self, d, eta, jyperk)) 1052 1402 s._add_history("convert_flux", varlist) 1403 print_log() 1053 1404 if insitu: self._assign(s) 1054 1405 else: return s 1055 1406 1056 @print_log_dec1407 #@print_log_dec 1057 1408 def gain_el(self, poly=None, filename="", method="linear", insitu=None): 1058 1409 """ … … 1103 1454 s = scantable(self._math._gainel(self, poly, filename, method)) 1104 1455 s._add_history("gain_el", varlist) 1456 print_log() 1105 1457 if insitu: 1106 1458 self._assign(s) … … 1108 1460 return s 1109 1461 1110 @print_log_dec1462 #@print_log_dec 1111 1463 def freq_align(self, reftime=None, method='cubic', insitu=None): 1112 1464 """ … … 1130 1482 s = scantable(self._math._freq_align(self, reftime, method)) 1131 1483 s._add_history("freq_align", varlist) 1484 print_log() 1132 1485 if insitu: self._assign(s) 1133 1486 else: return s 1134 1487 1135 @print_log_dec1488 #@print_log_dec 1136 1489 def opacity(self, tau=None, insitu=None): 1137 1490 """ … … 1158 1511 s = scantable(self._math._opacity(self, tau)) 1159 1512 s._add_history("opacity", varlist) 1513 print_log() 1160 1514 if insitu: self._assign(s) 1161 1515 else: return s 1162 1516 1163 @print_log_dec1517 #@print_log_dec 1164 1518 def bin(self, width=5, insitu=None): 1165 1519 """ … … 1176 1530 s = scantable(self._math._bin(self, width)) 1177 1531 s._add_history("bin", varlist) 1532 print_log() 1178 1533 if insitu: 1179 1534 self._assign(s) … … 1181 1536 return s 1182 1537 1183 @print_log_dec1538 #@print_log_dec 1184 1539 def resample(self, width=5, method='cubic', insitu=None): 1185 1540 """ 1186 1541 Return a scan where all spectra have been binned up. 1187 1542 1188 1543 Parameters: 1189 1544 width: The bin width (default=5) in pixels … … 1200 1555 s = scantable(self._math._resample(self, method, width)) 1201 1556 s._add_history("resample", varlist) 1557 print_log() 1202 1558 if insitu: self._assign(s) 1203 1559 else: return s 1204 1560 1205 @print_log_dec1561 #@print_log_dec 1206 1562 def average_pol(self, mask=None, weight='none'): 1207 1563 """ … … 1218 1574 s = scantable(self._math._averagepol(self, mask, weight.upper())) 1219 1575 s._add_history("average_pol", varlist) 1576 print_log() 1220 1577 return s 1221 1578 1222 @print_log_dec1579 #@print_log_dec 1223 1580 def average_beam(self, mask=None, weight='none'): 1224 1581 """ … … 1235 1592 s = scantable(self._math._averagebeams(self, mask, weight.upper())) 1236 1593 s._add_history("average_beam", varlist) 1594 print_log() 1237 1595 return s 1238 1596 … … 1249 1607 self._add_history("parallactify", varlist) 1250 1608 1251 @print_log_dec1609 #@print_log_dec 1252 1610 def convert_pol(self, poltype=None): 1253 1611 """ … … 1263 1621 except RuntimeError, msg: 1264 1622 if rcParams['verbose']: 1265 print msg 1623 #print msg 1624 print_log() 1625 asaplog.push( str(msg) ) 1626 print_log( 'ERROR' ) 1266 1627 return 1267 1628 else: 1268 1629 raise 1269 1630 s._add_history("convert_pol", varlist) 1631 print_log() 1270 1632 return s 1271 1633 1272 @print_log_dec1273 def smooth(self, kernel="hanning", width=5.0, order=2, insitu=None):1634 #@print_log_dec 1635 def smooth(self, kernel="hanning", width=5.0, order=2, plot=False, insitu=None): 1274 1636 """ 1275 1637 Smooth the spectrum by the specified kernel (conserving flux). … … 1286 1648 specify the order of the polnomial. Ignored by all other 1287 1649 kernels. 1650 plot: plot the original and the smoothed spectra. 1651 In this each indivual fit has to be approved, by 1652 typing 'y' or 'n' 1288 1653 insitu: if False a new scantable is returned. 1289 1654 Otherwise, the scaling is done in-situ … … 1295 1660 self._math._setinsitu(insitu) 1296 1661 varlist = vars() 1662 1663 if plot: orgscan = self.copy() 1664 1297 1665 s = scantable(self._math._smooth(self, kernel.lower(), width, order)) 1298 1666 s._add_history("smooth", varlist) 1667 1668 if plot: 1669 if rcParams['plotter.gui']: 1670 from asap.asaplotgui import asaplotgui as asaplot 1671 else: 1672 from asap.asaplot import asaplot 1673 self._p=asaplot() 1674 self._p.set_panels() 1675 ylab=s._get_ordinate_label() 1676 #self._p.palette(0,["#777777","red"]) 1677 for r in xrange(s.nrow()): 1678 xsm=s._getabcissa(r) 1679 ysm=s._getspectrum(r) 1680 xorg=orgscan._getabcissa(r) 1681 yorg=orgscan._getspectrum(r) 1682 self._p.clear() 1683 self._p.hold() 1684 self._p.set_axes('ylabel',ylab) 1685 self._p.set_axes('xlabel',s._getabcissalabel(r)) 1686 self._p.set_axes('title',s._getsourcename(r)) 1687 self._p.set_line(label='Original',color="#777777") 1688 self._p.plot(xorg,yorg) 1689 self._p.set_line(label='Smoothed',color="red") 1690 self._p.plot(xsm,ysm) 1691 ### Ugly part for legend 1692 for i in [0,1]: 1693 self._p.subplots[0]['lines'].append([self._p.subplots[0]['axes'].lines[i]]) 1694 self._p.release() 1695 ### Ugly part for legend 1696 self._p.subplots[0]['lines']=[] 1697 res = raw_input("Accept smoothing ([y]/n): ") 1698 if res.upper() == 'N': 1699 s._setspectrum(yorg, r) 1700 self._p.unmap() 1701 self._p = None 1702 del orgscan 1703 1704 print_log() 1299 1705 if insitu: self._assign(s) 1300 1706 else: return s 1301 1707 1302 @print_log_dec1708 #@print_log_dec 1303 1709 def poly_baseline(self, mask=None, order=0, plot=False, uselin=False, 1304 1710 insitu=None): … … 1321 1727 """ 1322 1728 if insitu is None: insitu = rcParams['insitu'] 1729 if not insitu: 1730 workscan = self.copy() 1731 else: 1732 workscan = self 1323 1733 varlist = vars() 1324 1734 if mask is None: 1325 1735 mask = [True for i in xrange(self.nchan(-1))] 1736 1326 1737 from asap.asapfitter import fitter 1327 1738 try: 1328 1739 f = fitter() 1329 f.set_scan(self, mask)1330 #f.set_function(poly=order)1331 1740 if uselin: 1332 1741 f.set_function(lpoly=order) 1333 1742 else: 1334 1743 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 1744 1745 rows = range(workscan.nrow()) 1746 if len(rows) > 0: 1747 self.blpars = [] 1748 1749 for r in rows: 1750 # take into account flagtra info (CAS-1434) 1751 flagtra = workscan._getmask(r) 1752 actualmask = mask[:] 1753 if len(actualmask) == 0: 1754 actualmask = list(flagtra[:]) 1755 else: 1756 if len(actualmask) != len(flagtra): 1757 raise RuntimeError, "Mask and flagtra have different length" 1758 else: 1759 for i in range(0, len(actualmask)): 1760 actualmask[i] = actualmask[i] and flagtra[i] 1761 f.set_scan(workscan, actualmask) 1762 f.x = workscan._getabcissa(r) 1763 f.y = workscan._getspectrum(r) 1764 f.data = None 1765 f.fit() 1766 if plot: 1767 f.plot(residual=True) 1768 x = raw_input("Accept fit ( [y]/n ): ") 1769 if x.upper() == 'N': 1770 self.blpars.append(None) 1771 continue 1772 workscan._setspectrum(f.fitter.getresidual(), r) 1773 self.blpars.append(f.get_parameters()) 1774 1775 if plot: 1776 f._p.unmap() 1777 f._p = None 1778 workscan._add_history("poly_baseline", varlist) 1779 print_log() 1780 if insitu: self._assign(workscan) 1781 else: return workscan 1339 1782 except RuntimeError: 1340 1783 msg = "The fit failed, possibly because it didn't converge." 1341 1784 if rcParams['verbose']: 1342 print msg 1785 #print msg 1786 print_log() 1787 asaplog.push( str(msg) ) 1788 print_log( 'ERROR' ) 1343 1789 return 1344 1790 else: 1345 1791 raise RuntimeError(msg) 1792 1346 1793 1347 1794 def auto_poly_baseline(self, mask=[], edge=(0, 0), order=0, … … 1427 1874 1428 1875 rows = range(workscan.nrow()) 1876 # Save parameters of baseline fits & masklists as a class attribute. 1877 # NOTICE: It does not reflect changes in scantable! 1878 if len(rows) > 0: 1879 self.blpars=[] 1880 self.masklists=[] 1429 1881 asaplog.push("Processing:") 1430 1882 for r in rows: … … 1441 1893 curedge = edge[workscan.getif(r)] 1442 1894 1895 # take into account flagtra info (CAS-1434) 1896 flagtra = workscan._getmask(r) 1897 actualmask = mask[:] 1898 if len(actualmask) == 0: 1899 actualmask = list(flagtra[:]) 1900 else: 1901 if len(actualmask) != len(flagtra): 1902 raise RuntimeError, "Mask and flagtra have different length" 1903 else: 1904 for i in range(0, len(actualmask)): 1905 actualmask[i] = actualmask[i] and flagtra[i] 1906 1443 1907 # 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())) 1908 fl.find_lines(r, actualmask, curedge) 1909 outmask=fl.get_mask() 1910 f.set_scan(workscan, fl.get_mask()) 1911 f.x = workscan._getabcissa(r) 1912 f.y = workscan._getspectrum(r) 1913 f.data = None 1447 1914 f.fit() 1448 x = f.get_parameters() 1915 1916 # Show mask list 1917 masklist=workscan.get_masklist(fl.get_mask(),row=r) 1918 msg = "mask range: "+str(masklist) 1919 asaplog.push(msg, False) 1920 1449 1921 if plot: 1450 1922 f.plot(residual=True) 1451 1923 x = raw_input("Accept fit ( [y]/n ): ") 1452 1924 if x.upper() == 'N': 1925 self.blpars.append(None) 1926 self.masklists.append(None) 1453 1927 continue 1928 1454 1929 workscan._setspectrum(f.fitter.getresidual(), r) 1930 self.blpars.append(f.get_parameters()) 1931 self.masklists.append(masklist) 1455 1932 if plot: 1456 1933 f._p.unmap() … … 1462 1939 return workscan 1463 1940 1464 @print_log_dec1941 #@print_log_dec 1465 1942 def rotate_linpolphase(self, angle): 1466 1943 """ … … 1476 1953 self._math._rotate_linpolphase(self, angle) 1477 1954 self._add_history("rotate_linpolphase", varlist) 1955 print_log() 1478 1956 return 1479 1957 1480 @print_log_dec1958 #@print_log_dec 1481 1959 def rotate_xyphase(self, angle): 1482 1960 """ … … 1492 1970 self._math._rotate_xyphase(self, angle) 1493 1971 self._add_history("rotate_xyphase", varlist) 1972 print_log() 1494 1973 return 1495 1974 1496 @print_log_dec1975 #@print_log_dec 1497 1976 def swap_linears(self): 1498 1977 """ … … 1503 1982 self._math._swap_linears(self) 1504 1983 self._add_history("swap_linears", varlist) 1984 print_log() 1505 1985 return 1506 1986 1507 @print_log_dec1987 #@print_log_dec 1508 1988 def invert_phase(self): 1509 1989 """ … … 1513 1993 self._math._invert_phase(self) 1514 1994 self._add_history("invert_phase", varlist) 1995 print_log() 1515 1996 return 1516 1997 1517 @print_log_dec1998 #@print_log_dec 1518 1999 def add(self, offset, insitu=None): 1519 2000 """ … … 1530 2011 s = scantable(self._math._unaryop(self, offset, "ADD", False)) 1531 2012 s._add_history("add", varlist) 2013 print_log() 1532 2014 if insitu: 1533 2015 self._assign(s) … … 1535 2017 return s 1536 2018 1537 @print_log_dec2019 #@print_log_dec 1538 2020 def scale(self, factor, tsys=True, insitu=None): 1539 2021 """ 1540 2022 Return a scan where all spectra are scaled by the give 'factor' 1541 2023 Parameters: 1542 factor: the scaling factor 2024 factor: the scaling factor (float or 1D float list) 1543 2025 insitu: if False a new scantable is returned. 1544 2026 Otherwise, the scaling is done in-situ … … 1550 2032 self._math._setinsitu(insitu) 1551 2033 varlist = vars() 1552 s = scantable(self._math._unaryop(self, factor, "MUL", tsys)) 2034 s = None 2035 import numpy 2036 if isinstance(factor, list) or isinstance(factor, numpy.ndarray): 2037 if isinstance(factor[0], list) or isinstance(factor[0], numpy.ndarray): 2038 from asapmath import _array2dOp 2039 s = _array2dOp( self.copy(), factor, "MUL", tsys ) 2040 else: 2041 s = scantable( self._math._arrayop( self.copy(), factor, "MUL", tsys ) ) 2042 else: 2043 s = scantable(self._math._unaryop(self.copy(), factor, "MUL", tsys)) 1553 2044 s._add_history("scale", varlist) 2045 print_log() 1554 2046 if insitu: 1555 2047 self._assign(s) … … 1593 2085 self._add_history("set_sourcetype", varlist) 1594 2086 1595 @print_log_dec1596 def auto_quotient(self, preserve=True, mode='paired' ):2087 #@print_log_dec 2088 def auto_quotient(self, preserve=True, mode='paired', verify=False): 1597 2089 """ 1598 2090 This function allows to build quotients automatically. 1599 It assumes the observation to have the same num er of2091 It assumes the observation to have the same number of 1600 2092 "ons" and "offs" 1601 2093 Parameters: … … 1634 2126 s = scantable(self._math._auto_quotient(self, mode, preserve)) 1635 2127 s._add_history("auto_quotient", varlist) 2128 print_log() 1636 2129 return s 1637 2130 1638 @print_log_dec2131 #@print_log_dec 1639 2132 def mx_quotient(self, mask = None, weight='median', preserve=True): 1640 2133 """ … … 1656 2149 q = quotient(on, off, preserve) 1657 2150 q._add_history("mx_quotient", varlist) 2151 print_log() 1658 2152 return q 1659 2153 1660 @print_log_dec2154 #@print_log_dec 1661 2155 def freq_switch(self, insitu=None): 1662 2156 """ … … 1674 2168 s = scantable(self._math._freqswitch(self)) 1675 2169 s._add_history("freq_switch", varlist) 2170 print_log() 1676 2171 if insitu: self._assign(s) 1677 2172 else: return s 1678 2173 1679 @print_log_dec2174 #@print_log_dec 1680 2175 def recalc_azel(self): 1681 2176 """ … … 1688 2183 self._recalcazel() 1689 2184 self._add_history("recalc_azel", varlist) 2185 print_log() 1690 2186 return 1691 2187 1692 @print_log_dec2188 #@print_log_dec 1693 2189 def __add__(self, other): 1694 varlist = vars() 1695 s = None 1696 if isinstance(other, scantable): 1697 s = scantable(self._math._binaryop(self, other, "ADD")) 1698 elif isinstance(other, float): 1699 s = scantable(self._math._unaryop(self, other, "ADD", False)) 1700 else: 1701 raise TypeError("Other input is not a scantable or float value") 1702 s._add_history("operator +", varlist) 1703 return s 1704 1705 @print_log_dec 2190 """ 2191 implicit on all axes and on Tsys 2192 """ 2193 return self._operation( other, "ADD" ) 2194 2195 #@print_log_dec 1706 2196 def __sub__(self, other): 1707 2197 """ 1708 2198 implicit on all axes and on Tsys 1709 2199 """ 1710 varlist = vars() 1711 s = None 1712 if isinstance(other, scantable): 1713 s = scantable(self._math._binaryop(self, other, "SUB")) 1714 elif isinstance(other, float): 1715 s = scantable(self._math._unaryop(self, other, "SUB", False)) 1716 else: 1717 raise TypeError("Other input is not a scantable or float value") 1718 s._add_history("operator -", varlist) 1719 return s 1720 1721 @print_log_dec 2200 return self._operation( other, 'SUB' ) 2201 2202 #@print_log_dec 1722 2203 def __mul__(self, other): 1723 2204 """ 1724 2205 implicit on all axes and on Tsys 1725 2206 """ 1726 varlist = vars() 1727 s = None 1728 if isinstance(other, scantable): 1729 s = scantable(self._math._binaryop(self, other, "MUL")) 1730 elif isinstance(other, float): 1731 s = scantable(self._math._unaryop(self, other, "MUL", False)) 1732 else: 1733 raise TypeError("Other input is not a scantable or float value") 1734 s._add_history("operator *", varlist) 1735 return s 1736 1737 1738 @print_log_dec 2207 return self._operation( other, 'MUL' ) 2208 2209 #@print_log_dec 1739 2210 def __div__(self, other): 1740 2211 """ 1741 2212 implicit on all axes and on Tsys 1742 2213 """ 1743 varlist = vars() 1744 s = None 1745 if isinstance(other, scantable): 1746 s = scantable(self._math._binaryop(self, other, "DIV")) 1747 elif isinstance(other, float): 1748 if other == 0.0: 1749 raise ZeroDivisionError("Dividing by zero is not recommended") 1750 s = scantable(self._math._unaryop(self, other, "DIV", False)) 1751 else: 1752 raise TypeError("Other input is not a scantable or float value") 1753 s._add_history("operator /", varlist) 1754 return s 2214 return self._operation( other, 'DIV' ) 1755 2215 1756 2216 def get_fit(self, row=0): … … 1765 2225 fit = asapfit(self._getfit(row)) 1766 2226 if rcParams['verbose']: 1767 print fit 2227 #print fit 2228 asaplog.push( '%s' %(fit) ) 2229 print_log() 1768 2230 return 1769 2231 else: … … 1862 2324 return (sum(nchans)/len(nchans) == nchans[0]) 1863 2325 1864 def _fill(self, names, unit, average ):2326 def _fill(self, names, unit, average, getpt, antenna): 1865 2327 import os 1866 2328 from asap._asap import stfiller … … 1874 2336 if rcParams['verbose']: 1875 2337 asaplog.push(msg) 1876 print asaplog.pop().strip() 2338 #print asaplog.pop().strip() 2339 print_log( 'ERROR' ) 1877 2340 return 1878 2341 raise IOError(msg) … … 1889 2352 asaplog.push(msg, False) 1890 2353 print_log() 1891 r._open(name, -1, -1)2354 r._open(name, antenna, -1, -1, getpt) 1892 2355 r._read() 1893 2356 if average: … … 1901 2364 if unit is not None: 1902 2365 self.set_fluxunit(unit) 1903 self.set_freqframe(rcParams['scantable.freqframe'])2366 #self.set_freqframe(rcParams['scantable.freqframe']) 1904 2367 1905 2368 def __getitem__(self, key): … … 1926 2389 for i in range(len(self)): 1927 2390 yield self[i] 2391 2392 def _operation(self, other, opmode): 2393 varlist = vars() 2394 s = None 2395 import numpy 2396 if isinstance(other, scantable): 2397 s = scantable(self._math._binaryop(self.copy(), other, opmode)) 2398 elif isinstance(other, float) or isinstance(other, int): 2399 if opmode == 'DIV' and float(other) == 0.0: 2400 raise ZeroDivisionError("Dividing by zero is not recommended") 2401 s = scantable(self._math._unaryop(self.copy(), other, opmode, False)) 2402 elif isinstance(other, list) or isinstance(other, numpy.ndarray): 2403 if isinstance(other[0], list) or isinstance(other[0], numpy.ndarray): 2404 from asapmath import _array2dOp 2405 s = _array2dOp( self.copy(), other, opmode, False ) 2406 else: 2407 s = scantable(self._math._arrayop(self.copy(), other, opmode, False)) 2408 else: 2409 raise TypeError("Other input is not a scantable or float value or float list") 2410 opdic = {} 2411 opdic['ADD'] = '+' 2412 opdic['SUB'] = '-' 2413 opdic['MUL'] = '*' 2414 opdic['DIV'] = '/' 2415 s._add_history("operator %s" % opdic[opmode], varlist) 2416 print_log() 2417 return s 2418 2419 -
branches/mergetest/python/selector.py
r1596 r1779 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.