Changeset 1757 for branches/alma/python
- Timestamp:
- 06/09/10 19:03:06 (15 years ago)
- Location:
- branches/alma
- Files:
-
- 5 added
- 14 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/alma
-
Property svn:ignore
set to
.sconf_temp
.sconsign.dblite
-
Property svn:mergeinfo
set to
/branches/asap-3.x merged eligible
-
Property svn:ignore
set to
-
branches/alma/python/__init__.py
r1729 r1757 4 4 """ 5 5 import os,sys,shutil, platform 6 try: 7 from functools import wraps as wraps_dec 8 except ImportError: 9 from asap.compatibility import wraps as wraps_dec 6 10 7 11 # Set up CASAPATH and first time use of asap i.e. ~/.asap/* … … 33 37 #shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap") 34 38 # commented out by TT on 2009.06.23 for casapy use 35 ##shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 39 ##shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 36 40 ## userdir+"/ipy_user_conf.py") 37 41 f = file(userdir+"/asapuserfuncs.py", "w") … … 43 47 # upgrade to support later ipython versions 44 48 ##if not os.path.exists(userdir+"/ipy_user_conf.py"): 45 ## shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 49 ## shutil.copyfile(asapdata+"/data/ipy_user_conf.py", 46 50 ## userdir+"/ipy_user_conf.py") 47 51 … … 74 78 75 79 """ 76 77 80 fname = os.path.join( os.getcwd(), '.asaprc') 78 81 if os.path.exists(fname): return fname … … 109 112 'plotter.histogram' : [False, _validate_bool], 110 113 'plotter.papertype' : ['A4', str], 111 'plotter.xaxisformatting' : ['asap', str], 114 ## for older Matplotlib version 115 #'plotter.axesformatting' : ['mpl', str], 116 'plotter.axesformatting' : ['asap', str], 112 117 113 118 # scantable … … 118 123 'scantable.storage' : ['memory', str], 119 124 'scantable.history' : [True, _validate_bool], 120 'scantable.reference' : ['.*(e|w|_R)$', str] 125 'scantable.reference' : ['.*(e|w|_R)$', str], 126 'scantable.parallactify' : [False, _validate_bool] 121 127 # fitter 122 128 } … … 146 152 plotter.panelling : scan 147 153 148 # push panels together, to share axis labels154 # push panels together, to share axis labels 149 155 plotter.ganged : True 150 156 … … 164 170 165 171 # The formatting style of the xaxis 166 plotter. xaxisformatting : 'asap' or 'mpl'172 plotter.axesformatting : 'mpl' (default) or 'asap' (for old versions of matplotlib) 167 173 168 174 # scantable … … 189 195 # Control the identification of reference (off) scans 190 196 # This is has to be a regular expression 191 scantable.reference : .*(e|w|_R)$ 197 scantable.reference : .*(e|w|_R)$ 198 199 # Indicate whether the data was parallactified (total phase offest == 0.0) 200 scantable.parallactify : False 201 192 202 # Fitter 193 203 """ … … 290 300 291 301 def _n_bools(n, val): 292 return [ val for i in xrange(n) ] 302 return [ val for i in xrange(n) ] 293 303 294 304 def _is_sequence_or_number(param, ptype=int): … … 357 367 asaplog.disable() 358 368 369 370 def print_log_dec(f): 371 @wraps_dec(f) 372 def wrap_it(*args, **kw): 373 val = f(*args, **kw) 374 print_log() 375 return val 376 return wrap_it 377 359 378 def print_log(level='INFO'): 360 379 from taskinit import casalog … … 382 401 from scantable import scantable 383 402 from asaplinefind import linefinder 403 from simplelinefinder import simplelinefinder 384 404 from linecatalog import linecatalog 385 405 from interactivemask import interactivemask 406 from opacity import skydip 407 from opacity import model as opacity_model 386 408 387 409 if rcParams['useplotter']: … … 392 414 import matplotlib 393 415 if not matplotlib.sys.modules['matplotlib.backends']: matplotlib.use("TkAgg") 394 import pylab416 from matplotlib import pylab 395 417 xyplotter = pylab 396 418 plotter = asapplotter(gui) … … 402 424 403 425 __date__ = '$Date$'.split()[1] 404 __version__ = ' 2.3.1alma'426 __version__ = '3.0.0 alma' 405 427 # nrao casapy specific, get revision number 406 428 #__revision__ = ' unknown ' … … 427 449 428 450 def is_ipython(): 429 return ' __IP' in dir(sys.modules["__main__"])451 return 'IPython' in sys.modules.keys() 430 452 if is_ipython(): 431 453 def version(): print "ASAP %s(%s)"% (__version__, __date__) 454 432 455 def list_scans(t = scantable): 433 import types 434 globs = sys.modules['__main__'].__dict__.iteritems() 435 print "The user created scantables are:" 436 sts = map(lambda x: x[0], filter(lambda x: isinstance(x[1], t), globs)) 437 print filter(lambda x: not x.startswith('_'), sts) 438 return 456 import inspect 457 print "The user created scantables are: ", 458 globs=inspect.currentframe().f_back.f_locals.copy() 459 out = [ k for k,v in globs.iteritems() \ 460 if isinstance(v, scantable) and not k.startswith("_") ] 461 print out 462 return out 439 463 440 464 def commands(): … … 462 486 get_elevation - get the elevation of the scans 463 487 get_parangle - get the parallactic angle of the scans 488 get_coordinate - get the spectral coordinate for the given row, 489 which can be used for coordinate conversions 490 get_weather - get the weather condition parameters 464 491 get_unit - get the current unit 465 492 set_unit - set the abcissa unit to be used from this … … 506 533 mx_quotient - Form a quotient using MX data (off beams) 507 534 scale, *, / - return a scan scaled by a given factor 508 add, +, - - return a scan with given value added 535 add, + - return a scan with given value added 536 sub, - - return a scan with given value subtracted 509 537 bin - return a scan with binned channels 510 538 resample - return a scan with resampled channels … … 529 557 stddev - Determine the standard deviation of the current 530 558 beam/if/pol 559 get_row_selector - get the selection object for a specified row 560 number 531 561 [Selection] 532 562 selector - a selection object to set a subset of a scantable … … 590 620 plot - plot a scantable 591 621 plot_lines - plot a linecatalog overlay 622 plotazel - plot azimuth and elevation versus time 623 plotpointing - plot telescope pointings 592 624 save - save the plot to a file ('png' ,'ps' or 'eps') 593 625 set_mode - set the state of the plotter, i.e. … … 613 645 axhline,axvline - draw horizontal/vertical lines 614 646 axhspan,axvspan - draw horizontal/vertical regions 647 annotate - draw an arrow with label 648 create_mask - create a scnatble mask interactively 615 649 616 650 xyplotter - matplotlib/pylab plotting functions 617 618 [Reading files]619 reader - access rpfits/sdfits files620 open - attach reader to a file621 close - detach reader from file622 read - read in integrations623 summary - list info about all integrations624 651 625 652 [General] 626 653 commands - this command 627 654 print - print details about a variable 628 list_scans - list all scantables created b tthe user655 list_scans - list all scantables created by the user 629 656 list_files - list all files readable by asap (default rpf) 630 657 del - delete the given variable from memory … … 639 666 mask_not - boolean operations on masks created with 640 667 scantable.create_mask 668 skydip - gain opacity values from a sky dip observation 669 opacity_model - compute opacities fro given frequencies based on 670 atmospheric model 641 671 642 672 Note: -
branches/alma/python/asapfitter.py
r1701 r1757 1 1 import _asap 2 2 from asap import rcParams 3 from asap import print_log 3 from asap import print_log, print_log_dec 4 4 from asap import _n_bools 5 5 from asap import mask_and … … 79 79 Set the function to be fit. 80 80 Parameters: 81 poly: use a polynomial of the order given with nonlinear least squares fit 81 poly: use a polynomial of the order given with nonlinear least squares fit 82 82 lpoly: use polynomial of the order given with linear least squares fit 83 83 gauss: fit the number of gaussian specified … … 95 95 n = kwargs.get('poly') 96 96 self.components = [n] 97 self.uselinear = False 97 self.uselinear = False 98 98 elif kwargs.has_key('lpoly'): 99 99 self.fitfunc = 'poly' … … 106 106 self.fitfuncs = [ 'gauss' for i in range(n) ] 107 107 self.components = [ 3 for i in range(n) ] 108 self.uselinear = False 108 self.uselinear = False 109 109 elif kwargs.has_key('lorentz'): 110 110 n = kwargs.get('lorentz') … … 112 112 self.fitfuncs = [ 'lorentz' for i in range(n) ] 113 113 self.components = [ 3 for i in range(n) ] 114 self.uselinear = False 114 self.uselinear = False 115 115 else: 116 116 msg = "Invalid function type." … … 127 127 return 128 128 129 #@print_log_dec 129 130 def fit(self, row=0, estimate=False): 130 131 """ … … 164 165 self.data.getbeam(i), 165 166 self.data.getif(i), 166 self.data.getpol(i), 167 self.data.getpol(i), 167 168 self.data.getcycle(i)) 168 169 asaplog.push(out,False) … … 221 222 self.data._addfit(fit,self._fittedrow) 222 223 223 # def set_parameters(self, params, fixed=None, component=None):224 #@print_log_dec 224 225 def set_parameters(self,*args,**kwargs): 225 226 """ … … 543 544 return self.fitter.getfit() 544 545 546 #@print_log_dec 545 547 def commit(self): 546 548 """ … … 571 573 return scan 572 574 573 def plot(self, residual=False, components=None, plotparms=False, filename=None): 575 #@print_log_dec 576 def plot(self, residual=False, components=None, plotparms=False, 577 filename=None): 574 578 """ 575 579 Plot the last fit. … … 598 602 xlab = 'Abcissa' 599 603 ylab = 'Ordinate' 600 from matplotlib.numeriximport ma,logical_not,logical_and,array604 from numpy import ma,logical_not,logical_and,array 601 605 m = self.mask 602 606 if self.data: … … 606 610 array(self.data._getmask(self._fittedrow), 607 611 copy=False)) 608 612 609 613 ylab = self.data._get_ordinate_label() 610 614 … … 670 674 print_log() 671 675 676 #@print_log_dec 672 677 def auto_fit(self, insitu=None, plot=False): 673 678 """ … … 700 705 scan.getbeam(r), 701 706 scan.getif(r), 702 scan.getpol(r), 707 scan.getpol(r), 703 708 scan.getcycle(r)) 704 709 asaplog.push(out, False) … … 723 728 print_log() 724 729 return scan 725 -
branches/alma/python/asaplinefind.py
r929 r1757 41 41 42 42 def set_options(self,threshold=1.7320508075688772,min_nchan=3, 43 avg_limit=8,box_size=0.2 ):43 avg_limit=8,box_size=0.2,noise_box='all',noise_stat='mean80'): 44 44 """ 45 45 Set the parameters of the algorithm … … 55 55 this parameter can be averaged to search for 56 56 broad lines. Default is 8. 57 box_size A running mean box size specified as a fraction57 box_size A running mean/median box size specified as a fraction 58 58 of the total spectrum length. Default is 1/5 59 noise_box Area of the spectrum used to estimate noise stats 60 Both string values and numbers are allowed 61 Allowed string values: 62 'all' use all the spectrum (default) 63 'box' noise box is the same as running mean/median 64 box 65 Numeric values are defined as a fraction from the 66 spectrum size. Values should be positive. 67 (noise_box == box_size has the same effect as 68 noise_box = 'box') 69 noise_stat Statistics used to estimate noise, allowed values: 70 'mean80' use the 80% of the lowest deviations 71 in the noise box (default) 72 'median' median of deviations in the noise box 73 59 74 Note: For bad baselines threshold should be increased, 60 75 and avg_limit decreased (or even switched off completely by … … 62 77 undulations instead of real lines. 63 78 """ 64 self.finder.setoptions(threshold,min_nchan,avg_limit,box_size) 79 if noise_stat.lower() not in ["mean80",'median']: 80 raise RuntimeError, "noise_stat argument in linefinder.set_options can only be mean80 or median" 81 nStat = (noise_stat.lower() == "median") 82 nBox = -1. 83 if isinstance(noise_box,str): 84 if noise_box.lower() not in ['all','box']: 85 raise RuntimeError, "string-valued noise_box in linefinder.set_options can only be all or box" 86 if noise_box.lower() == 'box': 87 nBox = box_size 88 else: 89 nBox = float(noise_box) 90 self.finder.setoptions(threshold,min_nchan,avg_limit,box_size,nBox,nStat) 65 91 return 66 92 -
branches/alma/python/asaplot.py
r708 r1757 11 11 ASAP plotting class based on matplotlib. 12 12 """ 13 def __init__(self, rows=1, cols=0, title='', size= (8,4), buffering=False):13 def __init__(self, rows=1, cols=0, title='', size=None, buffering=False): 14 14 """ 15 15 Create a new instance of the ASAPlot plotting class. -
branches/alma/python/asaplotbase.py
r1723 r1757 10 10 from matplotlib.figure import Figure, Text 11 11 from matplotlib.font_manager import FontProperties as FP 12 from matplotlib.numeriximport sqrt12 from numpy import sqrt 13 13 from matplotlib import rc, rcParams 14 14 from asap import rcParams as asaprcParams 15 15 from matplotlib.ticker import OldScalarFormatter 16 from matplotlib.ticker import NullLocator17 16 18 17 # API change in mpl >= 0.98 … … 20 19 from matplotlib.transforms import blended_transform_factory 21 20 except ImportError: 22 from matplotlib.transforms import blend_xy_sep_transform 21 from matplotlib.transforms import blend_xy_sep_transform as blended_transform_factory 23 22 24 23 from asap import asaplog … … 29 28 print_log( 'WARN' ) 30 29 31 #class MyFormatter(OldScalarFormatter):32 # def __call__(self, x, pos=None):33 # last = len(self.locs)-234 # if pos==0:35 # return ''36 # else: return OldScalarFormatter.__call__(self, x, pos)37 38 30 class asaplotbase: 39 31 """ … … 41 33 """ 42 34 43 def __init__(self, rows=1, cols=0, title='', size= (8,6), buffering=False):35 def __init__(self, rows=1, cols=0, title='', size=None, buffering=False): 44 36 """ 45 37 Create a new instance of the ASAPlot plotting class. … … 157 149 fmt is the line style as in plot(). 158 150 """ 159 from matplotlib.numeriximport array160 from matplotlib.numerix.ma import MaskedArray151 from numpy import array 152 from numpy.ma import MaskedArray 161 153 if x is None: 162 154 if y is None: return … … 289 281 self.register('button_press', position_disable) 290 282 283 284 # 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 291 299 292 300 def region(self): … … 640 648 self.subplots[i]['axes'] = self.figure.add_subplot(rows, 641 649 cols, i+1) 642 if asaprcParams['plotter. xaxisformatting'] == 'mpl':650 if asaprcParams['plotter.axesformatting'] != 'mpl': 643 651 self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter()) 644 652 else: … … 646 654 self.subplots[i]['axes'] = self.figure.add_subplot(rows, 647 655 cols, i+1) 648 if asaprcParams['plotter. xaxisformatting'] != 'mpl':656 if asaprcParams['plotter.axesformatting'] != 'mpl': 649 657 650 658 self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter()) … … 730 738 731 739 from matplotlib.artist import setp 732 fp = FP(size=rcParams['xtick.labelsize']) 733 xts = fp.get_size_in_points()- (self.cols)/2 734 fp = FP(size=rcParams['ytick.labelsize']) 735 yts = fp.get_size_in_points() - (self.rows)/2 740 fpx = FP(size=rcParams['xtick.labelsize']) 741 xts = fpx.get_size_in_points()- (self.cols)/2 742 fpy = FP(size=rcParams['ytick.labelsize']) 743 yts = fpy.get_size_in_points() - (self.rows)/2 744 fpa = FP(size=rcParams['axes.labelsize']) 745 fpat = FP(size=rcParams['axes.titlesize']) 746 axsize = fpa.get_size_in_points() 747 tsize = fpat.get_size_in_points()-(self.cols)/2 736 748 for sp in self.subplots: 737 749 ax = sp['axes'] 738 #s = ax.title.get_size()739 #tsize = s-(self.cols+self.rows)740 s=FP(size=rcParams['axes.titlesize'])741 tsize = s.get_size_in_points()-(self.cols)/2742 750 ax.title.set_size(tsize) 743 fp = FP(size=rcParams['axes.labelsize'])744 751 setp(ax.get_xticklabels(), fontsize=xts) 745 752 setp(ax.get_yticklabels(), fontsize=yts) 746 origx = fp.get_size_in_points()747 origy = origx748 753 off = 0 749 754 if self.cols > 1: off = self.cols 750 xfsize = origx-off 751 ax.xaxis.label.set_size(xfsize) 755 ax.xaxis.label.set_size(axsize-off) 752 756 off = 0 753 757 if self.rows > 1: off = self.rows 754 yfsize = origy-off 755 ax.yaxis.label.set_size(yfsize) 758 ax.yaxis.label.set_size(axsize-off) 756 759 757 760 def subplot(self, i=None, inc=None): -
branches/alma/python/asaplotgui.py
r1699 r1757 16 16 """ 17 17 18 def __init__(self, rows=1, cols=0, title='', size= (8,6), buffering=False):18 def __init__(self, rows=1, cols=0, title='', size=None, buffering=False): 19 19 """ 20 20 Create a new instance of the ASAPlot plotting class. -
branches/alma/python/asaplotgui_gtk.py
r1619 r1757 18 18 """ 19 19 20 def __init__(self, rows=1, cols=0, title='', size= (8,6), buffering=False):20 def __init__(self, rows=1, cols=0, title='', size=None, buffering=False): 21 21 """ 22 22 Create a new instance of the ASAPlot plotting class. -
branches/alma/python/asaplotgui_qt4.py
r1640 r1757 18 18 """ 19 19 20 def __init__(self, rows=1, cols=0, title='', size= (8,6), buffering=False):20 def __init__(self, rows=1, cols=0, title='', size=None, buffering=False): 21 21 """ 22 22 Create a new instance of the ASAPlot plotting class. -
branches/alma/python/asapmath.py
r1693 r1757 1 1 from asap.scantable import scantable 2 2 from asap import rcParams 3 from asap import print_log 3 from asap import print_log, print_log_dec 4 4 from asap import selector 5 5 from asap import asaplog 6 6 from asap import asaplotgui 7 7 8 #@print_log_dec 8 9 def average_time(*args, **kwargs): 9 10 """ … … 29 30 # without using a mask 30 31 scanav = average_time(scana,scanb) 31 32 32 # or equivalent 33 # scanav = average_time([scana, scanb]) 33 34 # return the (time) averaged scan, i.e. the average of 34 35 # all correlator cycles … … 122 123 return s 123 124 125 #@print_log_dec 124 126 def dototalpower(calon, caloff, tcalval=0.0): 125 127 """ … … 140 142 return s 141 143 144 #@print_log_dec 142 145 def dosigref(sig, ref, smooth, tsysval=0.0, tauval=0.0): 143 146 """ … … 160 163 return s 161 164 165 #@print_log_dec 162 166 def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 163 167 """ … … 442 446 return ress 443 447 448 #@print_log_dec 444 449 def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 445 450 """ … … 682 687 return resspec 683 688 689 #@print_log_dec 684 690 def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False): 685 691 """ … … 889 895 return resspec 890 896 891 def simple_math(left, right, op='add', tsys=True): 892 """ 893 Apply simple mathematical binary operations to two 894 scan tables, returning the result in a new scan table. 895 The operation is applied to both the correlations and the TSys data 896 The cursor of the output scan is set to 0 897 Parameters: 898 left: the 'left' scan 899 right: the 'right' scan 900 op: the operation: 'add' (default), 'sub', 'mul', 'div' 901 tsys: if True (default) then apply the operation to Tsys 902 as well as the data 903 """ 904 #print "simple_math is deprecated use +=/* instead." 905 asaplog.push( "simple_math is deprecated use +=/* instead." ) 906 print_log('WARN') 907 897 #@print_log_dec 908 898 def merge(*args): 909 899 """ … … 914 904 Example: 915 905 myscans = [scan1, scan2] 916 917 918 906 allscans = merge(myscans) 907 # or equivalent 908 sameallscans = merge(scan1, scan2) 919 909 """ 920 910 varlist = vars() -
branches/alma/python/asapplotter.py
r1732 r1757 1 from asap import rcParams, print_log, selector 1 from asap import rcParams, print_log, print_log_dec 2 from asap import selector, scantable 2 3 from asap import asaplog 3 4 import matplotlib.axes 5 from matplotlib.font_manager import FontProperties 6 from matplotlib.text import Text 7 4 8 import re 5 9 … … 13 17 other variables. 14 18 """ 15 def __init__(self, visible=None ):19 def __init__(self, visible=None , **kwargs): 16 20 self._visible = rcParams['plotter.gui'] 17 21 if visible is not None: 18 22 self._visible = visible 19 self._plotter = self._newplotter( )23 self._plotter = self._newplotter(**kwargs) 20 24 if self._visible and matplotlib.get_backend() == "TkAgg": 21 25 from asap.casatoolbar import CustomToolbarTkAgg … … 42 46 self._selection = selector() 43 47 self._hist = rcParams['plotter.histogram'] 48 self._fp = FontProperties() 44 49 self._panellayout = self.set_panellayout(refresh=False) 45 50 … … 52 57 return None 53 58 54 def _newplotter(self ):59 def _newplotter(self, **kwargs): 55 60 backend=matplotlib.get_backend() 56 61 if not self._visible: … … 64 69 else: 65 70 from asap.asaplot import asaplot 66 return asaplot( )67 68 71 return asaplot(**kwargs) 72 73 #@print_log_dec 69 74 def plot(self, scan=None): 70 75 """ … … 101 106 return 102 107 108 def gca(self): 109 return self._plotter.figure.gca() 110 111 def refresh(self): 112 """Do a soft refresh""" 113 self._plotter.figure.show() 114 115 def create_mask(self, nwin=1, panel=0, color=None): 116 """ 117 Interactively define a mask.It retruns a mask that is equivalent to 118 the one created manually with scantable.create_mask. 119 Parameters: 120 nwin: The number of mask windows to create interactively 121 default is 1. 122 panel: Which panel to use for mask selection. This is useful 123 if different IFs are spread over panels (default 0) 124 """ 125 if self._data is None: 126 return [] 127 outmask = [] 128 self._plotter.subplot(panel) 129 xmin, xmax = self._plotter.axes.get_xlim() 130 marg = 0.05*(xmax-xmin) 131 self._plotter.axes.set_xlim(xmin-marg, xmax+marg) 132 self.refresh() 133 134 def cleanup(lines=False, texts=False, refresh=False): 135 if lines: 136 del self._plotter.axes.lines[-1] 137 if texts: 138 del self._plotter.axes.texts[-1] 139 if refresh: 140 self.refresh() 141 142 for w in xrange(nwin): 143 wpos = [] 144 self.text(0.05,1.0, "Add start boundary", 145 coords="relative", fontsize=10) 146 point = self._plotter.get_point() 147 cleanup(texts=True) 148 if point is None: 149 continue 150 wpos.append(point[0]) 151 self.axvline(wpos[0], color=color) 152 self.text(0.05,1.0, "Add end boundary", coords="relative", fontsize=10) 153 point = self._plotter.get_point() 154 cleanup(texts=True, lines=True) 155 if point is None: 156 self.refresh() 157 continue 158 wpos.append(point[0]) 159 self.axvspan(wpos[0], wpos[1], alpha=0.1, 160 edgecolor=color, facecolor=color) 161 ymin, ymax = self._plotter.axes.get_ylim() 162 outmask.append(wpos) 163 164 self._plotter.axes.set_xlim(xmin, xmax) 165 self.refresh() 166 if len(outmask) > 0: 167 return self._data.create_mask(*outmask) 168 return [] 103 169 104 170 # forwards to matplotlib axes 105 171 def text(self, *args, **kwargs): 172 if kwargs.has_key("interactive"): 173 #if kwargs.pop("interactive"): 174 # pos = self._plotter.get_point() 175 # args = tuple(pos)+args 176 kwargs.pop("interactive") 106 177 self._axes_callback("text", *args, **kwargs) 178 107 179 text.__doc__ = matplotlib.axes.Axes.text.__doc__ 180 108 181 def arrow(self, *args, **kwargs): 182 if kwargs.has_key("interactive"): 183 #if kwargs.pop("interactive"): 184 # pos = self._plotter.get_region() 185 # dpos = (pos[0][0], pos[0][1], 186 # pos[1][0]-pos[0][0], 187 # pos[1][1] - pos[0][1]) 188 # args = dpos + args 189 kwargs.pop("interactive") 109 190 self._axes_callback("arrow", *args, **kwargs) 191 110 192 arrow.__doc__ = matplotlib.axes.Axes.arrow.__doc__ 193 194 def annotate(self, text, xy=None, xytext=None, **kwargs): 195 if kwargs.has_key("interactive"): 196 #if kwargs.pop("interactive"): 197 # xy = self._plotter.get_point() 198 # xytext = self._plotter.get_point() 199 kwargs.pop("interactive") 200 if not kwargs.has_key("arrowprops"): 201 kwargs["arrowprops"] = dict(arrowstyle="->") 202 self._axes_callback("annotate", text, xy, xytext, **kwargs) 203 204 annotate.__doc__ = matplotlib.axes.Axes.annotate.__doc__ 205 111 206 def axvline(self, *args, **kwargs): 207 if kwargs.has_key("interactive"): 208 #if kwargs.pop("interactive"): 209 # pos = self._plotter.get_point() 210 # args = (pos[0],)+args 211 kwargs.pop("interactive") 112 212 self._axes_callback("axvline", *args, **kwargs) 213 113 214 axvline.__doc__ = matplotlib.axes.Axes.axvline.__doc__ 215 114 216 def axhline(self, *args, **kwargs): 217 if kwargs.has_key("interactive"): 218 #if kwargs.pop("interactive"): 219 # pos = self._plotter.get_point() 220 # args = (pos[1],)+args 221 kwargs.pop("interactive") 115 222 self._axes_callback("axhline", *args, **kwargs) 223 116 224 axhline.__doc__ = matplotlib.axes.Axes.axhline.__doc__ 225 117 226 def axvspan(self, *args, **kwargs): 227 if kwargs.has_key("interactive"): 228 #if kwargs.pop("interactive"): 229 # pos = self._plotter.get_region() 230 # dpos = (pos[0][0], pos[1][0]) 231 # args = dpos + args 232 kwargs.pop("interactive") 118 233 self._axes_callback("axvspan", *args, **kwargs) 119 234 # hack to preventy mpl from redrawing the patch 120 235 # it seem to convert the patch into lines on every draw. 121 236 # This doesn't happen in a test script??? 122 del self._plotter.axes.patches[-1] 237 #del self._plotter.axes.patches[-1] 238 123 239 axvspan.__doc__ = matplotlib.axes.Axes.axvspan.__doc__ 124 240 125 241 def axhspan(self, *args, **kwargs): 242 if kwargs.has_key("interactive"): 243 #if kwargs.pop("interactive"): 244 # pos = self._plotter.get_region() 245 # dpos = (pos[0][1], pos[1][1]) 246 # args = dpos + args 247 kwargs.pop("interactive") 126 248 self._axes_callback("axhspan", *args, **kwargs) 127 249 # hack to preventy mpl from redrawing the patch 128 250 # it seem to convert the patch into lines on every draw. 129 251 # This doesn't happen in a test script??? 130 del self._plotter.axes.patches[-1] 252 #del self._plotter.axes.patches[-1] 253 131 254 axhspan.__doc__ = matplotlib.axes.Axes.axhspan.__doc__ 132 255 … … 465 588 if refresh and self._data: self.plot(self._data) 466 589 467 def set_font(self, family=None, style=None, weight=None, size=None, refresh=True):590 def set_font(self, refresh=True,**kwargs): 468 591 """ 469 592 Set font properties. … … 479 602 """ 480 603 from matplotlib import rc as rcp 481 if isinstance(family, str): 482 rcp('font', family=family) 483 if isinstance(style, str): 484 rcp('font', style=style) 485 if isinstance(weight, str): 486 rcp('font', weight=weight) 487 if isinstance(size, float) or isinstance(size, int): 488 rcp('font', size=size) 604 fdict = {} 605 for k,v in kwargs.iteritems(): 606 if v: 607 fdict[k] = v 608 self._fp = FontProperties(**fdict) 489 609 if refresh and self._data: self.plot(self._data) 490 610 … … 540 660 if not self._data.get_unit().endswith("Hz"): 541 661 raise RuntimeError("Can only overlay linecatalogs when data is in frequency.") 542 from matplotlib.numeriximport ma662 from numpy import ma 543 663 for j in range(len(self._plotter.subplots)): 544 664 self._plotter.subplot(j) … … 716 836 if isinstance(nstack0, int): nstack = nstack0 717 837 else: nstack = len(nstack0) 718 maxpanel, maxstack = 16, 8838 maxpanel, maxstack = 16,16 719 839 if n > maxpanel or nstack > maxstack: 720 840 maxn = 0 … … 761 881 ylab = self._ordinate and self._ordinate[panelcount] \ 762 882 or scan._get_ordinate_label() 763 self._plotter.set_axes('xlabel', xlab)764 self._plotter.set_axes('ylabel', ylab)883 self._plotter.set_axes('xlabel', xlab) 884 self._plotter.set_axes('ylabel', ylab) 765 885 lbl = self._get_label(scan, r, self._panelling, self._title) 766 886 if isinstance(lbl, list) or isinstance(lbl, tuple): … … 781 901 y = scan._getspectrum(r) 782 902 m = scan._getmask(r) 783 from matplotlib.numeriximport logical_not, logical_and903 from numpy import logical_not, logical_and 784 904 if self._maskselection and len(self._usermask) == len(m): 785 905 if d[self._stacking](r) in self._maskselection[self._stacking]: 786 906 m = logical_and(m, self._usermask) 787 907 x = scan._getabcissa(r) 788 from matplotlib.numeriximport ma, array908 from numpy import ma, array 789 909 y = ma.masked_array(y,mask=logical_not(array(m,copy=False))) 790 910 if self._minmaxx is not None: … … 839 959 #reset the selector to the scantable's original 840 960 scan.set_selection(savesel) 841 842 def set_selection(self, selection=None, refresh=True): 961 962 #temporary switch-off for older matplotlib 963 #if self._fp is not None: 964 if self._fp is not None and getattr(self._plotter.figure,'findobj',False): 965 for o in self._plotter.figure.findobj(Text): 966 o.set_fontproperties(self._fp) 967 968 def set_selection(self, selection=None, refresh=True, **kw): 843 969 """ 844 970 Parameters: … … 848 974 Otherwise,the parameter(s) are set without replotting. 849 975 """ 850 self._selection = isinstance(selection,selector) and selection or selector() 976 if selection is None: 977 # reset 978 if len(kw) == 0: 979 self._selection = selector() 980 else: 981 # try keywords 982 for k in kw: 983 if k not in selector.fields: 984 raise KeyError("Invalid selection key '%s', valid keys are %s" % (k, selector.fields)) 985 self._selection = selector(**kw) 986 elif isinstance(selection, selector): 987 self._selection = selection 988 else: 989 raise TypeError("'selection' is not of type selector") 990 851 991 d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO', 852 992 'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' } … … 885 1025 886 1026 def plotazel(self, scan=None, outfile=None): 887 """ 888 plot azimuth and elevation versus time of a scantable 889 """ 890 import pylab as PL 891 from matplotlib.dates import DateFormatter, timezone, HourLocator, MinuteLocator, DayLocator 1027 #def plotazel(self): 1028 """ 1029 plot azimuth and elevation versus time of a scantable 1030 """ 1031 from matplotlib import pylab as PL 1032 from matplotlib.dates import DateFormatter, timezone 1033 from matplotlib.dates import HourLocator, MinuteLocator,SecondLocator, DayLocator 892 1034 from matplotlib.ticker import MultipleLocator 893 from matplotlib.numeriximport array, pi1035 from numpy import array, pi 894 1036 self._data = scan 895 1037 self._outfile = outfile … … 898 1040 tz = timezone('UTC') 899 1041 PL.cla() 900 #PL.ioff()1042 PL.ioff() 901 1043 PL.clf() 902 1044 # Adjust subplot layouts … … 917 1059 minloc = HourLocator(range(0,23,12)) 918 1060 timefmt = DateFormatter("%b%d") 1061 elif tdel > 24./60.: 1062 timefmt = DateFormatter('%H:%M') 1063 majloc = HourLocator() 1064 minloc = MinuteLocator(30) 919 1065 else: 920 timefmt = DateFormatter('%H') 921 majloc = HourLocator() 922 minloc = MinuteLocator(20) 1066 timefmt = DateFormatter('%H:%M') 1067 majloc = MinuteLocator(interval=5) 1068 minloc = SecondLocator(30) 1069 923 1070 PL.title(dstr) 924 925 1071 if tdel == 0.0: 926 1072 th = (t - PL.floor(t))*24.0 … … 947 1093 if az[irow] < 0: az[irow] += 360.0 948 1094 949 ax = PL.subplot(2,1,2)1095 ax2 = PL.subplot(2,1,2) 950 1096 #PL.xlabel('Time (UT [hour])') 951 1097 PL.ylabel('Az [deg.]') … … 954 1100 else: 955 1101 PL.plot_date(t,az,'o', markersize=2,markeredgecolor='b',markerfacecolor='b',tz=tz) 956 ax .xaxis.set_major_formatter(timefmt)957 ax .xaxis.set_major_locator(majloc)958 ax .xaxis.set_minor_locator(minloc)959 #ax .grid(True)960 ax .set_ylim(0,360)961 ax .yaxis.grid(True)1102 ax2.xaxis.set_major_formatter(timefmt) 1103 ax2.xaxis.set_major_locator(majloc) 1104 ax2.xaxis.set_minor_locator(minloc) 1105 #ax2.grid(True) 1106 ax2.set_ylim(0,360) 1107 ax2.yaxis.grid(True) 962 1108 #hfmt = DateFormatter('%H') 963 1109 #hloc = HourLocator() 964 1110 yloc = MultipleLocator(60) 965 ax .yaxis.set_major_locator(yloc)1111 ax2.yaxis.set_major_locator(yloc) 966 1112 if tdel > 1.0: 967 labels = ax .get_xticklabels()1113 labels = ax2.get_xticklabels() 968 1114 PL.setp(labels, fontsize=10) 969 1115 PL.xlabel('Time (UT [day])') … … 971 1117 PL.xlabel('Time (UT [hour])') 972 1118 973 #PL.ion()1119 PL.ion() 974 1120 PL.draw() 975 1121 if (self._outfile is not None): … … 977 1123 978 1124 def plotpointing(self, scan=None, outfile=None): 1125 #def plotpointing(self): 979 1126 """ 980 1127 plot telescope pointings 981 1128 """ 982 import pylab as PL 983 from matplotlib.dates import DateFormatter, timezone 984 from matplotlib.ticker import MultipleLocator 985 from matplotlib.numerix import array, pi, zeros 1129 from matplotlib import pylab as PL 1130 from numpy import array, pi 986 1131 self._data = scan 987 1132 self._outfile = outfile … … 1001 1146 #ax = PL.axes([0.1,0.1,0.8,0.8]) 1002 1147 ax.set_aspect('equal') 1003 PL.plot(ra, dec, 'b,')1148 PL.plot(ra, dec, 'b,') 1004 1149 PL.xlabel('RA [deg.]') 1005 1150 PL.ylabel('Declination [deg.]') … … 1135 1280 # Print Observation header to the upper-left corner of plot 1136 1281 if plot: 1137 srest=ssum[ssum.find('Rest Freqs:'):ssum.find('Abcissa:')]1138 shead=ssum[ssum.find('Beams:'):ssum.find('Flux Unit:')]1139 headstr=shead.split('\n\n')1140 if extrastr != '': headstr[ 1]=extrastr+'\n'+headstr[1]1282 headstr=[ssum[ssum.find('Observer:'):ssum.find('Flux Unit:')]] 1283 headstr.append(ssum[ssum.find('Beams:'):ssum.find('Observer:')] 1284 +ssum[ssum.find('Rest Freqs:'):ssum.find('Abcissa:')]) 1285 if extrastr != '': headstr[0]=extrastr+'\n'+headstr[0] 1141 1286 #headstr[1]='Data File: '+(filestr or 'unknown')+'\n'+headstr[1] 1142 headstr[0]=headstr[0]+'\n'+srest1143 headstr.reverse()1144 1287 ssel='***Selections***\n'+(selstr+self._data.get_selection().__str__() or 'none') 1145 1288 headstr.append(ssel) … … 1159 1302 verticalalignment='bottom',fontsize=8) 1160 1303 self._plotter.release() 1161 del srest, shead,headstr, ssel1304 del headstr, ssel 1162 1305 if logger: 1163 1306 asaplog.push("----------------\n Plot Summary\n----------------") -
branches/alma/python/asapreader.py
r1059 r1757 1 1 from asap._asap import stfiller 2 from asap import print_log 2 from asap import print_log, print_log_dec 3 3 4 4 class reader(stfiller): … … 25 25 rpfits ONLY. 26 26 """ 27 27 #@print_log_dec 28 28 def __init__(self, filename, unit=None, theif=None, thebeam=None): 29 29 self.unit = unit … … 48 48 print_log() 49 49 50 #@print_log_dec 50 51 def read(self): 51 52 """ -
branches/alma/python/scantable.py
r1701 r1757 1 import os 2 try: 3 from functools import wraps as wraps_dec 4 except ImportError: 5 from asap.compatibility import wraps as wraps_dec 6 1 7 from asap._asap import Scantable 2 8 from asap import rcParams 3 from asap import print_log 9 from asap import print_log, print_log_dec 4 10 from asap import asaplog 5 11 from asap import selector 6 12 from asap import linecatalog 13 from asap.coordinate import coordinate 7 14 from asap import _n_bools, mask_not, mask_and, mask_or 15 16 17 def preserve_selection(func): 18 @wraps_dec(func) 19 def wrap(obj, *args, **kw): 20 basesel = obj.get_selection() 21 val = func(obj, *args, **kw) 22 obj.set_selection(basesel) 23 return val 24 return wrap 25 26 27 def is_scantable(filename): 28 return (os.path.isdir(filename) 29 and not os.path.exists(filename+'/table.f1') 30 and os.path.exists(filename+'/table.info')) 31 8 32 9 33 class scantable(Scantable): … … 12 36 """ 13 37 14 def __init__(self, filename, average=None, unit=None, getpt=None, antenna=None): 38 #@print_log_dec 39 def __init__(self, filename, average=None, unit=None, getpt=None, antenna=None, parallactify=None): 15 40 """ 16 41 Create a scantable from a saved one or make a reference … … 36 61 antenna: Antenna selection. integer (id) or string (name 37 62 or id). 63 parallactify: Indcicate that the data had been parallatified. 64 Default is taken form rc file. 38 65 """ 39 66 if average is None: … … 57 84 return 58 85 antenna = tmpstr.rstrip(',') 86 parallactify = parallactify or rcParams['scantable.parallactify'] 59 87 varlist = vars() 60 88 from asap._asap import stmath … … 63 91 Scantable.__init__(self, filename) 64 92 else: 65 if isinstance(filename, str):# or \ 66 # (isinstance(filename, list) or isinstance(filename, tuple)) \ 67 # and isinstance(filename[-1], str): 68 import os.path 93 if isinstance(filename, str): 69 94 filename = os.path.expandvars(filename) 70 95 filename = os.path.expanduser(filename) … … 73 98 if rcParams['verbose']: 74 99 asaplog.push(s) 75 #print asaplog.pop().strip()76 100 print_log('ERROR') 77 101 return 78 102 raise IOError(s) 79 if os.path.isdir(filename) \ 80 and not os.path.exists(filename+'/table.f1'): 81 # crude check if asap table 82 if os.path.exists(filename+'/table.info'): 83 ondisk = rcParams['scantable.storage'] == 'disk' 84 Scantable.__init__(self, filename, ondisk) 85 if unit is not None: 86 self.set_fluxunit(unit) 87 # do not reset to the default freqframe 88 #self.set_freqframe(rcParams['scantable.freqframe']) 103 if is_scantable(filename): 104 ondisk = rcParams['scantable.storage'] == 'disk' 105 Scantable.__init__(self, filename, ondisk) 106 if unit is not None: 107 self.set_fluxunit(unit) 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 89 119 else: 90 msg = "The given file '%s'is not a valid " \ 91 "asap table." % (filename) 92 if rcParams['verbose']: 93 #print msg 94 asaplog.push( msg ) 95 print_log( 'ERROR' ) 96 return 97 else: 98 raise IOError(msg) 120 raise IOError(msg) 99 121 else: 100 122 self._fill([filename], unit, average, getpt, antenna) … … 102 124 and isinstance(filename[-1], str): 103 125 self._fill(filename, unit, average, getpt, antenna) 126 self.parallactify(parallactify) 104 127 self._add_history("scantable", varlist) 105 128 print_log() 106 129 130 #@print_log_dec 107 131 def save(self, name=None, format=None, overwrite=False): 108 132 """ … … 119 143 'MS2' (saves as an aips++ 120 144 MeasurementSet V2) 121 'FITS' (save as image FITS - not 145 'FITS' (save as image FITS - not 122 146 readable by class) 123 147 'CLASS' (save as FITS readable by CLASS) … … 130 154 """ 131 155 from os import path 132 if format is None: format =rcParams['scantable.save']156 format = format or rcParams['scantable.save'] 133 157 suffix = '.'+format.lower() 134 158 if name is None or name == "": … … 203 227 else: raise 204 228 try: 205 bsel = self.get_selection() 206 sel = selector() 207 sel.set_scans(allscans) 208 self.set_selection(bsel+sel) 209 scopy = self._copy() 210 self.set_selection(bsel) 211 return scantable(scopy) 229 sel = selector(scans=allscans) 230 return self._select_copy(sel) 212 231 except RuntimeError: 213 232 if rcParams['verbose']: … … 219 238 raise 220 239 240 def _select_copy(self, selection): 241 orig = self.get_selection() 242 self.set_selection(orig+selection) 243 cp = self.copy() 244 self.set_selection(orig) 245 return cp 221 246 222 247 def get_scan(self, scanid=None): … … 253 278 if type(scanid) is str: 254 279 sel.set_name(scanid) 255 self.set_selection(bsel+sel) 256 scopy = self._copy() 257 self.set_selection(bsel) 258 return scantable(scopy) 280 return self._select_copy(sel) 259 281 elif type(scanid) is int: 260 282 sel.set_scans([scanid]) 261 self.set_selection(bsel+sel) 262 scopy = self._copy() 263 self.set_selection(bsel) 264 return scantable(scopy) 283 return self._select_copy(sel) 265 284 elif type(scanid) is list: 266 285 sel.set_scans(scanid) 267 self.set_selection(sel) 268 scopy = self._copy() 269 self.set_selection(bsel) 270 return scantable(scopy) 286 return self._select_copy(sel) 271 287 else: 272 288 msg = "Illegal scanid type, use 'int' or 'list' if ints." … … 294 310 filename: the name of a file to write the putput to 295 311 Default - no file output 296 verbose: print extra info such as the frequency table297 The default (False) is taken from .asaprc298 312 """ 299 313 info = Scantable._summary(self, True) 300 #if verbose is None: verbose = rcParams['scantable.verbosesummary']301 314 if filename is not None: 302 315 if filename is "": … … 328 341 """Return the spectrum for the current row in the scantable as a list. 329 342 Parameters: 330 rowno: the row number to retrieve the spectrum from 343 rowno: the row number to retrieve the spectrum from 331 344 """ 332 345 return self._getspectrum(rowno) … … 335 348 """Return the mask for the current row in the scantable as a list. 336 349 Parameters: 337 rowno: the row number to retrieve the mask from 350 rowno: the row number to retrieve the mask from 338 351 """ 339 352 return self._getmask(rowno) … … 343 356 Parameters: 344 357 spec: the spectrum 345 rowno: the row number to set the spectrum for 358 rowno: the row number to set the spectrum for 346 359 """ 347 360 assert(len(spec) == self.nchan()) 348 361 return self._setspectrum(spec, rowno) 362 363 def get_coordinate(self, rowno): 364 """Return the (spectral) coordinate for a a given 'rowno'. 365 NOTE: 366 * This coordinate is only valid until a scantable method modifies 367 the frequency axis. 368 * This coordinate does contain the original frequency set-up 369 NOT the new frame. The conversions however are done using the user 370 specified frame (e.g. LSRK/TOPO). To get the 'real' coordinate, 371 use scantable.freq_align first. Without it there is no closure, 372 i.e. 373 c = myscan.get_coordinate(0) 374 c.to_frequency(c.get_reference_pixel()) != c.get_reference_value() 375 376 Parameters: 377 rowno: the row number for the spectral coordinate 378 379 """ 380 return coordinate(Scantable.get_coordinate(self, rowno)) 349 381 350 382 def get_selection(self): … … 360 392 return selector(self._getselection()) 361 393 362 def set_selection(self, selection= selector()):394 def set_selection(self, selection=None, **kw): 363 395 """ 364 396 Select a subset of the data. All following operations on this scantable 365 397 are only applied to thi selection. 366 398 Parameters: 367 selection: a selector object (default unset the selection) 399 selection: a selector object (default unset the selection), 400 401 or 402 403 any combination of 404 "pols", "ifs", "beams", "scans", "cycles", "name", "query" 405 368 406 Examples: 369 407 sel = selector() # create a selection object … … 372 410 scan.summary() # will only print summary of scanno 0 an 3 373 411 scan.set_selection() # unset the selection 374 """ 412 # or the equivalent 413 scan.set_selection(scans=[0,3]) 414 scan.summary() # will only print summary of scanno 0 an 3 415 scan.set_selection() # unset the selection 416 """ 417 if selection is None: 418 # reset 419 if len(kw) == 0: 420 selection = selector() 421 else: 422 # try keywords 423 for k in kw: 424 if k not in selector.fields: 425 raise KeyError("Invalid selection key '%s', valid keys are %s" % (k, selector.fields)) 426 selection = selector(**kw) 375 427 self._setselection(selection) 376 428 … … 425 477 scan.stats(stat='mean', mask=m) 426 478 """ 427 if mask == None: 428 mask = [] 429 axes = ['Beam', 'IF', 'Pol', 'Time'] 479 mask = mask or [] 430 480 if not self._check_ifs(): 431 481 raise ValueError("Cannot apply mask as the IFs have different " … … 441 491 if not rtnabc: statvals = self._math._stats(self, mask, stat) 442 492 443 out = '' 444 axes = [] 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 445 503 for i in range(self.nrow()): 446 axis = []447 axis.append(self.getscan(i))448 axis.append(self.getbeam(i))449 axis.append(self.getif(i))450 axis.append(self.getpol(i))451 axis.append(self.getcycle(i))452 axes.append(axis)453 tm = self._gettime(i)454 src = self._getsourcename(i)455 504 refstr = '' 456 505 statunit= '' … … 459 508 if rtnabc: 460 509 statvals.append(qx['value']) 461 #refstr = '(value: %3.3f' % (qy['value'])+' ['+qy['unit']+'])'462 510 refstr = ('(value: %'+form) % (qy['value'])+' ['+qy['unit']+'])' 463 511 statunit= '['+qx['unit']+']' 464 512 else: 465 #refstr = '(@ %3.3f' % (qx['value'])+' ['+qx['unit']+'])'466 513 refstr = ('(@ %'+form) % (qx['value'])+' ['+qx['unit']+'])' 467 #statunit= ' ['+qy['unit']+']' 468 out += 'Scan[%d] (%s) ' % (axis[0], src) 514 515 tm = self._gettime(i) 516 src = self._getsourcename(i) 517 out += 'Scan[%d] (%s) ' % (self.getscan(i), src) 469 518 out += 'Time[%s]:\n' % (tm) 470 if self.nbeam(-1) > 1: out += ' Beam[%d] ' % (axis[1]) 471 if self.nif(-1) > 1: out += ' IF[%d] ' % (axis[2]) 472 if self.npol(-1) > 1: out += ' Pol[%d] ' % (axis[3]) 473 #out += '= %3.3f ' % (statvals[i]) +refstr+'\n' 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' 474 525 out += ('= %'+form) % (statvals[i]) +' '+refstr+'\n' 475 out += "--------------------------------------------------\n"526 out += sep+"\n" 476 527 477 528 if rcParams['verbose']: … … 484 535 tmpfile='/tmp/tmp_'+usr+'_casapy_asap_scantable_stats' 485 536 f=open(tmpfile,'w') 486 print >> f, "--------------------------------------------------"487 print >> f, " ", stat, statunit488 print >> f, "--------------------------------------------------"537 print >> f, sep 538 print >> f, ' %s %s' % (label, statunit) 539 print >> f, sep 489 540 print >> f, out 490 541 f.close() … … 492 543 x=f.readlines() 493 544 f.close() 494 for xx in x: 495 asaplog.push( xx, False ) 545 blanc='' 546 asaplog.push(blanc.join(x), False) 547 #for xx in x: 548 # asaplog.push( xx, False ) 496 549 print_log() 497 #else:498 #retval = { 'axesnames': ['scanno', 'beamno', 'ifno', 'polno', 'cycleno'],499 # 'axes' : axes,500 # 'data': statvals}501 550 return statvals 502 551 … … 541 590 return list(Scantable.get_column_names(self)) 542 591 543 def get_tsys(self ):592 def get_tsys(self, row=-1): 544 593 """ 545 594 Return the System temperatures. … … 547 596 a list of Tsys values for the current selection 548 597 """ 549 598 if row > -1: 599 return self._get_column(self._gettsys, row) 550 600 return self._row_callback(self._gettsys, "Tsys") 551 601 602 603 def get_weather(self, row=-1): 604 values = self._get_column(self._get_weather, row) 605 if row > -1: 606 return {'temperature': values[0], 607 'pressure': values[1], 'humidity' : values[2], 608 'windspeed' : values[3], 'windaz' : values[4] 609 } 610 else: 611 out = [] 612 for r in values: 613 614 out.append({'temperature': r[0], 615 'pressure': r[1], 'humidity' : r[2], 616 'windspeed' : r[3], 'windaz' : r[4] 617 }) 618 return out 619 552 620 def _row_callback(self, callback, label): 553 axes = []554 axesnames = ['scanno', 'beamno', 'ifno', 'polno', 'cycleno']555 621 out = "" 556 622 outvec = [] 623 sep = '-'*50 557 624 for i in range(self.nrow()): 558 axis = []559 axis.append(self.getscan(i))560 axis.append(self.getbeam(i))561 axis.append(self.getif(i))562 axis.append(self.getpol(i))563 axis.append(self.getcycle(i))564 axes.append(axis)565 625 tm = self._gettime(i) 566 626 src = self._getsourcename(i) 567 out += 'Scan[%d] (%s) ' % ( axis[0], src)627 out += 'Scan[%d] (%s) ' % (self.getscan(i), src) 568 628 out += 'Time[%s]:\n' % (tm) 569 if self.nbeam(-1) > 1: out += ' Beam[%d] ' % (axis[1]) 570 if self.nif(-1) > 1: out += ' IF[%d] ' % (axis[2]) 571 if self.npol(-1) > 1: out += ' Pol[%d] ' % (axis[3]) 629 if self.nbeam(-1) > 1: 630 out += ' Beam[%d] ' % (self.getbeam(i)) 631 if self.nif(-1) > 1: out += ' IF[%d] ' % (self.getif(i)) 632 if self.npol(-1) > 1: out += ' Pol[%d] ' % (self.getpol(i)) 572 633 outvec.append(callback(i)) 573 634 out += '= %3.3f\n' % (outvec[i]) 574 out += "--------------------------------------------------\n"635 out += sep+'\n' 575 636 if rcParams['verbose']: 576 asaplog.push( "--------------------------------------------------")637 asaplog.push(sep) 577 638 asaplog.push(" %s" % (label)) 578 asaplog.push( "--------------------------------------------------")639 asaplog.push(sep) 579 640 asaplog.push(out) 580 641 print_log() 581 # disabled because the vector seems more useful582 #retval = {'axesnames': axesnames, 'axes': axes, 'data': outvec}583 642 return outvec 584 643 … … 624 683 none 625 684 """ 626 return self._get_column(self._getinttime, row) 627 685 return self._get_column(self._getinttime, row) 686 628 687 629 688 def get_sourcename(self, row=-1): … … 674 733 """ 675 734 Get a list of Positions on the sky (direction) for the observations. 676 Return a floatfor each integration in the scantable.735 Return a string for each integration in the scantable. 677 736 Parameters: 678 737 row: row no of integration. Default -1 return all rows … … 693 752 return self._get_column(self._getdirectionvec, row) 694 753 754 #@print_log_dec 695 755 def set_unit(self, unit='channel'): 696 756 """ … … 708 768 self._add_history("set_unit", varlist) 709 769 770 #@print_log_dec 710 771 def set_instrument(self, instr): 711 772 """ … … 719 780 print_log() 720 781 782 #@print_log_dec 721 783 def set_feedtype(self, feedtype): 722 784 """ … … 729 791 print_log() 730 792 793 #@print_log_dec 731 794 def set_doppler(self, doppler='RADIO'): 732 795 """ … … 742 805 print_log() 743 806 807 #@print_log_dec 744 808 def set_freqframe(self, frame=None): 745 809 """ … … 747 811 Parameters: 748 812 frame: an optional frame type, default 'LSRK'. Valid frames are: 749 ' REST', 'TOPO', 'LSRD', 'LSRK', 'BARY',813 'TOPO', 'LSRD', 'LSRK', 'BARY', 750 814 'GEO', 'GALACTO', 'LGROUP', 'CMB' 751 815 Examples: 752 816 scan.set_freqframe('BARY') 753 817 """ 754 if frame is None: frame = rcParams['scantable.freqframe'] 755 varlist = vars() 756 valid = ['REST', 'TOPO', 'LSRD', 'LSRK', 'BARY', \ 818 frame = frame or rcParams['scantable.freqframe'] 819 varlist = vars() 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', \ 757 824 'GEO', 'GALACTO', 'LGROUP', 'CMB'] 758 825 … … 829 896 """ 830 897 varlist = vars() 831 if mask is None: 832 mask = [] 898 mask = mask or [] 833 899 try: 834 900 self._flag(mask, unflag) … … 883 949 else: raise 884 950 self._add_history("clip", varlist) 885 886 def lag_flag(self, frequency, width=0.0, unit="GHz", insitu=None): 951 952 #@print_log_dec 953 def lag_flag(self, start, end, unit="MHz", insitu=None): 954 #def lag_flag(self, frequency, width=0.0, unit="GHz", insitu=None): 887 955 """ 888 956 Flag the data in 'lag' space by providing a frequency to remove. 889 Flagged data in the scantable gets set to 0.0 before the fft.957 Flagged data in the scantable gets interpolated over the region. 890 958 No taper is applied. 891 959 Parameters: 892 frequency: the frequency (really a period within the bandwidth)893 894 width: the width of the frequency to remove, to remove a895 range of frequencies around the centre.896 unit: the frequency unit (default "GHz")960 start: the start frequency (really a period within the 961 bandwidth) or period to remove 962 end: the end frequency or period to remove 963 unit: the frequency unit (default "MHz") or "" for 964 explicit lag channels 897 965 Notes: 898 It is recommended to flag edges of the band or strong 966 It is recommended to flag edges of the band or strong 899 967 signals beforehand. 900 968 """ … … 902 970 self._math._setinsitu(insitu) 903 971 varlist = vars() 904 base = { "GHz": 1000000000., "MHz": 1000000., "kHz": 1000., "Hz": 1. 905 if not base.has_key(unit):972 base = { "GHz": 1000000000., "MHz": 1000000., "kHz": 1000., "Hz": 1.} 973 if not (unit == "" or base.has_key(unit)): 906 974 raise ValueError("%s is not a valid unit." % unit) 907 975 try: 908 s = scantable(self._math._lag_flag(self, frequency*base[unit], 909 width*base[unit])) 976 if unit == "": 977 s = scantable(self._math._lag_flag(self, start, end, "lags")) 978 else: 979 s = scantable(self._math._lag_flag(self, start*base[unit], 980 end*base[unit], "frequency")) 910 981 except RuntimeError, msg: 911 982 if rcParams['verbose']: … … 923 994 return s 924 995 925 996 #@print_log_dec 926 997 def create_mask(self, *args, **kwargs): 927 998 """ … … 952 1023 c) 953 1024 mask only channel 400 954 msk = scan.create_mask([400, 400]) 955 """ 956 row = 0 957 if kwargs.has_key("row"): 958 row = kwargs.get("row") 1025 msk = scan.create_mask([400]) 1026 """ 1027 row = kwargs.get("row", 0) 959 1028 data = self._getabcissa(row) 960 1029 u = self._getcoordinfo()[0] … … 973 1042 and args or args[0] 974 1043 for window in ws: 975 if (len(window) != 2 or window[0] > window[1] ): 976 raise TypeError("A window needs to be defined as [min, max]") 1044 if len(window) == 1: 1045 window = [window[0], window[0]] 1046 if len(window) == 0 or len(window) > 2: 1047 raise ValueError("A window needs to be defined as [start(, end)]") 1048 if window[0] > window[1]: 1049 tmp = window[0] 1050 window[0] = window[1] 1051 window[1] = tmp 977 1052 for i in range(n): 978 1053 if data[i] >= window[0] and data[i] <= window[1]: … … 1127 1202 source and IF basis, use scantable.set_selection() before using 1128 1203 this function. 1129 # provide your scantable is call scan1204 # provide your scantable is called scan 1130 1205 selection = selector() 1131 1206 selection.set_name("ORION*") … … 1188 1263 1189 1264 def shift_refpix(self, delta): 1190 1191 Shift the reference pixel of the Spectra Coordinate by an 1192 1193 1194 1265 """ 1266 Shift the reference pixel of the Spectra Coordinate by an 1267 integer amount. 1268 Parameters: 1269 delta: the amount to shift by 1195 1270 Note: 1196 1197 """ 1198 Scantable.shift(self, delta)1271 Be careful using this with broadband data. 1272 """ 1273 Scantable.shift_refpix(self, delta) 1199 1274 1200 1275 def history(self, filename=None): … … 1249 1324 # Maths business 1250 1325 # 1251 1326 #@print_log_dec 1252 1327 def average_time(self, mask=None, scanav=False, weight='tint', align=False): 1253 1328 """ … … 1275 1350 """ 1276 1351 varlist = vars() 1277 if weight is None: weight = 'TINT' 1278 if mask is None: mask = () 1279 if scanav: scanav = "SCAN" 1280 else: scanav = "NONE" 1352 weight = weight or 'TINT' 1353 mask = mask or () 1354 scanav = (scanav and 'SCAN') or 'NONE' 1281 1355 scan = (self, ) 1282 1356 try: … … 1302 1376 return s 1303 1377 1378 #@print_log_dec 1304 1379 def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None): 1305 1380 """ … … 1321 1396 self._math._setinsitu(insitu) 1322 1397 varlist = vars() 1323 if jyperk is None: jyperk =-1.01324 if d is None: d =-1.01325 if eta is None: eta =-1.01398 jyperk = jyperk or -1.0 1399 d = d or -1.0 1400 eta = eta or -1.0 1326 1401 s = scantable(self._math._convertflux(self, d, eta, jyperk)) 1327 1402 s._add_history("convert_flux", varlist) … … 1330 1405 else: return s 1331 1406 1407 #@print_log_dec 1332 1408 def gain_el(self, poly=None, filename="", method="linear", insitu=None): 1333 1409 """ … … 1373 1449 self._math._setinsitu(insitu) 1374 1450 varlist = vars() 1375 if poly is None: 1376 poly = () 1451 poly = poly or () 1377 1452 from os.path import expandvars 1378 1453 filename = expandvars(filename) … … 1380 1455 s._add_history("gain_el", varlist) 1381 1456 print_log() 1382 if insitu: self._assign(s) 1383 else: return s 1384 1457 if insitu: 1458 self._assign(s) 1459 else: 1460 return s 1461 1462 #@print_log_dec 1385 1463 def freq_align(self, reftime=None, method='cubic', insitu=None): 1386 1464 """ … … 1401 1479 self._math._setinsitu(insitu) 1402 1480 varlist = vars() 1403 if reftime is None: reftime =""1481 reftime = reftime or "" 1404 1482 s = scantable(self._math._freq_align(self, reftime, method)) 1405 1483 s._add_history("freq_align", varlist) … … 1408 1486 else: return s 1409 1487 1410 def opacity(self, tau, insitu=None): 1488 #@print_log_dec 1489 def opacity(self, tau=None, insitu=None): 1411 1490 """ 1412 1491 Apply an opacity correction. The data 1413 1492 and Tsys are multiplied by the correction factor. 1414 1493 Parameters: 1415 tau: Opacity from which the correction factor is1494 tau: (list of) opacity from which the correction factor is 1416 1495 exp(tau*ZD) 1417 where ZD is the zenith-distance 1496 where ZD is the zenith-distance. 1497 If a list is provided, it has to be of length nIF, 1498 nIF*nPol or 1 and in order of IF/POL, e.g. 1499 [opif0pol0, opif0pol1, opif1pol0 ...] 1500 if tau is `None` the opacities are determined from a 1501 model. 1418 1502 insitu: if False a new scantable is returned. 1419 1503 Otherwise, the scaling is done in-situ … … 1423 1507 self._math._setinsitu(insitu) 1424 1508 varlist = vars() 1509 if not hasattr(tau, "__len__"): 1510 tau = [tau] 1425 1511 s = scantable(self._math._opacity(self, tau)) 1426 1512 s._add_history("opacity", varlist) … … 1429 1515 else: return s 1430 1516 1517 #@print_log_dec 1431 1518 def bin(self, width=5, insitu=None): 1432 1519 """ … … 1444 1531 s._add_history("bin", varlist) 1445 1532 print_log() 1446 if insitu: self._assign(s) 1447 else: return s 1448 1449 1533 if insitu: 1534 self._assign(s) 1535 else: 1536 return s 1537 1538 #@print_log_dec 1450 1539 def resample(self, width=5, method='cubic', insitu=None): 1451 1540 """ … … 1470 1559 else: return s 1471 1560 1472 1561 #@print_log_dec 1473 1562 def average_pol(self, mask=None, weight='none'): 1474 1563 """ … … 1482 1571 """ 1483 1572 varlist = vars() 1484 if mask is None: 1485 mask = () 1573 mask = mask or () 1486 1574 s = scantable(self._math._averagepol(self, mask, weight.upper())) 1487 1575 s._add_history("average_pol", varlist) … … 1489 1577 return s 1490 1578 1579 #@print_log_dec 1491 1580 def average_beam(self, mask=None, weight='none'): 1492 1581 """ … … 1500 1589 """ 1501 1590 varlist = vars() 1502 if mask is None: 1503 mask = () 1591 mask = mask or () 1504 1592 s = scantable(self._math._averagebeams(self, mask, weight.upper())) 1505 1593 s._add_history("average_beam", varlist) … … 1507 1595 return s 1508 1596 1597 def parallactify(self, pflag): 1598 """ 1599 Set a flag to inidcate whether this data should be treated as having 1600 been 'parallactified' (total phase == 0.0) 1601 Parameters: 1602 pflag: Bool inidcating whether to turn this on (True) or 1603 off (False) 1604 """ 1605 varlist = vars() 1606 self._parallactify(pflag) 1607 self._add_history("parallactify", varlist) 1608 1609 #@print_log_dec 1509 1610 def convert_pol(self, poltype=None): 1510 1611 """ 1511 1612 Convert the data to a different polarisation type. 1613 Note that you will need cross-polarisation terms for most conversions. 1512 1614 Parameters: 1513 1615 poltype: The new polarisation type. Valid types are: 1514 "linear", " stokes" and "circular"1616 "linear", "circular", "stokes" and "linpol" 1515 1617 """ 1516 1618 varlist = vars() … … 1530 1632 return s 1531 1633 1532 # def smooth(self, kernel="hanning", width=5.0, insitu=None):1533 def smooth(self, kernel="hanning", width=5.0, plot=False, insitu=None):1634 #@print_log_dec 1635 def smooth(self, kernel="hanning", width=5.0, order=2, plot=False, insitu=None): 1534 1636 """ 1535 1637 Smooth the spectrum by the specified kernel (conserving flux). 1536 1638 Parameters: 1537 1639 kernel: The type of smoothing kernel. Select from 1538 'hanning' (default), 'gaussian', 'boxcar' and1539 'rmedian'1640 'hanning' (default), 'gaussian', 'boxcar', 'rmedian' 1641 or 'poly' 1540 1642 width: The width of the kernel in pixels. For hanning this is 1541 1643 ignored otherwise it defauls to 5 pixels. 1542 1644 For 'gaussian' it is the Full Width Half 1543 1645 Maximum. For 'boxcar' it is the full width. 1544 For 'rmedian' it is the half width. 1646 For 'rmedian' and 'poly' it is the half width. 1647 order: Optional parameter for 'poly' kernel (default is 2), to 1648 specify the order of the polnomial. Ignored by all other 1649 kernels. 1545 1650 plot: plot the original and the smoothed spectra. 1546 1651 In this each indivual fit has to be approved, by … … 1558 1663 if plot: orgscan = self.copy() 1559 1664 1560 s = scantable(self._math._smooth(self, kernel.lower(), width ))1665 s = scantable(self._math._smooth(self, kernel.lower(), width, order)) 1561 1666 s._add_history("smooth", varlist) 1562 1667 … … 1601 1706 else: return s 1602 1707 1603 1604 def poly_baseline(self, mask=None, order=0, plot=False, uselin=False, insitu=None): 1708 #@print_log_dec 1709 def poly_baseline(self, mask=None, order=0, plot=False, uselin=False, 1710 insitu=None): 1605 1711 """ 1606 1712 Return a scan which has been baselined (all rows) by a polynomial. … … 1833 1939 return workscan 1834 1940 1941 #@print_log_dec 1835 1942 def rotate_linpolphase(self, angle): 1836 1943 """ … … 1849 1956 return 1850 1957 1851 1958 #@print_log_dec 1852 1959 def rotate_xyphase(self, angle): 1853 1960 """ … … 1866 1973 return 1867 1974 1975 #@print_log_dec 1868 1976 def swap_linears(self): 1869 1977 """ 1870 Swap the linear polarisations XX and YY, or better the first two 1978 Swap the linear polarisations XX and YY, or better the first two 1871 1979 polarisations as this also works for ciculars. 1872 1980 """ … … 1877 1985 return 1878 1986 1987 #@print_log_dec 1879 1988 def invert_phase(self): 1880 1989 """ … … 1887 1996 return 1888 1997 1998 #@print_log_dec 1889 1999 def add(self, offset, insitu=None): 1890 2000 """ … … 1907 2017 return s 1908 2018 2019 #@print_log_dec 1909 2020 def scale(self, factor, tsys=True, insitu=None): 1910 2021 """ … … 1972 2083 self._setsourcetype(stype) 1973 2084 self.set_selection(basesel) 1974 s._add_history("set_sourcetype", varlist) 1975 2085 self._add_history("set_sourcetype", varlist) 2086 2087 #@print_log_dec 1976 2088 def auto_quotient(self, preserve=True, mode='paired', verify=False): 1977 2089 """ … … 1984 2096 preserve: Output = Toff * (on/off) - Toff 1985 2097 remove: Output = Toff * (on/off) - Ton 1986 mode: the on/off detection mode 2098 mode: the on/off detection mode 1987 2099 'paired' (default) 1988 2100 identifies 'off' scans by the … … 2017 2129 return s 2018 2130 2131 #@print_log_dec 2019 2132 def mx_quotient(self, mask = None, weight='median', preserve=True): 2020 2133 """ … … 2028 2141 remove: Output = Toff * (on/off) - Ton 2029 2142 """ 2030 if mask is None: mask =()2143 mask = mask or () 2031 2144 varlist = vars() 2032 2145 on = scantable(self._math._mx_extract(self, 'on')) … … 2039 2152 return q 2040 2153 2154 #@print_log_dec 2041 2155 def freq_switch(self, insitu=None): 2042 2156 """ … … 2058 2172 else: return s 2059 2173 2174 #@print_log_dec 2060 2175 def recalc_azel(self): 2061 2176 """ … … 2071 2186 return 2072 2187 2188 #@print_log_dec 2073 2189 def __add__(self, other): 2074 2190 """ … … 2077 2193 return self._operation( other, "ADD" ) 2078 2194 2195 #@print_log_dec 2079 2196 def __sub__(self, other): 2080 2197 """ … … 2083 2200 return self._operation( other, 'SUB' ) 2084 2201 2202 #@print_log_dec 2085 2203 def __mul__(self, other): 2086 2204 """ … … 2089 2207 return self._operation( other, 'MUL' ) 2090 2208 2209 #@print_log_dec 2091 2210 def __div__(self, other): 2092 2211 """ … … 2120 2239 basesel = self.get_selection() 2121 2240 for i in range(self.nrow()): 2122 sel = selector()+basesel 2123 sel.set_scans(self.getscan(i)) 2124 sel.set_beams(self.getbeam(i)) 2125 sel.set_ifs(self.getif(i)) 2126 sel.set_polarisations(self.getpol(i)) 2127 self.set_selection(sel) 2241 sel = self.get_row_selector(i) 2242 self.set_selection(basesel+sel) 2128 2243 nans = numpy.isnan(self._getspectrum(0)) 2129 2244 if numpy.any(nans): … … 2131 2246 self.flag(bnans) 2132 2247 self.set_selection(basesel) 2133 2248 2249 def get_row_selector(self, rowno): 2250 return selector(beams=self.getbeam(rowno), 2251 ifs=self.getif(rowno), 2252 pols=self.getpol(rowno), 2253 scans=self.getscan(rowno), 2254 cycles=self.getcycle(rowno)) 2134 2255 2135 2256 def _add_history(self, funcname, parameters): -
branches/alma/python/selector.py
r1693 r1757 7 7 scantables to specific rows. 8 8 """ 9 def __init(self): 10 _selector.__init__(self) 9 fields = ["pols", "ifs", "beams", "scans", "cycles", "name", "query"] 10 11 def __init__(self, *args, **kw): 12 if len(args) == 1: 13 if isinstance(args[0], self.__class__) \ 14 or isinstance(args[0], _selector): 15 _selector.__init__(self, args[0]) 16 else: 17 raise TypeError("Argument can only be a selector object") 18 else: 19 _selector.__init__(self) 20 for k,v in kw.items(): 21 if k in self.fields: 22 func = getattr(self, "set_%s" % k) 23 func(v) 11 24 12 25 def reset(self): … … 45 58 else: 46 59 raise TypeError('Unknown pol type. Please use [0,1...] or ["XX","YY"...]') 47 60 48 61 # for the americans 49 62 set_polarizations = set_polarisations … … 220 233 Merge two selections. 221 234 """ 235 if self.is_empty(): 236 return other 237 elif other.is_empty(): 238 return self 222 239 union = selector() 223 240 gets = [[self._getscans(), other._getscans(), union._setscans],
Note:
See TracChangeset
for help on using the changeset viewer.