Changeset 1757 for branches/alma/python


Ignore:
Timestamp:
06/09/10 19:03:06 (14 years ago)
Author:
Kana Sugimoto
Message:

New Development: Yes

JIRA Issue: Yes (CAS-2211)

Ready for Test: Yes

Interface Changes: Yes

What Interface Changed: ASAP 3.0.0 interface changes

Test Programs:

Put in Release Notes: Yes

Module(s): all the CASA sd tools and tasks are affected.

Description: Merged ATNF-ASAP 3.0.0 developments to CASA (alma) branch.

Note you also need to update casa/code/atnf.


Location:
branches/alma
Files:
5 added
14 edited

Legend:

Unmodified
Added
Removed
  • branches/alma

  • branches/alma/python/__init__.py

    r1729 r1757  
    44"""
    55import os,sys,shutil, platform
     6try:
     7    from functools import wraps as wraps_dec
     8except ImportError:
     9    from asap.compatibility import wraps as wraps_dec
    610
    711# Set up CASAPATH and first time use of asap i.e. ~/.asap/*
     
    3337    #shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap")
    3438    # 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",
    3640    ##                userdir+"/ipy_user_conf.py")
    3741    f = file(userdir+"/asapuserfuncs.py", "w")
     
    4347    # upgrade to support later ipython versions
    4448    ##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",
    4650    ##                    userdir+"/ipy_user_conf.py")
    4751
     
    7478
    7579    """
    76 
    7780    fname = os.path.join( os.getcwd(), '.asaprc')
    7881    if os.path.exists(fname): return fname
     
    109112    'plotter.histogram'  : [False, _validate_bool],
    110113    'plotter.papertype'  : ['A4', str],
    111     'plotter.xaxisformatting' : ['asap', str],
     114    ## for older Matplotlib version
     115    #'plotter.axesformatting' : ['mpl', str],
     116    'plotter.axesformatting' : ['asap', str],
    112117
    113118    # scantable
     
    118123    'scantable.storage'   : ['memory', str],
    119124    '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]
    121127    # fitter
    122128    }
     
    146152plotter.panelling          : scan
    147153
    148 # push panels together, to share axislabels
     154# push panels together, to share axis labels
    149155plotter.ganged             : True
    150156
     
    164170
    165171# The formatting style of the xaxis
    166 plotter.xaxisformatting    : 'asap' or 'mpl'
     172plotter.axesformatting    : 'mpl' (default) or 'asap' (for old versions of matplotlib)
    167173
    168174# scantable
     
    189195# Control the identification of reference (off) scans
    190196# This is has to be a regular expression
    191 scantable.reference         : .*(e|w|_R)$
     197scantable.reference        : .*(e|w|_R)$
     198
     199# Indicate whether the data was parallactified (total phase offest == 0.0)
     200scantable.parallactify     : False
     201
    192202# Fitter
    193203"""
     
    290300
    291301def _n_bools(n, val):
    292     return [ val for i in xrange(n) ] 
     302    return [ val for i in xrange(n) ]
    293303
    294304def _is_sequence_or_number(param, ptype=int):
     
    357367    asaplog.disable()
    358368
     369
     370def 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
    359378def print_log(level='INFO'):
    360379    from taskinit import casalog
     
    382401from scantable import scantable
    383402from asaplinefind import linefinder
     403from simplelinefinder import simplelinefinder
    384404from linecatalog import linecatalog
    385405from interactivemask import interactivemask
     406from opacity import skydip
     407from opacity import model as opacity_model
    386408
    387409if rcParams['useplotter']:
     
    392414            import matplotlib
    393415            if not matplotlib.sys.modules['matplotlib.backends']: matplotlib.use("TkAgg")
    394         import pylab
     416        from matplotlib import pylab
    395417        xyplotter = pylab
    396418        plotter = asapplotter(gui)
     
    402424
    403425__date__ = '$Date$'.split()[1]
    404 __version__  = '2.3.1 alma'
     426__version__  = '3.0.0 alma'
    405427# nrao casapy specific, get revision number
    406428#__revision__ = ' unknown '
     
    427449
    428450def is_ipython():
    429     return '__IP' in dir(sys.modules["__main__"])
     451    return 'IPython' in sys.modules.keys()
    430452if is_ipython():
    431453    def version(): print  "ASAP %s(%s)"% (__version__, __date__)
     454
    432455    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
    439463
    440464    def commands():
     
    462486            get_elevation   - get the elevation of the scans
    463487            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
    464491            get_unit        - get the current unit
    465492            set_unit        - set the abcissa unit to be used from this
     
    506533            mx_quotient     - Form a quotient using MX data (off beams)
    507534            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
    509537            bin             - return a scan with binned channels
    510538            resample        - return a scan with resampled channels
     
    529557            stddev          - Determine the standard deviation of the current
    530558                              beam/if/pol
     559            get_row_selector - get the selection object for a specified row
     560                               number
    531561     [Selection]
    532562         selector              - a selection object to set a subset of a scantable
     
    590620            plot            - plot a scantable
    591621            plot_lines      - plot a linecatalog overlay
     622            plotazel        - plot azimuth and elevation versus time
     623            plotpointing    - plot telescope pointings
    592624            save            - save the plot to a file ('png' ,'ps' or 'eps')
    593625            set_mode        - set the state of the plotter, i.e.
     
    613645            axhline,axvline - draw horizontal/vertical lines
    614646            axhspan,axvspan - draw horizontal/vertical regions
     647            annotate        - draw an arrow with label
     648            create_mask     - create a scnatble mask interactively
    615649
    616650        xyplotter           - matplotlib/pylab plotting functions
    617 
    618     [Reading files]
    619         reader              - access rpfits/sdfits files
    620             open            - attach reader to a file
    621             close           - detach reader from file
    622             read            - read in integrations
    623             summary         - list info about all integrations
    624651
    625652    [General]
    626653        commands            - this command
    627654        print               - print details about a variable
    628         list_scans          - list all scantables created bt the user
     655        list_scans          - list all scantables created by the user
    629656        list_files          - list all files readable by asap (default rpf)
    630657        del                 - delete the given variable from memory
     
    639666        mask_not            - boolean operations on masks created with
    640667                              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
    641671
    642672    Note:
  • branches/alma/python/asapfitter.py

    r1701 r1757  
    11import _asap
    22from asap import rcParams
    3 from asap import print_log
     3from asap import print_log, print_log_dec
    44from asap import _n_bools
    55from asap import mask_and
     
    7979        Set the function to be fit.
    8080        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
    8282            lpoly:   use polynomial of the order given with linear least squares fit
    8383            gauss:   fit the number of gaussian specified
     
    9595            n = kwargs.get('poly')
    9696            self.components = [n]
    97             self.uselinear = False 
     97            self.uselinear = False
    9898        elif kwargs.has_key('lpoly'):
    9999            self.fitfunc = 'poly'
     
    106106            self.fitfuncs = [ 'gauss' for i in range(n) ]
    107107            self.components = [ 3 for i in range(n) ]
    108             self.uselinear = False 
     108            self.uselinear = False
    109109        elif kwargs.has_key('lorentz'):
    110110            n = kwargs.get('lorentz')
     
    112112            self.fitfuncs = [ 'lorentz' for i in range(n) ]
    113113            self.components = [ 3 for i in range(n) ]
    114             self.uselinear = False 
     114            self.uselinear = False
    115115        else:
    116116            msg = "Invalid function type."
     
    127127        return
    128128
     129    #@print_log_dec
    129130    def fit(self, row=0, estimate=False):
    130131        """
     
    164165                                                                      self.data.getbeam(i),
    165166                                                                      self.data.getif(i),
    166                                                                       self.data.getpol(i), 
     167                                                                      self.data.getpol(i),
    167168                                                                      self.data.getcycle(i))
    168169                asaplog.push(out,False)
     
    221222                self.data._addfit(fit,self._fittedrow)
    222223
    223     #def set_parameters(self, params, fixed=None, component=None):
     224    #@print_log_dec
    224225    def set_parameters(self,*args,**kwargs):
    225226        """
     
    543544        return self.fitter.getfit()
    544545
     546    #@print_log_dec
    545547    def commit(self):
    546548        """
     
    571573        return scan
    572574
    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):
    574578        """
    575579        Plot the last fit.
     
    598602        xlab = 'Abcissa'
    599603        ylab = 'Ordinate'
    600         from matplotlib.numerix import ma,logical_not,logical_and,array
     604        from numpy import ma,logical_not,logical_and,array
    601605        m = self.mask
    602606        if self.data:
     
    606610                             array(self.data._getmask(self._fittedrow),
    607611                                   copy=False))
    608                              
     612
    609613            ylab = self.data._get_ordinate_label()
    610614
     
    670674        print_log()
    671675
     676    #@print_log_dec
    672677    def auto_fit(self, insitu=None, plot=False):
    673678        """
     
    700705                                                                   scan.getbeam(r),
    701706                                                                   scan.getif(r),
    702                                                                    scan.getpol(r), 
     707                                                                   scan.getpol(r),
    703708                                                                   scan.getcycle(r))
    704709            asaplog.push(out, False)
     
    723728        print_log()
    724729        return scan
    725 
  • branches/alma/python/asaplinefind.py

    r929 r1757  
    4141
    4242    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'):
    4444        """
    4545        Set the parameters of the algorithm
     
    5555                          this parameter can be averaged to search for
    5656                          broad lines. Default is 8.
    57              box_size     A running mean box size specified as a fraction
     57             box_size     A running mean/median box size specified as a fraction
    5858                          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                             
    5974        Note:  For bad baselines threshold should be increased,
    6075               and avg_limit decreased (or even switched off completely by
     
    6277               undulations instead of real lines.
    6378        """
    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)
    6591        return
    6692
  • branches/alma/python/asaplot.py

    r708 r1757  
    1111    ASAP plotting class based on matplotlib.
    1212    """
    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):
    1414        """
    1515        Create a new instance of the ASAPlot plotting class.
  • branches/alma/python/asaplotbase.py

    r1723 r1757  
    1010from matplotlib.figure import Figure, Text
    1111from matplotlib.font_manager import FontProperties as FP
    12 from matplotlib.numerix import sqrt
     12from numpy import sqrt
    1313from matplotlib import rc, rcParams
    1414from asap import rcParams as asaprcParams
    1515from matplotlib.ticker import OldScalarFormatter
    16 from matplotlib.ticker import NullLocator
    1716
    1817# API change in mpl >= 0.98
     
    2019    from matplotlib.transforms import blended_transform_factory
    2120except ImportError:
    22     from matplotlib.transforms import blend_xy_sep_transform  as blended_transform_factory
     21    from matplotlib.transforms import blend_xy_sep_transform as blended_transform_factory
    2322
    2423from asap import asaplog
     
    2928    print_log( 'WARN' )
    3029
    31 #class MyFormatter(OldScalarFormatter):
    32 #    def __call__(self, x, pos=None):
    33 #        last = len(self.locs)-2
    34 #        if pos==0:
    35 #            return ''
    36 #        else: return OldScalarFormatter.__call__(self, x, pos)
    37 
    3830class asaplotbase:
    3931    """
     
    4133    """
    4234
    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):
    4436        """
    4537        Create a new instance of the ASAPlot plotting class.
     
    157149        fmt is the line style as in plot().
    158150        """
    159         from matplotlib.numerix import array
    160         from matplotlib.numerix.ma import MaskedArray
     151        from numpy import array
     152        from numpy.ma import MaskedArray
    161153        if x is None:
    162154            if y is None: return
     
    289281        self.register('button_press', position_disable)
    290282
     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
    291299
    292300    def region(self):
     
    640648                    self.subplots[i]['axes'] = self.figure.add_subplot(rows,
    641649                                                cols, i+1)
    642                     if asaprcParams['plotter.xaxisformatting'] == 'mpl':
     650                    if asaprcParams['plotter.axesformatting'] != 'mpl':
    643651                        self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter())
    644652                else:
     
    646654                        self.subplots[i]['axes'] = self.figure.add_subplot(rows,
    647655                                                cols, i+1)
    648                         if asaprcParams['plotter.xaxisformatting'] != 'mpl':
     656                        if asaprcParams['plotter.axesformatting'] != 'mpl':
    649657                           
    650658                            self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter())
     
    730738
    731739            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
    736748            for sp in self.subplots:
    737749                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)/2
    742750                ax.title.set_size(tsize)
    743                 fp = FP(size=rcParams['axes.labelsize'])
    744751                setp(ax.get_xticklabels(), fontsize=xts)
    745752                setp(ax.get_yticklabels(), fontsize=yts)
    746                 origx =  fp.get_size_in_points()
    747                 origy = origx
    748753                off = 0
    749754                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)
    752756                off = 0
    753757                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)
    756759
    757760    def subplot(self, i=None, inc=None):
  • branches/alma/python/asaplotgui.py

    r1699 r1757  
    1616    """
    1717
    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):
    1919        """
    2020        Create a new instance of the ASAPlot plotting class.
  • branches/alma/python/asaplotgui_gtk.py

    r1619 r1757  
    1818    """
    1919
    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):
    2121        """
    2222        Create a new instance of the ASAPlot plotting class.
  • branches/alma/python/asaplotgui_qt4.py

    r1640 r1757  
    1818    """
    1919
    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):
    2121        """
    2222        Create a new instance of the ASAPlot plotting class.
  • branches/alma/python/asapmath.py

    r1693 r1757  
    11from asap.scantable import scantable
    22from asap import rcParams
    3 from asap import print_log
     3from asap import print_log, print_log_dec
    44from asap import selector
    55from asap import asaplog
    66from asap import asaplotgui
    77
     8#@print_log_dec
    89def average_time(*args, **kwargs):
    910    """
     
    2930        # without using a mask
    3031        scanav = average_time(scana,scanb)
    31         # or equivalent
    32         # scanav = average_time([scana, scanb])
     32        # or equivalent
     33        # scanav = average_time([scana, scanb])
    3334        # return the (time) averaged scan, i.e. the average of
    3435        # all correlator cycles
     
    122123    return s
    123124
     125#@print_log_dec
    124126def dototalpower(calon, caloff, tcalval=0.0):
    125127    """
     
    140142    return s
    141143
     144#@print_log_dec
    142145def dosigref(sig, ref, smooth, tsysval=0.0, tauval=0.0):
    143146    """
     
    160163    return s
    161164
     165#@print_log_dec
    162166def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    163167    """
     
    442446    return ress
    443447
     448#@print_log_dec
    444449def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    445450    """
     
    682687    return resspec
    683688
     689#@print_log_dec
    684690def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    685691    """
     
    889895    return resspec
    890896
    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
    908898def merge(*args):
    909899    """
     
    914904    Example:
    915905        myscans = [scan1, scan2]
    916         allscans = merge(myscans)
    917         # or equivalent
    918         sameallscans = merge(scan1, scan2)
     906        allscans = merge(myscans)
     907        # or equivalent
     908        sameallscans = merge(scan1, scan2)
    919909    """
    920910    varlist = vars()
  • branches/alma/python/asapplotter.py

    r1732 r1757  
    1 from asap import rcParams, print_log, selector
     1from asap import rcParams, print_log, print_log_dec
     2from asap import selector, scantable
    23from asap import asaplog
    34import matplotlib.axes
     5from matplotlib.font_manager import FontProperties
     6from matplotlib.text import Text
     7
    48import re
    59
     
    1317        other variables.
    1418    """
    15     def __init__(self, visible=None):
     19    def __init__(self, visible=None , **kwargs):
    1620        self._visible = rcParams['plotter.gui']
    1721        if visible is not None:
    1822            self._visible = visible
    19         self._plotter = self._newplotter()
     23        self._plotter = self._newplotter(**kwargs)
    2024        if self._visible and matplotlib.get_backend() == "TkAgg":
    2125            from asap.casatoolbar import CustomToolbarTkAgg
     
    4246        self._selection = selector()
    4347        self._hist = rcParams['plotter.histogram']
     48        self._fp = FontProperties()
    4449        self._panellayout = self.set_panellayout(refresh=False)
    4550
     
    5257        return None
    5358
    54     def _newplotter(self):
     59    def _newplotter(self, **kwargs):
    5560        backend=matplotlib.get_backend()
    5661        if not self._visible:
     
    6469        else:
    6570            from asap.asaplot import asaplot
    66         return asaplot()
    67 
    68 
     71        return asaplot(**kwargs)
     72
     73    #@print_log_dec
    6974    def plot(self, scan=None):
    7075        """
     
    101106        return
    102107
     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 []
    103169
    104170    # forwards to matplotlib axes
    105171    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")
    106177        self._axes_callback("text", *args, **kwargs)
     178
    107179    text.__doc__ = matplotlib.axes.Axes.text.__doc__
     180
    108181    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")
    109190        self._axes_callback("arrow", *args, **kwargs)
     191
    110192    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
    111206    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")
    112212        self._axes_callback("axvline", *args, **kwargs)
     213
    113214    axvline.__doc__ = matplotlib.axes.Axes.axvline.__doc__
     215
    114216    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")
    115222        self._axes_callback("axhline", *args, **kwargs)
     223
    116224    axhline.__doc__ = matplotlib.axes.Axes.axhline.__doc__
     225
    117226    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")
    118233        self._axes_callback("axvspan", *args, **kwargs)
    119234        # hack to preventy mpl from redrawing the patch
    120235        # it seem to convert the patch into lines on every draw.
    121236        # This doesn't happen in a test script???
    122         del self._plotter.axes.patches[-1]
     237        #del self._plotter.axes.patches[-1]
     238
    123239    axvspan.__doc__ = matplotlib.axes.Axes.axvspan.__doc__
    124240
    125241    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")
    126248        self._axes_callback("axhspan", *args, **kwargs)
    127249        # hack to preventy mpl from redrawing the patch
    128250        # it seem to convert the patch into lines on every draw.
    129251        # This doesn't happen in a test script???
    130         del self._plotter.axes.patches[-1]
     252        #del self._plotter.axes.patches[-1]
     253
    131254    axhspan.__doc__ = matplotlib.axes.Axes.axhspan.__doc__
    132255
     
    465588        if refresh and self._data: self.plot(self._data)
    466589
    467     def set_font(self, family=None, style=None, weight=None, size=None, refresh=True):
     590    def set_font(self, refresh=True,**kwargs):
    468591        """
    469592        Set font properties.
     
    479602        """
    480603        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)
    489609        if refresh and self._data: self.plot(self._data)
    490610
     
    540660        if not self._data.get_unit().endswith("Hz"):
    541661            raise RuntimeError("Can only overlay linecatalogs when data is in frequency.")
    542         from matplotlib.numerix import ma
     662        from numpy import ma
    543663        for j in range(len(self._plotter.subplots)):
    544664            self._plotter.subplot(j)
     
    716836        if isinstance(nstack0, int): nstack = nstack0
    717837        else: nstack = len(nstack0)
    718         maxpanel, maxstack = 16,8
     838        maxpanel, maxstack = 16,16
    719839        if n > maxpanel or nstack > maxstack:
    720840            maxn = 0
     
    761881                ylab = self._ordinate and self._ordinate[panelcount] \
    762882                       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)
    765885                lbl = self._get_label(scan, r, self._panelling, self._title)
    766886                if isinstance(lbl, list) or isinstance(lbl, tuple):
     
    781901                    y = scan._getspectrum(r)
    782902                m = scan._getmask(r)
    783                 from matplotlib.numerix import logical_not, logical_and
     903                from numpy import logical_not, logical_and
    784904                if self._maskselection and len(self._usermask) == len(m):
    785905                    if d[self._stacking](r) in self._maskselection[self._stacking]:
    786906                        m = logical_and(m, self._usermask)
    787907                x = scan._getabcissa(r)
    788                 from matplotlib.numerix import ma, array
     908                from numpy import ma, array
    789909                y = ma.masked_array(y,mask=logical_not(array(m,copy=False)))
    790910                if self._minmaxx is not None:
     
    839959        #reset the selector to the scantable's original
    840960        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):
    843969        """
    844970        Parameters:
     
    848974                        Otherwise,the parameter(s) are set without replotting.
    849975        """
    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
    851991        d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
    852992              'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' }
     
    8851025
    8861026    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
    8921034        from matplotlib.ticker import MultipleLocator
    893         from matplotlib.numerix import array, pi
     1035        from numpy import array, pi
    8941036        self._data = scan
    8951037        self._outfile = outfile
     
    8981040        tz = timezone('UTC')
    8991041        PL.cla()
    900         #PL.ioff()
     1042        PL.ioff()
    9011043        PL.clf()
    9021044        # Adjust subplot layouts
     
    9171059            minloc = HourLocator(range(0,23,12))
    9181060            timefmt = DateFormatter("%b%d")
     1061        elif tdel > 24./60.:
     1062            timefmt = DateFormatter('%H:%M')
     1063            majloc = HourLocator()
     1064            minloc = MinuteLocator(30)
    9191065        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
    9231070        PL.title(dstr)
    924 
    9251071        if tdel == 0.0:
    9261072            th = (t - PL.floor(t))*24.0
     
    9471093                if az[irow] < 0: az[irow] += 360.0
    9481094
    949         ax = PL.subplot(2,1,2)
     1095        ax2 = PL.subplot(2,1,2)
    9501096        #PL.xlabel('Time (UT [hour])')
    9511097        PL.ylabel('Az [deg.]')
     
    9541100        else:
    9551101            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)
    9621108        #hfmt = DateFormatter('%H')
    9631109        #hloc = HourLocator()
    9641110        yloc = MultipleLocator(60)
    965         ax.yaxis.set_major_locator(yloc)
     1111        ax2.yaxis.set_major_locator(yloc)
    9661112        if tdel > 1.0:
    967             labels = ax.get_xticklabels()
     1113            labels = ax2.get_xticklabels()
    9681114            PL.setp(labels, fontsize=10)
    9691115            PL.xlabel('Time (UT [day])')
     
    9711117            PL.xlabel('Time (UT [hour])')
    9721118
    973         #PL.ion()
     1119        PL.ion()
    9741120        PL.draw()
    9751121        if (self._outfile is not None):
     
    9771123
    9781124    def plotpointing(self, scan=None, outfile=None):
     1125    #def plotpointing(self):
    9791126        """
    9801127        plot telescope pointings
    9811128        """
    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
    9861131        self._data = scan
    9871132        self._outfile = outfile
     
    10011146        #ax = PL.axes([0.1,0.1,0.8,0.8])
    10021147        ax.set_aspect('equal')
    1003         PL.plot(ra,dec, 'b,')
     1148        PL.plot(ra, dec, 'b,')
    10041149        PL.xlabel('RA [deg.]')
    10051150        PL.ylabel('Declination [deg.]')
     
    11351280        # Print Observation header to the upper-left corner of plot
    11361281        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]
    11411286            #headstr[1]='Data File:     '+(filestr or 'unknown')+'\n'+headstr[1]
    1142             headstr[0]=headstr[0]+'\n'+srest
    1143             headstr.reverse()
    11441287            ssel='***Selections***\n'+(selstr+self._data.get_selection().__str__() or 'none')
    11451288            headstr.append(ssel)
     
    11591302                            verticalalignment='bottom',fontsize=8)
    11601303            self._plotter.release()
    1161             del srest, shead, headstr, ssel
     1304            del headstr, ssel
    11621305        if logger:
    11631306            asaplog.push("----------------\n  Plot Summary\n----------------")
  • branches/alma/python/asapreader.py

    r1059 r1757  
    11from asap._asap import stfiller
    2 from asap import print_log
     2from asap import print_log, print_log_dec
    33
    44class reader(stfiller):
     
    2525               rpfits ONLY.
    2626    """
    27 
     27    #@print_log_dec
    2828    def __init__(self, filename, unit=None, theif=None, thebeam=None):
    2929        self.unit = unit
     
    4848        print_log()
    4949
     50    #@print_log_dec
    5051    def read(self):
    5152        """
  • branches/alma/python/scantable.py

    r1701 r1757  
     1import os
     2try:
     3    from functools import wraps as wraps_dec
     4except ImportError:
     5    from asap.compatibility import wraps as wraps_dec
     6
    17from asap._asap import Scantable
    28from asap import rcParams
    3 from asap import print_log
     9from asap import print_log, print_log_dec
    410from asap import asaplog
    511from asap import selector
    612from asap import linecatalog
     13from asap.coordinate import coordinate
    714from asap import _n_bools, mask_not, mask_and, mask_or
     15
     16
     17def 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
     27def 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
    832
    933class scantable(Scantable):
     
    1236    """
    1337
    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):
    1540        """
    1641        Create a scantable from a saved one or make a reference
     
    3661            antenna:     Antenna selection. integer (id) or string (name
    3762                         or id).
     63            parallactify: Indcicate that the data had been parallatified.
     64                          Default is taken form rc file.
    3865        """
    3966        if average is None:
     
    5784                    return
    5885            antenna = tmpstr.rstrip(',')
     86        parallactify = parallactify or rcParams['scantable.parallactify']
    5987        varlist = vars()
    6088        from asap._asap import stmath
     
    6391            Scantable.__init__(self, filename)
    6492        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):
    6994                filename = os.path.expandvars(filename)
    7095                filename = os.path.expanduser(filename)
     
    7398                    if rcParams['verbose']:
    7499                        asaplog.push(s)
    75                         #print asaplog.pop().strip()
    76100                        print_log('ERROR')
    77101                        return
    78102                    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
    89119                    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)
    99121                else:
    100122                    self._fill([filename], unit, average, getpt, antenna)
     
    102124                  and isinstance(filename[-1], str):
    103125                self._fill(filename, unit, average, getpt, antenna)
     126        self.parallactify(parallactify)
    104127        self._add_history("scantable", varlist)
    105128        print_log()
    106129
     130    #@print_log_dec
    107131    def save(self, name=None, format=None, overwrite=False):
    108132        """
     
    119143                                       'MS2' (saves as an aips++
    120144                                              MeasurementSet V2)
    121                                        'FITS' (save as image FITS - not 
     145                                       'FITS' (save as image FITS - not
    122146                                               readable by class)
    123147                                       'CLASS' (save as FITS readable by CLASS)
     
    130154        """
    131155        from os import path
    132         if format is None: format = rcParams['scantable.save']
     156        format = format or rcParams['scantable.save']
    133157        suffix = '.'+format.lower()
    134158        if name is None or name == "":
     
    203227            else: raise
    204228        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)
    212231        except RuntimeError:
    213232            if rcParams['verbose']:
     
    219238                raise
    220239
     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
    221246
    222247    def get_scan(self, scanid=None):
     
    253278            if type(scanid) is str:
    254279                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)
    259281            elif type(scanid) is int:
    260282                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)
    265284            elif type(scanid) is list:
    266285                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)
    271287            else:
    272288                msg = "Illegal scanid type, use 'int' or 'list' if ints."
     
    294310            filename:    the name of a file to write the putput to
    295311                         Default - no file output
    296             verbose:     print extra info such as the frequency table
    297                          The default (False) is taken from .asaprc
    298312        """
    299313        info = Scantable._summary(self, True)
    300         #if verbose is None: verbose = rcParams['scantable.verbosesummary']
    301314        if filename is not None:
    302315            if filename is "":
     
    328341        """Return the spectrum for the current row in the scantable as a list.
    329342        Parameters:
    330              rowno:   the row number to retrieve the spectrum from       
     343             rowno:   the row number to retrieve the spectrum from
    331344        """
    332345        return self._getspectrum(rowno)
     
    335348        """Return the mask for the current row in the scantable as a list.
    336349        Parameters:
    337              rowno:   the row number to retrieve the mask from       
     350             rowno:   the row number to retrieve the mask from
    338351        """
    339352        return self._getmask(rowno)
     
    343356        Parameters:
    344357             spec:   the spectrum
    345              rowno:    the row number to set the spectrum for       
     358             rowno:    the row number to set the spectrum for
    346359        """
    347360        assert(len(spec) == self.nchan())
    348361        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))
    349381
    350382    def get_selection(self):
     
    360392        return selector(self._getselection())
    361393
    362     def set_selection(self, selection=selector()):
     394    def set_selection(self, selection=None, **kw):
    363395        """
    364396        Select a subset of the data. All following operations on this scantable
    365397        are only applied to thi selection.
    366398        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
    368406        Examples:
    369407            sel = selector()         # create a selection object
     
    372410            scan.summary()           # will only print summary of scanno 0 an 3
    373411            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)
    375427        self._setselection(selection)
    376428
     
    425477            scan.stats(stat='mean', mask=m)
    426478        """
    427         if mask == None:
    428             mask = []
    429         axes = ['Beam', 'IF', 'Pol', 'Time']
     479        mask = mask or []
    430480        if not self._check_ifs():
    431481            raise ValueError("Cannot apply mask as the IFs have different "
     
    441491        if not rtnabc: statvals = self._math._stats(self, mask, stat)
    442492
    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
    445503        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)
    455504            refstr = ''
    456505            statunit= ''
     
    459508                if rtnabc:
    460509                    statvals.append(qx['value'])
    461                     #refstr = '(value: %3.3f' % (qy['value'])+' ['+qy['unit']+'])'
    462510                    refstr = ('(value: %'+form) % (qy['value'])+' ['+qy['unit']+'])'
    463511                    statunit= '['+qx['unit']+']'
    464512                else:
    465                     #refstr = '(@ %3.3f' % (qx['value'])+' ['+qx['unit']+'])'
    466513                    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)
    469518            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'
    474525            out += ('= %'+form) % (statvals[i]) +'   '+refstr+'\n'
    475             out +=  "--------------------------------------------------\n"
     526            out +=  sep+"\n"
    476527
    477528        if rcParams['verbose']:
     
    484535            tmpfile='/tmp/tmp_'+usr+'_casapy_asap_scantable_stats'
    485536            f=open(tmpfile,'w')
    486             print >> f, "--------------------------------------------------"
    487             print >> f, " ", stat, statunit
    488             print >> f, "--------------------------------------------------"
     537            print >> f, sep
     538            print >> f, ' %s %s' % (label, statunit)
     539            print >> f, sep
    489540            print >> f, out
    490541            f.close()
     
    492543            x=f.readlines()
    493544            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 )
    496549            print_log()
    497         #else:
    498             #retval = { 'axesnames': ['scanno', 'beamno', 'ifno', 'polno', 'cycleno'],
    499             #           'axes' : axes,
    500             #           'data': statvals}
    501550        return statvals
    502551
     
    541590        return list(Scantable.get_column_names(self))
    542591
    543     def get_tsys(self):
     592    def get_tsys(self, row=-1):
    544593        """
    545594        Return the System temperatures.
     
    547596            a list of Tsys values for the current selection
    548597        """
    549 
     598        if row > -1:
     599            return self._get_column(self._gettsys, row)
    550600        return self._row_callback(self._gettsys, "Tsys")
    551601
     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
    552620    def _row_callback(self, callback, label):
    553         axes = []
    554         axesnames = ['scanno', 'beamno', 'ifno', 'polno', 'cycleno']
    555621        out = ""
    556622        outvec = []
     623        sep = '-'*50
    557624        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)
    565625            tm = self._gettime(i)
    566626            src = self._getsourcename(i)
    567             out += 'Scan[%d] (%s) ' % (axis[0], src)
     627            out += 'Scan[%d] (%s) ' % (self.getscan(i), src)
    568628            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))
    572633            outvec.append(callback(i))
    573634            out += '= %3.3f\n' % (outvec[i])
    574             out +=  "--------------------------------------------------\n"
     635            out +=  sep+'\n'
    575636        if rcParams['verbose']:
    576             asaplog.push("--------------------------------------------------")
     637            asaplog.push(sep)
    577638            asaplog.push(" %s" % (label))
    578             asaplog.push("--------------------------------------------------")
     639            asaplog.push(sep)
    579640            asaplog.push(out)
    580641            print_log()
    581         # disabled because the vector seems more useful
    582         #retval = {'axesnames': axesnames, 'axes': axes, 'data': outvec}
    583642        return outvec
    584643
     
    624683            none
    625684        """
    626         return self._get_column(self._getinttime, row)       
    627        
     685        return self._get_column(self._getinttime, row)
     686
    628687
    629688    def get_sourcename(self, row=-1):
     
    674733        """
    675734        Get a list of Positions on the sky (direction) for the observations.
    676         Return a float for each integration in the scantable.
     735        Return a string for each integration in the scantable.
    677736        Parameters:
    678737            row:    row no of integration. Default -1 return all rows
     
    693752        return self._get_column(self._getdirectionvec, row)
    694753
     754    #@print_log_dec
    695755    def set_unit(self, unit='channel'):
    696756        """
     
    708768        self._add_history("set_unit", varlist)
    709769
     770    #@print_log_dec
    710771    def set_instrument(self, instr):
    711772        """
     
    719780        print_log()
    720781
     782    #@print_log_dec
    721783    def set_feedtype(self, feedtype):
    722784        """
     
    729791        print_log()
    730792
     793    #@print_log_dec
    731794    def set_doppler(self, doppler='RADIO'):
    732795        """
     
    742805        print_log()
    743806
     807    #@print_log_dec
    744808    def set_freqframe(self, frame=None):
    745809        """
     
    747811        Parameters:
    748812            frame:   an optional frame type, default 'LSRK'. Valid frames are:
    749                      'REST', 'TOPO', 'LSRD', 'LSRK', 'BARY',
     813                     'TOPO', 'LSRD', 'LSRK', 'BARY',
    750814                     'GEO', 'GALACTO', 'LGROUP', 'CMB'
    751815        Examples:
    752816            scan.set_freqframe('BARY')
    753817        """
    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', \
    757824                   'GEO', 'GALACTO', 'LGROUP', 'CMB']
    758825
     
    829896        """
    830897        varlist = vars()
    831         if mask is None:
    832             mask = []
     898        mask = mask or []
    833899        try:
    834900            self._flag(mask, unflag)
     
    883949            else: raise
    884950        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):
    887955        """
    888956        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.
    890958        No taper is applied.
    891959        Parameters:
    892             frequency:    the frequency (really a period within the bandwidth)
    893                           to remove
    894             width:        the width of the frequency to remove, to remove a
    895                           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
    897965        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
    899967            signals beforehand.
    900968        """
     
    902970        self._math._setinsitu(insitu)
    903971        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)):
    906974            raise ValueError("%s is not a valid unit." % unit)
    907975        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"))
    910981        except RuntimeError, msg:
    911982            if rcParams['verbose']:
     
    923994            return s
    924995
    925 
     996    #@print_log_dec
    926997    def create_mask(self, *args, **kwargs):
    927998        """
     
    9521023            c)
    9531024            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)
    9591028        data = self._getabcissa(row)
    9601029        u = self._getcoordinfo()[0]
     
    9731042             and args or args[0]
    9741043        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
    9771052            for i in range(n):
    9781053                if data[i] >= window[0] and data[i] <= window[1]:
     
    11271202            source and IF basis, use scantable.set_selection() before using
    11281203            this function.
    1129             # provide your scantable is call scan
     1204            # provide your scantable is called scan
    11301205            selection = selector()
    11311206            selection.set_name("ORION*")
     
    11881263
    11891264    def shift_refpix(self, delta):
    1190         """
    1191         Shift the reference pixel of the Spectra Coordinate by an
    1192         integer amount.
    1193         Parameters:
    1194             delta:   the amount to shift by
     1265        """
     1266        Shift the reference pixel of the Spectra Coordinate by an
     1267        integer amount.
     1268        Parameters:
     1269            delta:   the amount to shift by
    11951270        Note:
    1196             Be careful using this with broadband data.
    1197         """
    1198         Scantable.shift(self, delta)
     1271            Be careful using this with broadband data.
     1272        """
     1273        Scantable.shift_refpix(self, delta)
    11991274
    12001275    def history(self, filename=None):
     
    12491324    # Maths business
    12501325    #
    1251 
     1326    #@print_log_dec
    12521327    def average_time(self, mask=None, scanav=False, weight='tint', align=False):
    12531328        """
     
    12751350        """
    12761351        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'
    12811355        scan = (self, )
    12821356        try:
     
    13021376        return s
    13031377
     1378    #@print_log_dec
    13041379    def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None):
    13051380        """
     
    13211396        self._math._setinsitu(insitu)
    13221397        varlist = vars()
    1323         if jyperk is None: jyperk = -1.0
    1324         if d is None: d = -1.0
    1325         if eta is None: eta = -1.0
     1398        jyperk = jyperk or -1.0
     1399        d = d or -1.0
     1400        eta = eta or -1.0
    13261401        s = scantable(self._math._convertflux(self, d, eta, jyperk))
    13271402        s._add_history("convert_flux", varlist)
     
    13301405        else: return s
    13311406
     1407    #@print_log_dec
    13321408    def gain_el(self, poly=None, filename="", method="linear", insitu=None):
    13331409        """
     
    13731449        self._math._setinsitu(insitu)
    13741450        varlist = vars()
    1375         if poly is None:
    1376             poly = ()
     1451        poly = poly or ()
    13771452        from os.path import expandvars
    13781453        filename = expandvars(filename)
     
    13801455        s._add_history("gain_el", varlist)
    13811456        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
    13851463    def freq_align(self, reftime=None, method='cubic', insitu=None):
    13861464        """
     
    14011479        self._math._setinsitu(insitu)
    14021480        varlist = vars()
    1403         if reftime is None: reftime = ""
     1481        reftime = reftime or ""
    14041482        s = scantable(self._math._freq_align(self, reftime, method))
    14051483        s._add_history("freq_align", varlist)
     
    14081486        else: return s
    14091487
    1410     def opacity(self, tau, insitu=None):
     1488    #@print_log_dec
     1489    def opacity(self, tau=None, insitu=None):
    14111490        """
    14121491        Apply an opacity correction. The data
    14131492        and Tsys are multiplied by the correction factor.
    14141493        Parameters:
    1415             tau:         Opacity from which the correction factor is
     1494            tau:         (list of) opacity from which the correction factor is
    14161495                         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.
    14181502            insitu:      if False a new scantable is returned.
    14191503                         Otherwise, the scaling is done in-situ
     
    14231507        self._math._setinsitu(insitu)
    14241508        varlist = vars()
     1509        if not hasattr(tau, "__len__"):
     1510            tau = [tau]
    14251511        s = scantable(self._math._opacity(self, tau))
    14261512        s._add_history("opacity", varlist)
     
    14291515        else: return s
    14301516
     1517    #@print_log_dec
    14311518    def bin(self, width=5, insitu=None):
    14321519        """
     
    14441531        s._add_history("bin", varlist)
    14451532        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
    14501539    def resample(self, width=5, method='cubic', insitu=None):
    14511540        """
     
    14701559        else: return s
    14711560
    1472 
     1561    #@print_log_dec
    14731562    def average_pol(self, mask=None, weight='none'):
    14741563        """
     
    14821571        """
    14831572        varlist = vars()
    1484         if mask is None:
    1485             mask = ()
     1573        mask = mask or ()
    14861574        s = scantable(self._math._averagepol(self, mask, weight.upper()))
    14871575        s._add_history("average_pol", varlist)
     
    14891577        return s
    14901578
     1579    #@print_log_dec
    14911580    def average_beam(self, mask=None, weight='none'):
    14921581        """
     
    15001589        """
    15011590        varlist = vars()
    1502         if mask is None:
    1503             mask = ()
     1591        mask = mask or ()
    15041592        s = scantable(self._math._averagebeams(self, mask, weight.upper()))
    15051593        s._add_history("average_beam", varlist)
     
    15071595        return s
    15081596
     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
    15091610    def convert_pol(self, poltype=None):
    15101611        """
    15111612        Convert the data to a different polarisation type.
     1613        Note that you will need cross-polarisation terms for most conversions.
    15121614        Parameters:
    15131615            poltype:    The new polarisation type. Valid types are:
    1514                         "linear", "stokes" and "circular"
     1616                        "linear", "circular", "stokes" and "linpol"
    15151617        """
    15161618        varlist = vars()
     
    15301632        return s
    15311633
    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):
    15341636        """
    15351637        Smooth the spectrum by the specified kernel (conserving flux).
    15361638        Parameters:
    15371639            kernel:     The type of smoothing kernel. Select from
    1538                         'hanning' (default), 'gaussian', 'boxcar' and
    1539                         'rmedian'
     1640                        'hanning' (default), 'gaussian', 'boxcar', 'rmedian'
     1641                        or 'poly'
    15401642            width:      The width of the kernel in pixels. For hanning this is
    15411643                        ignored otherwise it defauls to 5 pixels.
    15421644                        For 'gaussian' it is the Full Width Half
    15431645                        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.
    15451650            plot:       plot the original and the smoothed spectra.
    15461651                        In this each indivual fit has to be approved, by
     
    15581663        if plot: orgscan = self.copy()
    15591664
    1560         s = scantable(self._math._smooth(self, kernel.lower(), width))
     1665        s = scantable(self._math._smooth(self, kernel.lower(), width, order))
    15611666        s._add_history("smooth", varlist)
    15621667
     
    16011706        else: return s
    16021707
    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):
    16051711        """
    16061712        Return a scan which has been baselined (all rows) by a polynomial.
     
    18331939            return workscan
    18341940
     1941    #@print_log_dec
    18351942    def rotate_linpolphase(self, angle):
    18361943        """
     
    18491956        return
    18501957
    1851 
     1958    #@print_log_dec
    18521959    def rotate_xyphase(self, angle):
    18531960        """
     
    18661973        return
    18671974
     1975    #@print_log_dec
    18681976    def swap_linears(self):
    18691977        """
    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
    18711979        polarisations as this also works for ciculars.
    18721980        """
     
    18771985        return
    18781986
     1987    #@print_log_dec
    18791988    def invert_phase(self):
    18801989        """
     
    18871996        return
    18881997
     1998    #@print_log_dec
    18891999    def add(self, offset, insitu=None):
    18902000        """
     
    19072017            return s
    19082018
     2019    #@print_log_dec
    19092020    def scale(self, factor, tsys=True, insitu=None):
    19102021        """
     
    19722083        self._setsourcetype(stype)
    19732084        self.set_selection(basesel)
    1974         s._add_history("set_sourcetype", varlist)
    1975 
     2085        self._add_history("set_sourcetype", varlist)
     2086
     2087    #@print_log_dec
    19762088    def auto_quotient(self, preserve=True, mode='paired', verify=False):
    19772089        """
     
    19842096                            preserve: Output = Toff * (on/off) - Toff
    19852097                            remove:   Output = Toff * (on/off) - Ton
    1986             mode:           the on/off detection mode 
     2098            mode:           the on/off detection mode
    19872099                            'paired' (default)
    19882100                            identifies 'off' scans by the
     
    20172129        return s
    20182130
     2131    #@print_log_dec
    20192132    def mx_quotient(self, mask = None, weight='median', preserve=True):
    20202133        """
     
    20282141                            remove:   Output = Toff * (on/off) - Ton
    20292142        """
    2030         if mask is None: mask = ()
     2143        mask = mask or ()
    20312144        varlist = vars()
    20322145        on = scantable(self._math._mx_extract(self, 'on'))
     
    20392152        return q
    20402153
     2154    #@print_log_dec
    20412155    def freq_switch(self, insitu=None):
    20422156        """
     
    20582172        else: return s
    20592173
     2174    #@print_log_dec
    20602175    def recalc_azel(self):
    20612176        """
     
    20712186        return
    20722187
     2188    #@print_log_dec
    20732189    def __add__(self, other):
    20742190        """
     
    20772193        return self._operation( other, "ADD" )
    20782194
     2195    #@print_log_dec
    20792196    def __sub__(self, other):
    20802197        """
     
    20832200        return self._operation( other, 'SUB' )
    20842201
     2202    #@print_log_dec
    20852203    def __mul__(self, other):
    20862204        """
     
    20892207        return self._operation( other, 'MUL' )
    20902208
     2209    #@print_log_dec
    20912210    def __div__(self, other):
    20922211        """
     
    21202239        basesel = self.get_selection()
    21212240        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)
    21282243            nans = numpy.isnan(self._getspectrum(0))
    21292244        if numpy.any(nans):
     
    21312246            self.flag(bnans)
    21322247        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))
    21342255
    21352256    def _add_history(self, funcname, parameters):
  • branches/alma/python/selector.py

    r1693 r1757  
    77    scantables to specific rows.
    88    """
    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)
    1124
    1225    def reset(self):
     
    4558        else:
    4659            raise TypeError('Unknown pol type. Please use [0,1...] or ["XX","YY"...]')
    47    
     60
    4861    # for the americans
    4962    set_polarizations = set_polarisations
     
    220233        Merge two selections.
    221234        """
     235        if self.is_empty():
     236            return other
     237        elif other.is_empty():
     238            return self
    222239        union = selector()
    223240        gets = [[self._getscans(), other._getscans(), union._setscans],
Note: See TracChangeset for help on using the changeset viewer.