Ignore:
Timestamp:
07/29/10 19:13:46 (14 years ago)
Author:
Kana Sugimoto
Message:

New Development: Yes

JIRA Issue: No (test merging alma branch)

Ready for Test: Yes

Interface Changes: Yes

What Interface Changed:

Test Programs:

Put in Release Notes: No

Module(s):

Description:


Location:
branches/mergetest
Files:
13 edited
8 copied

Legend:

Unmodified
Added
Removed
  • branches/mergetest

  • branches/mergetest/python/__init__.py

    r1739 r1779  
    99    from asap.compatibility import wraps as wraps_dec
    1010
    11 # Set up AIPSPATH and first time use of asap i.e. ~/.asap/*
     11# Set up CASAPATH and first time use of asap i.e. ~/.asap/*
    1212plf = None
    1313if sys.platform == "linux2":
     
    2626    if os.path.exists(os.environ["ASAPDATA"]):
    2727        asapdata = os.environ["ASAPDATA"]
    28 # use AIPSPATH if defined and "data" dir present
    29 if not os.environ.has_key("AIPSPATH") or \
    30         not os.path.exists(os.environ["AIPSPATH"].split()[0]+"/data"):
    31     os.environ["AIPSPATH"] = "%s %s somwhere" % ( asapdata, plf)
     28# use CASAPATH if defined and "data" dir present
     29if not os.environ.has_key("CASAPATH") or \
     30        not os.path.exists(os.environ["CASAPATH"].split()[0]+"/data"):
     31    os.environ["CASAPATH"] = "%s %s somwhere" % ( asapdata, plf)
    3232# set up user space
    3333userdir = os.environ["HOME"]+"/.asap"
     
    3535    print 'First time ASAP use. Setting up ~/.asap'
    3636    os.mkdir(userdir)
    37     shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap")
    38     shutil.copyfile(asapdata+"/data/ipy_user_conf.py",
    39                     userdir+"/ipy_user_conf.py")
     37    #shutil.copyfile(asapdata+"/data/ipythonrc-asap", userdir+"/ipythonrc-asap")
     38    # commented out by TT on 2009.06.23 for casapy use
     39    ##shutil.copyfile(asapdata+"/data/ipy_user_conf.py",
     40    ##                userdir+"/ipy_user_conf.py")
    4041    f = file(userdir+"/asapuserfuncs.py", "w")
    4142    f.close()
    4243    f = file(userdir+"/ipythonrc", "w")
    4344    f.close()
    44 else:
     45# commented out by TT on 2009.06.23 for casapy use
     46##else:
    4547    # upgrade to support later ipython versions
    46     if not os.path.exists(userdir+"/ipy_user_conf.py"):
    47         shutil.copyfile(asapdata+"/data/ipy_user_conf.py",
    48                         userdir+"/ipy_user_conf.py")
     48    ##if not os.path.exists(userdir+"/ipy_user_conf.py"):
     49    ##    shutil.copyfile(asapdata+"/data/ipy_user_conf.py",
     50    ##                    userdir+"/ipy_user_conf.py")
    4951
    5052# remove from namespace
     
    110112    'plotter.histogram'  : [False, _validate_bool],
    111113    'plotter.papertype'  : ['A4', str],
    112     'plotter.axesformatting' : ['mpl', str],
     114    ## for older Matplotlib version
     115    #'plotter.axesformatting' : ['mpl', str],
     116    'plotter.axesformatting' : ['asap', str],
    113117
    114118    # scantable
     
    218222        tup = line.split(':',1)
    219223        if len(tup) !=2:
    220             print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
     224            #print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
     225            asaplog.push('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
     226            print_log('WARN')
    221227            continue
    222228
     
    224230        key = key.strip()
    225231        if not defaultParams.has_key(key):
    226             print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
     232            #print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
     233            asaplog.push('Bad key "%s" on line %d in %s' % (key, cnt, fname))
     234            print_log('WARN')
    227235            continue
    228236
     
    234242        try: cval = converter(val)   # try to convert to proper type or raise
    235243        except ValueError, msg:
    236             print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
     244            #print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
     245            asaplog.push('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, str(msg)))
     246            print_log('WARN')
    237247            continue
    238248        else:
     
    366376    return wrap_it
    367377
    368 def print_log():
    369     log = asaplog.pop().strip()
    370     if len(log) and rcParams['verbose']: print log
     378def print_log(level='INFO'):
     379    from taskinit import casalog
     380    log = asaplog.pop()
     381    #if len(log) and rcParams['verbose']: print log
     382    if len(log) and rcParams['verbose']: casalog.post( log, priority=level )
    371383    return
    372384
     
    391403from simplelinefinder import simplelinefinder
    392404from linecatalog import linecatalog
     405from interactivemask import interactivemask
    393406from opacity import skydip
    394407from opacity import model as opacity_model
     
    400413        if gui:
    401414            import matplotlib
    402             matplotlib.use("TkAgg")
     415            if not matplotlib.sys.modules['matplotlib.backends']: matplotlib.use("TkAgg")
    403416        from matplotlib import pylab
    404417        xyplotter = pylab
     
    406419        del gui
    407420    except ImportError:
    408         print "Matplotlib not installed. No plotting available"
     421        #print "Matplotlib not installed. No plotting available"
     422        asaplog.post( "Matplotlib not installed. No plotting available")
     423        print_log('WARN')
    409424
    410425__date__ = '$Date$'.split()[1]
    411 __version__  = '$Revision$'
     426__version__  = '3.0.0 alma'
     427# nrao casapy specific, get revision number
     428#__revision__ = ' unknown '
     429casapath=os.environ["CASAPATH"].split()
     430#svninfo.txt path
     431if os.path.isdir(casapath[0]+'/'+casapath[1]+'/python/2.5/asap'):
     432    # for casa developer environment (linux or darwin)
     433    revinfo=casapath[0]+'/'+casapath[1]+'/python/2.5/asap/svninfo.txt'
     434else:
     435    # for end-user environments
     436    if casapath[1]=='darwin':
     437        revinfo=casapath[0]+'/Resources/python/asap/svninfo.txt'
     438    else:
     439        revinfo=casapath[0]+'/lib/python2.5/asap/svninfo.txt'
     440if os.path.isfile(revinfo):
     441    f = file(revinfo)
     442    f.readline()
     443    revsionno=f.readline()
     444    f.close()
     445    del f
     446    __revision__ = revsionno.rstrip()
     447else:
     448    __revision__ = ' unknown '
    412449
    413450def is_ipython():
    414451    return 'IPython' in sys.modules.keys()
    415 
    416452if is_ipython():
    417453    def version(): print  "ASAP %s(%s)"% (__version__, __date__)
  • branches/mergetest/python/asapfitter.py

    r1739 r1779  
    11import _asap
    22from asap import rcParams
    3 from asap import print_log_dec
     3from asap import print_log, print_log_dec
    44from asap import _n_bools
    55from asap import mask_and
     6from asap import asaplog
    67
    78class fitter:
     
    5960            msg = "Please give a correct scan"
    6061            if rcParams['verbose']:
    61                 print msg
     62                #print msg
     63                asaplog.push(msg)
     64                print_log('ERROR')
    6265                return
    6366            else:
     
    7982            lpoly:   use polynomial of the order given with linear least squares fit
    8083            gauss:   fit the number of gaussian specified
     84            lorentz: fit the number of lorentzian specified
    8185        Example:
    82             fitter.set_function(gauss=2) # will fit two gaussians
    8386            fitter.set_function(poly=3)  # will fit a 3rd order polynomial via nonlinear method
    8487            fitter.set_function(lpoly=3)  # will fit a 3rd order polynomial via linear method
     88            fitter.set_function(gauss=2) # will fit two gaussians
     89            fitter.set_function(lorentz=2) # will fit two lorentzians
    8590        """
    8691        #default poly order 0
     
    102107            self.components = [ 3 for i in range(n) ]
    103108            self.uselinear = False
     109        elif kwargs.has_key('lorentz'):
     110            n = kwargs.get('lorentz')
     111            self.fitfunc = 'lorentz'
     112            self.fitfuncs = [ 'lorentz' for i in range(n) ]
     113            self.components = [ 3 for i in range(n) ]
     114            self.uselinear = False
    104115        else:
    105116            msg = "Invalid function type."
    106117            if rcParams['verbose']:
    107                 print msg
     118                #print msg
     119                asaplog.push(msg)
     120                print_log('ERROR')
    108121                return
    109122            else:
     
    114127        return
    115128
    116     @print_log_dec
     129    #@print_log_dec
    117130    def fit(self, row=0, estimate=False):
    118131        """
     
    135148            msg = "Fitter not yet initialised. Please set data & fit function"
    136149            if rcParams['verbose']:
    137                 print msg
     150                #print msg
     151                asaplog.push(msg)
     152                print_log('ERROR')
    138153                return
    139154            else:
     
    145160                self.y = self.data._getspectrum(row)
    146161                self.mask = mask_and(self.mask, self.data._getmask(row))
    147                 from asap import asaplog
    148162                asaplog.push("Fitting:")
    149163                i = row
     
    155169                asaplog.push(out,False)
    156170        self.fitter.setdata(self.x, self.y, self.mask)
    157         if self.fitfunc == 'gauss':
     171        if self.fitfunc == 'gauss' or self.fitfunc == 'lorentz':
    158172            ps = self.fitter.getparameters()
    159173            if len(ps) == 0 or estimate:
     
    171185        except RuntimeError, msg:
    172186            if rcParams['verbose']:
    173                 print msg
     187                #print msg
     188                print_log()
     189                asaplog.push(str(msg))
     190                print_log('ERROR')
    174191            else:
    175192                raise
    176193        self._fittedrow = row
    177194        self.fitted = True
     195        print_log()
    178196        return
    179197
     
    204222                self.data._addfit(fit,self._fittedrow)
    205223
    206     @print_log_dec
     224    #@print_log_dec
    207225    def set_parameters(self,*args,**kwargs):
    208226        """
     
    228246            msg = "Please specify a fitting function first."
    229247            if rcParams['verbose']:
    230                 print msg
     248                #print msg
     249                asaplog.push(msg)
     250                print_log('ERROR')
    231251                return
    232252            else:
    233253                raise RuntimeError(msg)
    234         if self.fitfunc == "gauss" and component is not None:
     254        if (self.fitfunc == "gauss" or self.fitfunc == 'lorentz') and component is not None:
    235255            if not self.fitted and sum(self.fitter.getparameters()) == 0:
    236256                pars = _n_bools(len(self.components)*3, False)
     
    247267        if fixed is not None:
    248268            self.fitter.setfixedparameters(fixed)
     269        print_log()
    249270        return
    250271
     
    269290            msg = "Function only operates on Gaussian components."
    270291            if rcParams['verbose']:
    271                 print msg
     292                #print msg
     293                asaplog.push(msg)
     294                print_log('ERROR')
    272295                return
    273296            else:
     
    280303            msg = "Please select a valid  component."
    281304            if rcParams['verbose']:
    282                 print msg
     305                #print msg
     306                asaplog.push(msg)
     307                print_log('ERROR')
    283308                return
    284309            else:
    285310                raise ValueError(msg)
    286311
     312    def set_lorentz_parameters(self, peak, centre, fwhm,
     313                             peakfixed=0, centrefixed=0,
     314                             fwhmfixed=0,
     315                             component=0):
     316        """
     317        Set the Parameters of a 'Lorentzian' component, set with set_function.
     318        Parameters:
     319            peak, centre, fwhm:  The gaussian parameters
     320            peakfixed,
     321            centrefixed,
     322            fwhmfixed:           Optional parameters to indicate if
     323                                 the paramters should be held fixed during
     324                                 the fitting process. The default is to keep
     325                                 all parameters flexible.
     326            component:           The number of the component (Default is the
     327                                 component 0)
     328        """
     329        if self.fitfunc != "lorentz":
     330            msg = "Function only operates on Lorentzian components."
     331            if rcParams['verbose']:
     332                #print msg
     333                asaplog.push(msg)
     334                print_log('ERROR')
     335                return
     336            else:
     337                raise ValueError(msg)
     338        if 0 <= component < len(self.components):
     339            d = {'params':[peak, centre, fwhm],
     340                 'fixed':[peakfixed, centrefixed, fwhmfixed]}
     341            self.set_parameters(d, component)
     342        else:
     343            msg = "Please select a valid  component."
     344            if rcParams['verbose']:
     345                #print msg
     346                asaplog.push(msg)
     347                print_log('ERROR')
     348                return
     349            else:
     350                raise ValueError(msg)
     351
    287352    def get_area(self, component=None):
    288353        """
    289         Return the area under the fitted gaussian component.
    290         Parameters:
    291               component:   the gaussian component selection,
     354        Return the area under the fitted gaussian/lorentzian component.
     355        Parameters:
     356              component:   the gaussian/lorentzian component selection,
    292357                           default (None) is the sum of all components
    293358        Note:
    294               This will only work for gaussian fits.
     359              This will only work for gaussian/lorentzian fits.
    295360        """
    296361        if not self.fitted: return
    297         if self.fitfunc == "gauss":
     362        if self.fitfunc == "gauss" or self.fitfunc == "lorentz":
    298363            pars = list(self.fitter.getparameters())
    299364            from math import log,pi,sqrt
    300             fac = sqrt(pi/log(16.0))
     365            if self.fitfunc == "gauss":
     366                fac = sqrt(pi/log(16.0))
     367            elif self.fitfunc == "lorentz":
     368                fac = pi/2.0
    301369            areas = []
    302370            for i in range(len(self.components)):
     
    321389            msg = "Not yet fitted."
    322390            if rcParams['verbose']:
    323                 print msg
     391                #print msg
     392                asaplog.push(msg)
     393                print_log('ERROR')
    324394                return
    325395            else:
     
    328398        cerrs = errs
    329399        if component is not None:
    330             if self.fitfunc == "gauss":
     400            if self.fitfunc == "gauss" or self.fitfunc == "lorentz":
    331401                i = 3*component
    332402                if i < len(errs):
     
    344414            msg = "Not yet fitted."
    345415            if rcParams['verbose']:
    346                 print msg
     416                #print msg
     417                asaplog.push(msg)
     418                print_log('ERROR')
    347419                return
    348420            else:
     
    353425        area = []
    354426        if component is not None:
    355             if self.fitfunc == "gauss":
     427            if self.fitfunc == "gauss" or self.fitfunc == "lorentz":
    356428                i = 3*component
    357429                cpars = pars[i:i+3]
     
    368440            cfixed = fixed
    369441            cerrs = errs
    370             if self.fitfunc == "gauss":
     442            if self.fitfunc == "gauss" or self.fitfunc == "lorentz":
    371443                for c in range(len(self.components)):
    372444                  a = self.get_area(c)
     
    374446        fpars = self._format_pars(cpars, cfixed, errors and cerrs, area)
    375447        if rcParams['verbose']:
    376             print fpars
     448            #print fpars
     449            asaplog.push(fpars)
     450            print_log()
    377451        return {'params':cpars, 'fixed':cfixed, 'formatted': fpars,
    378452                'errors':cerrs}
     
    391465                c+=1
    392466            out = out[:-1]  # remove trailing ','
    393         elif self.fitfunc == 'gauss':
     467        elif self.fitfunc == 'gauss' or self.fitfunc == 'lorentz':
    394468            i = 0
    395469            c = 0
     
    415489        fixed = self.fitter.getfixedparameters()
    416490        if rcParams['verbose']:
    417             print self._format_pars(pars,fixed,None)
     491            #print self._format_pars(pars,fixed,None)
     492            asaplog.push(self._format_pars(pars,fixed,None))
     493            print_log()
    418494        return pars
    419495
     
    425501            msg = "Not yet fitted."
    426502            if rcParams['verbose']:
    427                 print msg
     503                #print msg
     504                asaplog.push(msg)
     505                print_log('ERROR')
    428506                return
    429507            else:
     
    438516            msg = "Not yet fitted."
    439517            if rcParams['verbose']:
    440                 print msg
     518                #print msg
     519                asaplog.push(msg)
     520                print_log('ERROR')
    441521                return
    442522            else:
     
    444524        ch2 = self.fitter.getchi2()
    445525        if rcParams['verbose']:
    446             print 'Chi^2 = %3.3f' % (ch2)
     526            #print 'Chi^2 = %3.3f' % (ch2)
     527            asaplog.push( 'Chi^2 = %3.3f' % (ch2) )
     528            print_log()
    447529        return ch2
    448530
     
    454536            msg = "Not yet fitted."
    455537            if rcParams['verbose']:
    456                 print msg
     538                #print msg
     539                asaplog.push(msg)
     540                print_log('ERROR')
    457541                return
    458542            else:
     
    460544        return self.fitter.getfit()
    461545
    462     @print_log_dec
     546    #@print_log_dec
    463547    def commit(self):
    464548        """
     
    468552            msg = "Not yet fitted."
    469553            if rcParams['verbose']:
    470                 print msg
     554                #print msg
     555                asaplog.push(msg)
     556                print_log('ERROR')
    471557                return
    472558            else:
     
    476562            msg = "Not a scantable"
    477563            if rcParams['verbose']:
    478                 print msg
     564                #print msg
     565                asaplog.push(msg)
     566                print_log('ERROR')
    479567                return
    480568            else:
     
    482570        scan = self.data.copy()
    483571        scan._setspectrum(self.fitter.getresidual())
     572        print_log()
    484573        return scan
    485574
    486     @print_log_dec
     575    #@print_log_dec
    487576    def plot(self, residual=False, components=None, plotparms=False,
    488577             filename=None):
     
    525614
    526615        colours = ["#777777","#dddddd","red","orange","purple","green","magenta", "cyan"]
     616        nomask=True
     617        for i in range(len(m)):
     618            nomask = nomask and m[i]
     619        label0='Masked Region'
     620        label1='Spectrum'
     621        if ( nomask ):
     622            label0=label1
     623        else:
     624            y = ma.masked_array( self.y, mask = m )
     625            self._p.palette(1,colours)
     626            self._p.set_line( label = label1 )
     627            self._p.plot( self.x, y )
    527628        self._p.palette(0,colours)
    528         self._p.set_line(label='Spectrum')
     629        self._p.set_line(label=label0)
    529630        y = ma.masked_array(self.y,mask=logical_not(m))
    530631        self._p.plot(self.x, y)
    531632        if residual:
    532             self._p.palette(1)
     633            self._p.palette(7)
    533634            self._p.set_line(label='Residual')
    534635            y = ma.masked_array(self.get_residual(),
     
    571672        if (not rcParams['plotter.gui']):
    572673            self._p.save(filename)
    573 
    574     @print_log_dec
     674        print_log()
     675
     676    #@print_log_dec
    575677    def auto_fit(self, insitu=None, plot=False):
    576678        """
     
    583685            msg = "Data is not a scantable"
    584686            if rcParams['verbose']:
    585                 print msg
     687                #print msg
     688                asaplog.push(msg)
     689                print_log('ERROR')
    586690                return
    587691            else:
     
    593697            scan = self.data
    594698        rows = xrange(scan.nrow())
    595         from asap import asaplog
     699        # Save parameters of baseline fits as a class attribute.
     700        # NOTICE: This does not reflect changes in scantable!
     701        if len(rows) > 0: self.blpars=[]
    596702        asaplog.push("Fitting:")
    597703        for r in rows:
     
    608714            self.fit()
    609715            x = self.get_parameters()
     716            fpar = self.get_parameters()
    610717            if plot:
    611718                self.plot(residual=True)
    612719                x = raw_input("Accept fit ([y]/n): ")
    613720                if x.upper() == 'N':
     721                    self.blpars.append(None)
    614722                    continue
    615723            scan._setspectrum(self.fitter.getresidual(), r)
     724            self.blpars.append(fpar)
    616725        if plot:
    617726            self._p.unmap()
    618727            self._p = None
     728        print_log()
    619729        return scan
  • branches/mergetest/python/asaplot.py

    r1564 r1779  
    66
    77from matplotlib.backends.backend_agg import FigureCanvasAgg
     8from matplotlib.backend_bases import FigureManagerBase
    89
    910class asaplot(asaplotbase):
     
    2223        asaplotbase.__init__(self,**v)
    2324        self.canvas = FigureCanvasAgg(self.figure)
     25        self.figmgr = FigureManagerBase(self.canvas,1)
  • branches/mergetest/python/asaplotbase.py

    r1739 r1779  
    2121    from matplotlib.transforms import blend_xy_sep_transform as blended_transform_factory
    2222
     23from asap import asaplog
     24
    2325if int(matplotlib.__version__.split(".")[1]) < 87:
    24     print "Warning: matplotlib version < 0.87. This might cause errors. Please upgrade."
     26    #print "Warning: matplotlib version < 0.87. This might cause errors. Please upgrade."
     27    asaplog.push( "matplotlib version < 0.87. This might cause errors. Please upgrade." )
     28    print_log( 'WARN' )
    2529
    2630class asaplotbase:
     
    147151        from numpy import array
    148152        from numpy.ma import MaskedArray
    149 
    150153        if x is None:
    151154            if y is None: return
     
    168171            ymsk = y.mask
    169172            ydat = y.data
    170 
    171173        for i in range(l2):
    172174            x2[i] = x[i/2]
     
    280282
    281283
    282     def get_region(self):
    283         pos = []
    284         print "Please select the bottom/left point"
    285         pos.append(self.figure.ginput(n=1, show_clicks=False)[0])
    286         print "Please select the top/right point"
    287         pos.append(self.figure.ginput(n=1, show_clicks=False)[0])
    288         return pos
    289 
    290     def get_point(self):
    291         print "Please select the point"
    292         pt = self.figure.ginput(n=1, show_clicks=False)
    293         if pt:
    294             return pt[0]
    295         else:
    296             return None
     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
    297299
    298300    def region(self):
     
    304306
    305307        def region_start(event):
    306             height = self.canvas.figure.bbox.height()
    307             self.rect = {'fig': None, 'height': height,
    308                          'x': event.x, 'y': height - event.y,
     308            self.rect = {'x': event.x, 'y': event.y,
    309309                         'world': [event.xdata, event.ydata,
    310310                                   event.xdata, event.ydata]}
     
    314314
    315315        def region_draw(event):
    316             self.canvas._tkcanvas.delete(self.rect['fig'])
    317             self.rect['fig'] = self.canvas._tkcanvas.create_rectangle(
    318                                 self.rect['x'], self.rect['y'],
    319                                 event.x, self.rect['height'] - event.y)
    320 
     316            self.figmgr.toolbar.draw_rubberband(event, event.x, event.y,
     317                                                self.rect['x'], self.rect['y'])
     318           
    321319        def region_disable(event):
    322320            self.register('motion_notify', None)
    323321            self.register('button_release', None)
    324 
    325             self.canvas._tkcanvas.delete(self.rect['fig'])
    326322
    327323            self.rect['world'][2:4] = [event.xdata, event.ydata]
     
    329325                self.rect['world'][1], self.rect['world'][2],
    330326                self.rect['world'][3])
     327            self.figmgr.toolbar.release(event)
    331328
    332329        self.register('button_press', region_start)
     
    381378                self.events[type] = None
    382379
    383                 # It seems to be necessary to return events to the toolbar.
    384                 if type == 'motion_notify':
    385                     self.canvas.mpl_connect(type + '_event',
    386                         self.figmgr.toolbar.mouse_move)
    387                 elif type == 'button_press':
    388                     self.canvas.mpl_connect(type + '_event',
    389                         self.figmgr.toolbar.press)
    390                 elif type == 'button_release':
    391                     self.canvas.mpl_connect(type + '_event',
    392                         self.figmgr.toolbar.release)
     380                # It seems to be necessary to return events to the toolbar. <-- Not ture. 2010.Jul.14.kana.
     381                #if type == 'motion_notify':
     382                #    self.canvas.mpl_connect(type + '_event',
     383                #        self.figmgr.toolbar.mouse_move)
     384                #elif type == 'button_press':
     385                #    self.canvas.mpl_connect(type + '_event',
     386                #        self.figmgr.toolbar.press)
     387                #elif type == 'button_release':
     388                #    self.canvas.mpl_connect(type + '_event',
     389                #        self.figmgr.toolbar.release)
    393390
    394391        else:
     
    459456                    print 'Written file %s' % (fname)
    460457            except IOError, msg:
    461                 print 'Failed to save %s: Error msg was\n\n%s' % (fname, msg)
     458                #print 'Failed to save %s: Error msg was\n\n%s' % (fname, err)
     459                print_log()
     460                asaplog.push('Failed to save %s: Error msg was\n\n%s' % (fname, str(msg)))
     461                print_log( 'ERROR' )
    462462                return
    463463        else:
    464             print "Invalid image type. Valid types are:"
    465             print "'ps', 'eps', 'png'"
     464            #print "Invalid image type. Valid types are:"
     465            #print "'ps', 'eps', 'png'"
     466            asaplog.push( "Invalid image type. Valid types are:" )
     467            asaplog.push( "'ps', 'eps', 'png'" )
     468            print_log('WARN')
    466469
    467470
     
    575578
    576579
    577     def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, ganged=True):
     580    #def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, ganged=True):
     581    def set_panels(self, rows=1, cols=0, n=-1, nplots=-1, layout=None,ganged=True):
    578582        """
    579583        Set the panel layout.
     
    598602            self.set_title()
    599603
     604        if layout:
     605            lef, bot, rig, top, wsp, hsp = layout
     606            self.figure.subplots_adjust(
     607                left=lef,bottom=bot,right=rig,top=top,wspace=wsp,hspace=hsp)
     608            del lef,bot,rig,top,wsp,hsp
     609
    600610        if rows < 1: rows = 1
    601611
     
    610620        if 0 <= n < rows*cols:
    611621            i = len(self.subplots)
     622
    612623            self.subplots.append({})
    613624
     
    644655                                                cols, i+1)
    645656                        if asaprcParams['plotter.axesformatting'] != 'mpl':
    646 
     657                           
    647658                            self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter())
    648659                    else:
     
    671682                self.cols = cols
    672683            self.subplot(0)
     684        del rows,cols,n,nplots,layout,ganged,i
    673685
    674686    def tidy(self):
     
    725737                        sp['axes'].legend((' '))
    726738
    727 
    728739            from matplotlib.artist import setp
    729740            fpx = FP(size=rcParams['xtick.labelsize'])
     
    734745            fpat = FP(size=rcParams['axes.titlesize'])
    735746            axsize =  fpa.get_size_in_points()
    736             tsize =  fpat.get_size_in_points()
     747            tsize =  fpat.get_size_in_points()-(self.cols)/2
    737748            for sp in self.subplots:
    738749                ax = sp['axes']
    739                 off = 0
    740                 if len(self.subplots) > 1:
    741                     off = self.cols+self.rows
    742                 ax.title.set_size(tsize-off)
     750                ax.title.set_size(tsize)
    743751                setp(ax.get_xticklabels(), fontsize=xts)
    744752                setp(ax.get_yticklabels(), fontsize=yts)
    745753                off = 0
    746                 if self.cols > 1:
    747                     off = self.cols
     754                if self.cols > 1: off = self.cols
    748755                ax.xaxis.label.set_size(axsize-off)
    749                 if self.rows > 1:
    750                     off = self.rows
     756                off = 0
     757                if self.rows > 1: off = self.rows
    751758                ax.yaxis.label.set_size(axsize-off)
    752759
  • branches/mergetest/python/asaplotgui.py

    r1563 r1779  
    5656        self.window.lift()
    5757
    58     def position(self):
    59         """
    60         Use the mouse to get a position from a graph.
    61         """
    62 
    63         def position_disable(event):
    64             self.register('button_press', None)
    65             print '%.4f, %.4f' % (event.xdata, event.ydata)
    66 
    67         print 'Press any mouse button...'
    68         self.register('button_press', position_disable)
    69 
    70 
    7158    def quit(self):
    7259        """
     
    7461        """
    7562        self.window.destroy()
    76 
    77 
    78     def region(self):
    79         """
    80         Use the mouse to get a rectangular region from a plot.
    81 
    82         The return value is [x0, y0, x1, y1] in world coordinates.
    83         """
    84 
    85         def region_start(event):
    86             height = self.canvas.figure.bbox.height()
    87             self.rect = {'fig': None, 'height': height,
    88                          'x': event.x, 'y': height - event.y,
    89                          'world': [event.xdata, event.ydata,
    90                                    event.xdata, event.ydata]}
    91             self.register('button_press', None)
    92             self.register('motion_notify', region_draw)
    93             self.register('button_release', region_disable)
    94 
    95         def region_draw(event):
    96             self.canvas._tkcanvas.delete(self.rect['fig'])
    97             self.rect['fig'] = self.canvas._tkcanvas.create_rectangle(
    98                                 self.rect['x'], self.rect['y'],
    99                                 event.x, self.rect['height'] - event.y)
    100 
    101         def region_disable(event):
    102             self.register('motion_notify', None)
    103             self.register('button_release', None)
    104 
    105             self.canvas._tkcanvas.delete(self.rect['fig'])
    106 
    107             self.rect['world'][2:4] = [event.xdata, event.ydata]
    108             print '(%.2f, %.2f)  (%.2f, %.2f)' % (self.rect['world'][0],
    109                 self.rect['world'][1], self.rect['world'][2],
    110                 self.rect['world'][3])
    111 
    112         self.register('button_press', region_start)
    113 
    114         # This has to be modified to block and return the result (currently
    115         # printed by region_disable) when that becomes possible in matplotlib.
    116 
    117         return [0.0, 0.0, 0.0, 0.0]
    118 
    119 
    120     def register(self, type=None, func=None):
    121         """
    122         Register, reregister, or deregister events of type 'button_press',
    123         'button_release', or 'motion_notify'.
    124 
    125         The specified callback function should have the following signature:
    126 
    127             def func(event)
    128 
    129         where event is an MplEvent instance containing the following data:
    130 
    131             name                # Event name.
    132             canvas              # FigureCanvas instance generating the event.
    133             x      = None       # x position - pixels from left of canvas.
    134             y      = None       # y position - pixels from bottom of canvas.
    135             button = None       # Button pressed: None, 1, 2, 3.
    136             key    = None       # Key pressed: None, chr(range(255)), shift,
    137                                   win, or control
    138             inaxes = None       # Axes instance if cursor within axes.
    139             xdata  = None       # x world coordinate.
    140             ydata  = None       # y world coordinate.
    141 
    142         For example:
    143 
    144             def mouse_move(event):
    145                 print event.xdata, event.ydata
    146 
    147             a = asaplot()
    148             a.register('motion_notify', mouse_move)
    149 
    150         If func is None, the event is deregistered.
    151 
    152         Note that in TkAgg keyboard button presses don't generate an event.
    153         """
    154 
    155         if not self.events.has_key(type): return
    156 
    157         if func is None:
    158             if self.events[type] is not None:
    159                 # It's not clear that this does anything.
    160                 self.canvas.mpl_disconnect(self.events[type])
    161                 self.events[type] = None
    162 
    163                 # It seems to be necessary to return events to the toolbar.
    164                 if type == 'motion_notify':
    165                     self.canvas.mpl_connect(type + '_event',
    166                         self.figmgr.toolbar.mouse_move)
    167                 elif type == 'button_press':
    168                     self.canvas.mpl_connect(type + '_event',
    169                         self.figmgr.toolbar.press)
    170                 elif type == 'button_release':
    171                     self.canvas.mpl_connect(type + '_event',
    172                         self.figmgr.toolbar.release)
    173 
    174         else:
    175             self.events[type] = self.canvas.mpl_connect(type + '_event', func)
    176 
    17763
    17864    def show(self, hardrefresh=True):
  • branches/mergetest/python/asaplotgui_gtk.py

    r1563 r1779  
    5757        #self.window.lift()
    5858
    59     def position(self):
    60         """
    61         Use the mouse to get a position from a graph.
    62         """
    63 
    64         def position_disable(event):
    65             self.register('button_press', None)
    66             print '%.4f, %.4f' % (event.xdata, event.ydata)
    67 
    68         print 'Press any mouse button...'
    69         self.register('button_press', position_disable)
     59#     def position(self):
     60#         """
     61#         Use the mouse to get a position from a graph.
     62#         """
     63
     64#         def position_disable(event):
     65#             self.register('button_press', None)
     66#             print '%.4f, %.4f' % (event.xdata, event.ydata)
     67
     68#         print 'Press any mouse button...'
     69#         self.register('button_press', position_disable)
    7070
    7171
     
    7777
    7878
    79     def region(self):
    80         """
    81         Use the mouse to get a rectangular region from a plot.
    82 
    83         The return value is [x0, y0, x1, y1] in world coordinates.
    84         """
    85 
    86         def region_start(event):
    87             height = self.canvas.figure.bbox.height()
    88             self.rect = {'fig': None, 'height': height,
    89                          'x': event.x, 'y': height - event.y,
    90                          'world': [event.xdata, event.ydata,
    91                                    event.xdata, event.ydata]}
    92             self.register('button_press', None)
    93             self.register('motion_notify', region_draw)
    94             self.register('button_release', region_disable)
    95 
    96         def region_draw(event):
    97             self.canvas._tkcanvas.delete(self.rect['fig'])
    98             self.rect['fig'] = self.canvas._tkcanvas.create_rectangle(
    99                                 self.rect['x'], self.rect['y'],
    100                                 event.x, self.rect['height'] - event.y)
    101 
    102         def region_disable(event):
    103             self.register('motion_notify', None)
    104             self.register('button_release', None)
    105 
    106             self.canvas._tkcanvas.delete(self.rect['fig'])
    107 
    108             self.rect['world'][2:4] = [event.xdata, event.ydata]
    109             print '(%.2f, %.2f)  (%.2f, %.2f)' % (self.rect['world'][0],
    110                 self.rect['world'][1], self.rect['world'][2],
    111                 self.rect['world'][3])
    112 
    113         self.register('button_press', region_start)
    114 
    115         # This has to be modified to block and return the result (currently
    116         # printed by region_disable) when that becomes possible in matplotlib.
    117 
    118         return [0.0, 0.0, 0.0, 0.0]
    119 
    120 
    121     def register(self, type=None, func=None):
    122         """
    123         Register, reregister, or deregister events of type 'button_press',
    124         'button_release', or 'motion_notify'.
    125 
    126         The specified callback function should have the following signature:
    127 
    128             def func(event)
    129 
    130         where event is an MplEvent instance containing the following data:
    131 
    132             name                # Event name.
    133             canvas              # FigureCanvas instance generating the event.
    134             x      = None       # x position - pixels from left of canvas.
    135             y      = None       # y position - pixels from bottom of canvas.
    136             button = None       # Button pressed: None, 1, 2, 3.
    137             key    = None       # Key pressed: None, chr(range(255)), shift,
    138                                   win, or control
    139             inaxes = None       # Axes instance if cursor within axes.
    140             xdata  = None       # x world coordinate.
    141             ydata  = None       # y world coordinate.
    142 
    143         For example:
    144 
    145             def mouse_move(event):
    146                 print event.xdata, event.ydata
    147 
    148             a = asaplot()
    149             a.register('motion_notify', mouse_move)
    150 
    151         If func is None, the event is deregistered.
    152 
    153         Note that in TkAgg keyboard button presses don't generate an event.
    154         """
    155 
    156         if not self.events.has_key(type): return
    157 
    158         if func is None:
    159             if self.events[type] is not None:
    160                 # It's not clear that this does anything.
    161                 self.canvas.mpl_disconnect(self.events[type])
    162                 self.events[type] = None
    163 
    164                 # It seems to be necessary to return events to the toolbar.
    165                 if type == 'motion_notify':
    166                     self.canvas.mpl_connect(type + '_event',
    167                         self.figmgr.toolbar.mouse_move)
    168                 elif type == 'button_press':
    169                     self.canvas.mpl_connect(type + '_event',
    170                         self.figmgr.toolbar.press)
    171                 elif type == 'button_release':
    172                     self.canvas.mpl_connect(type + '_event',
    173                         self.figmgr.toolbar.release)
    174 
    175         else:
    176             self.events[type] = self.canvas.mpl_connect(type + '_event', func)
     79#     def region(self):
     80#         """
     81#         Use the mouse to get a rectangular region from a plot.
     82
     83#         The return value is [x0, y0, x1, y1] in world coordinates.
     84#         """
     85
     86#         def region_start(event):
     87#             height = self.canvas.figure.bbox.height()
     88#             self.rect = {'fig': None, 'height': height,
     89#                          'x': event.x, 'y': height - event.y,
     90#                          'world': [event.xdata, event.ydata,
     91#                                    event.xdata, event.ydata]}
     92#             self.register('button_press', None)
     93#             self.register('motion_notify', region_draw)
     94#             self.register('button_release', region_disable)
     95
     96#         def region_draw(event):
     97#             self.canvas._tkcanvas.delete(self.rect['fig'])
     98#             self.rect['fig'] = self.canvas._tkcanvas.create_rectangle(
     99#                                 self.rect['x'], self.rect['y'],
     100#                                 event.x, self.rect['height'] - event.y)
     101
     102#         def region_disable(event):
     103#             self.register('motion_notify', None)
     104#             self.register('button_release', None)
     105
     106#             self.canvas._tkcanvas.delete(self.rect['fig'])
     107
     108#             self.rect['world'][2:4] = [event.xdata, event.ydata]
     109#             print '(%.2f, %.2f)  (%.2f, %.2f)' % (self.rect['world'][0],
     110#                 self.rect['world'][1], self.rect['world'][2],
     111#                 self.rect['world'][3])
     112
     113#         self.register('button_press', region_start)
     114
     115#         # This has to be modified to block and return the result (currently
     116#         # printed by region_disable) when that becomes possible in matplotlib.
     117
     118#         return [0.0, 0.0, 0.0, 0.0]
     119
     120
     121#     def register(self, type=None, func=None):
     122#         """
     123#         Register, reregister, or deregister events of type 'button_press',
     124#         'button_release', or 'motion_notify'.
     125
     126#         The specified callback function should have the following signature:
     127
     128#             def func(event)
     129
     130#         where event is an MplEvent instance containing the following data:
     131
     132#             name                # Event name.
     133#             canvas              # FigureCanvas instance generating the event.
     134#             x      = None       # x position - pixels from left of canvas.
     135#             y      = None       # y position - pixels from bottom of canvas.
     136#             button = None       # Button pressed: None, 1, 2, 3.
     137#             key    = None       # Key pressed: None, chr(range(255)), shift,
     138#                                   win, or control
     139#             inaxes = None       # Axes instance if cursor within axes.
     140#             xdata  = None       # x world coordinate.
     141#             ydata  = None       # y world coordinate.
     142
     143#         For example:
     144
     145#             def mouse_move(event):
     146#                 print event.xdata, event.ydata
     147
     148#             a = asaplot()
     149#             a.register('motion_notify', mouse_move)
     150
     151#         If func is None, the event is deregistered.
     152
     153#         Note that in TkAgg keyboard button presses don't generate an event.
     154#         """
     155
     156#         if not self.events.has_key(type): return
     157
     158#         if func is None:
     159#             if self.events[type] is not None:
     160#                 # It's not clear that this does anything.
     161#                 self.canvas.mpl_disconnect(self.events[type])
     162#                 self.events[type] = None
     163
     164#                 # It seems to be necessary to return events to the toolbar.
     165#                 if type == 'motion_notify':
     166#                     self.canvas.mpl_connect(type + '_event',
     167#                         self.figmgr.toolbar.mouse_move)
     168#                 elif type == 'button_press':
     169#                     self.canvas.mpl_connect(type + '_event',
     170#                         self.figmgr.toolbar.press)
     171#                 elif type == 'button_release':
     172#                     self.canvas.mpl_connect(type + '_event',
     173#                         self.figmgr.toolbar.release)
     174
     175#         else:
     176#             self.events[type] = self.canvas.mpl_connect(type + '_event', func)
    177177
    178178
  • branches/mergetest/python/asapmath.py

    r1591 r1779  
    11from asap.scantable import scantable
    22from asap import rcParams
    3 from asap import print_log_dec
     3from asap import print_log, print_log_dec
    44from asap import selector
    5 
    6 @print_log_dec
     5from asap import asaplog
     6from asap import asaplotgui
     7
     8#@print_log_dec
    79def average_time(*args, **kwargs):
    810    """
     
    4648    if kwargs.has_key('align'):
    4749        align = kwargs.get('align')
     50    compel = False
     51    if kwargs.has_key('compel'):
     52        compel = kwargs.get('compel')
    4853    varlist = vars()
    4954    if isinstance(args[0],list):
     
    6469            msg = "Please give a list of scantables"
    6570            if rcParams['verbose']:
    66                 print msg
     71                #print msg
     72                asaplog.push(msg)
     73                print_log('ERROR')
    6774                return
    6875            else:
     
    8794        del merged
    8895    else:
    89         s = scantable(stm._average(alignedlst, mask, weight.upper(), scanav))
     96        #s = scantable(stm._average(alignedlst, mask, weight.upper(), scanav))
     97        s = scantable(stm._new_average(alignedlst, compel, mask, weight.upper(), scanav))
    9098    s._add_history("average_time",varlist)
     99    print_log()
    91100    return s
    92101
     
    111120    s = scantable(stm._quotient(source, reference, preserve))
    112121    s._add_history("quotient",varlist)
     122    print_log()
    113123    return s
    114124
    115 @print_log_dec
     125#@print_log_dec
    116126def dototalpower(calon, caloff, tcalval=0.0):
    117127    """
     
    129139    s = scantable(stm._dototalpower(calon, caloff, tcalval))
    130140    s._add_history("dototalpower",varlist)
     141    print_log()
    131142    return s
    132143
    133 @print_log_dec
     144#@print_log_dec
    134145def dosigref(sig, ref, smooth, tsysval=0.0, tauval=0.0):
    135146    """
     
    149160    s = scantable(stm._dosigref(sig, ref, smooth, tsysval, tauval))
    150161    s._add_history("dosigref",varlist)
     162    print_log()
    151163    return s
    152164
    153 @print_log_dec
    154 def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0):
     165#@print_log_dec
     166def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    155167    """
    156168    Calibrate GBT position switched data
     
    176188    varlist = vars()
    177189    # check for the appropriate data
    178     s = scantab.get_scan('*_ps*')
    179     if s is None:
     190##    s = scantab.get_scan('*_ps*')
     191##     if s is None:
     192##         msg = "The input data appear to contain no position-switch mode data."
     193##         if rcParams['verbose']:
     194##             #print msg
     195##             asaplog.push(msg)
     196##             print_log('ERROR')
     197##             return
     198##         else:
     199##             raise TypeError(msg)
     200    s = scantab.copy()
     201    from asap._asap import srctype
     202    sel = selector()
     203    sel.set_types( srctype.pson )
     204    try:
     205        scantab.set_selection( sel )
     206    except Exception, e:
    180207        msg = "The input data appear to contain no position-switch mode data."
    181208        if rcParams['verbose']:
    182             print msg
     209            #print msg
     210            asaplog.push(msg)
     211            print_log('ERROR')
    183212            return
    184213        else:
    185214            raise TypeError(msg)
     215    s.set_selection()
     216    sel.reset()
    186217    ssub = s.get_scan(scannos)
    187218    if ssub is None:
    188219        msg = "No data was found with given scan numbers!"
    189220        if rcParams['verbose']:
    190             print msg
     221            #print msg
     222            asaplog.push(msg)
     223            print_log('ERROR')
    191224            return
    192225        else:
    193226            raise TypeError(msg)
    194     ssubon = ssub.get_scan('*calon')
    195     ssuboff = ssub.get_scan('*[^calon]')
     227    #ssubon = ssub.get_scan('*calon')
     228    #ssuboff = ssub.get_scan('*[^calon]')
     229    sel.set_types( [srctype.poncal,srctype.poffcal] )
     230    ssub.set_selection( sel )
     231    ssubon = ssub.copy()
     232    ssub.set_selection()
     233    sel.reset()
     234    sel.set_types( [srctype.pson,srctype.psoff] )
     235    ssub.set_selection( sel )
     236    ssuboff = ssub.copy()
     237    ssub.set_selection()
     238    sel.reset()
    196239    if ssubon.nrow() != ssuboff.nrow():
    197240        msg = "mismatch in numbers of CAL on/off scans. Cannot calibrate. Check the scan numbers."
    198241        if rcParams['verbose']:
    199             print msg
     242            #print msg
     243            asaplog.push(msg)
     244            print_log('ERROR')
    200245            return
    201246        else:
    202247            raise TypeError(msg)
    203248    cals = dototalpower(ssubon, ssuboff, tcalval)
    204     sig = cals.get_scan('*ps')
    205     ref = cals.get_scan('*psr')
     249    #sig = cals.get_scan('*ps')
     250    #ref = cals.get_scan('*psr')
     251    sel.set_types( srctype.pson )
     252    cals.set_selection( sel )
     253    sig = cals.copy()
     254    cals.set_selection()
     255    sel.reset()
     256    sel.set_types( srctype.psoff )
     257    cals.set_selection( sel )
     258    ref = cals.copy()
     259    cals.set_selection()
     260    sel.reset()
    206261    if sig.nscan() != ref.nscan():
    207262        msg = "mismatch in numbers of on/off scans. Cannot calibrate. Check the scan numbers."
    208263        if rcParams['verbose']:
    209             print msg
     264            #print msg
     265            asaplog.push(msg)
     266            print_log('ERROR')
    210267            return
    211268        else:
     
    217274            msg = "Need to supply a valid tau to use the supplied Tsys"
    218275            if rcParams['verbose']:
    219                 print msg
     276                #print msg
     277                asaplog.push(msg)
     278                print_log('ERROR')
    220279                return
    221280            else:
     
    236295    #ress = dosigref(sig, ref, smooth, tsysval)
    237296    ress = dosigref(sig, ref, smooth, tsysval, tauval)
     297    ###
     298    if verify:
     299        # get data
     300        import numpy
     301        precal={}
     302        postcal=[]
     303        keys=['ps','ps_calon','psr','psr_calon']
     304        types=[srctype.pson,srctype.poncal,srctype.psoff,srctype.poffcal]
     305        ifnos=list(ssub.getifnos())
     306        polnos=list(ssub.getpolnos())
     307        sel=selector()
     308        for i in range(2):
     309            #ss=ssuboff.get_scan('*'+keys[2*i])
     310            ll=[]
     311            for j in range(len(ifnos)):
     312                for k in range(len(polnos)):
     313                    sel.set_ifs(ifnos[j])
     314                    sel.set_polarizations(polnos[k])
     315                    sel.set_types(types[2*i])
     316                    try:
     317                        #ss.set_selection(sel)
     318                        ssuboff.set_selection(sel)
     319                    except:
     320                        continue
     321                    #ll.append(numpy.array(ss._getspectrum(0)))
     322                    ll.append(numpy.array(ssuboff._getspectrum(0)))
     323                    sel.reset()
     324                    ssuboff.set_selection()
     325            precal[keys[2*i]]=ll
     326            #del ss
     327            #ss=ssubon.get_scan('*'+keys[2*i+1])
     328            ll=[]
     329            for j in range(len(ifnos)):
     330                for k in range(len(polnos)):
     331                    sel.set_ifs(ifnos[j])
     332                    sel.set_polarizations(polnos[k])
     333                    sel.set_types(types[2*i+1])
     334                    try:
     335                        #ss.set_selection(sel)
     336                        ssubon.set_selection(sel)
     337                    except:
     338                        continue
     339                    #ll.append(numpy.array(ss._getspectrum(0)))
     340                    ll.append(numpy.array(ssubon._getspectrum(0)))
     341                    sel.reset()
     342                    ssubon.set_selection()
     343            precal[keys[2*i+1]]=ll
     344            #del ss
     345        for j in range(len(ifnos)):
     346            for k in range(len(polnos)):
     347                sel.set_ifs(ifnos[j])
     348                sel.set_polarizations(polnos[k])
     349                try:
     350                    ress.set_selection(sel)
     351                except:
     352                    continue
     353                postcal.append(numpy.array(ress._getspectrum(0)))
     354                sel.reset()
     355                ress.set_selection()
     356        del sel
     357        # plot
     358        print_log()
     359        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
     360        print_log('WARN')
     361        p=asaplotgui.asaplotgui()
     362        #nr=min(6,len(ifnos)*len(polnos))
     363        nr=len(ifnos)*len(polnos)
     364        titles=[]
     365        btics=[]
     366        if nr<4:
     367            p.set_panels(rows=nr,cols=2,nplots=2*nr,ganged=False)
     368            for i in range(2*nr):
     369                b=False
     370                if i >= 2*nr-2:
     371                    b=True
     372                btics.append(b)
     373        elif nr==4:
     374            p.set_panels(rows=2,cols=4,nplots=8,ganged=False)
     375            for i in range(2*nr):
     376                b=False
     377                if i >= 2*nr-4:
     378                    b=True
     379                btics.append(b)
     380        elif nr<7:
     381            p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False)
     382            for i in range(2*nr):
     383                if i >= 2*nr-4:
     384                    b=True
     385                btics.append(b)
     386        else:
     387            print_log()
     388            asaplog.push('Only first 6 [if,pol] pairs are plotted.')
     389            print_log('WARN')
     390            nr=6
     391            for i in range(2*nr):
     392                b=False
     393                if i >= 2*nr-4:
     394                    b=True
     395                btics.append(b)
     396            p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False)
     397        for i in range(nr):
     398            p.subplot(2*i)
     399            p.color=0
     400            title='raw data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)])
     401            titles.append(title)
     402            #p.set_axes('title',title,fontsize=40)
     403            ymin=1.0e100
     404            ymax=-1.0e100
     405            nchan=s.nchan()
     406            edge=int(nchan*0.01)
     407            for j in range(4):
     408                spmin=min(precal[keys[j]][i][edge:nchan-edge])
     409                spmax=max(precal[keys[j]][i][edge:nchan-edge])
     410                ymin=min(ymin,spmin)
     411                ymax=max(ymax,spmax)
     412            for j in range(4):
     413                if i==0:
     414                    p.set_line(label=keys[j])
     415                else:
     416                    p.legend()
     417                p.plot(precal[keys[j]][i])
     418            p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax))
     419            if not btics[2*i]:
     420                p.axes.set_xticks([])
     421            p.subplot(2*i+1)
     422            p.color=0
     423            title='cal data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)])
     424            titles.append(title)
     425            #p.set_axes('title',title)
     426            p.legend()
     427            ymin=postcal[i][edge:nchan-edge].min()
     428            ymax=postcal[i][edge:nchan-edge].max()
     429            p.plot(postcal[i])
     430            p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax))
     431            if not btics[2*i+1]:
     432                p.axes.set_xticks([])
     433        for i in range(2*nr):
     434            p.subplot(i)
     435            p.set_axes('title',titles[i],fontsize='medium')
     436        x=raw_input('Accept calibration ([y]/n): ' )
     437        if x.upper() == 'N':
     438            p.unmap()
     439            del p
     440            return scabtab
     441        p.unmap()
     442        del p
     443    ###
    238444    ress._add_history("calps", varlist)
     445    print_log()
    239446    return ress
    240447
    241 @print_log_dec
    242 def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0):
     448#@print_log_dec
     449def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    243450    """
    244451    Do full (but a pair of scans at time) processing of GBT Nod data
     
    255462    varlist = vars()
    256463    from asap._asap import stmath
     464    from asap._asap import srctype
    257465    stm = stmath()
    258466    stm._setinsitu(False)
    259467
    260468    # check for the appropriate data
    261     s = scantab.get_scan('*_nod*')
    262     if s is None:
     469##     s = scantab.get_scan('*_nod*')
     470##     if s is None:
     471##         msg = "The input data appear to contain no Nod observing mode data."
     472##         if rcParams['verbose']:
     473##             #print msg
     474##             asaplog.push(msg)
     475##             print_log('ERROR')
     476##             return
     477##         else:
     478##             raise TypeError(msg)
     479    s = scantab.copy()
     480    sel = selector()
     481    sel.set_types( srctype.nod )
     482    try:
     483        s.set_selection( sel )
     484    except Exception, e:
    263485        msg = "The input data appear to contain no Nod observing mode data."
    264486        if rcParams['verbose']:
    265             print msg
     487            #print msg
     488            asaplog.push(msg)
     489            print_log('ERROR')
    266490            return
    267491        else:
    268492            raise TypeError(msg)
     493    sel.reset()
     494    del sel
     495    del s
    269496
    270497    # need check correspondance of each beam with sig-ref ...
     
    300527            msg = "Need to supply a valid tau to use the supplied Tsys"
    301528            if rcParams['verbose']:
    302                 print msg
     529                #print msg
     530                asaplog.push(msg)
     531                print_log('ERROR')
    303532                return
    304533            else:
     
    307536            scantab.recalc_azel()
    308537    resspec = scantable(stm._donod(scantab, pairScans, smooth, tsysval,tauval,tcalval))
     538    ###
     539    if verify:
     540        # get data
     541        import numpy
     542        precal={}
     543        postcal=[]
     544        keys=['','_calon']
     545        types=[srctype.nod,srctype.nodcal]
     546        ifnos=list(scantab.getifnos())
     547        polnos=list(scantab.getpolnos())
     548        sel=selector()
     549        ss = scantab.copy()
     550        for i in range(2):
     551            #ss=scantab.get_scan('*'+keys[i])
     552            ll=[]
     553            ll2=[]
     554            for j in range(len(ifnos)):
     555                for k in range(len(polnos)):
     556                    sel.set_ifs(ifnos[j])
     557                    sel.set_polarizations(polnos[k])
     558                    sel.set_scans(pairScans[0])
     559                    sel.set_types(types[i])
     560                    try:
     561                        ss.set_selection(sel)
     562                    except:
     563                        continue
     564                    ll.append(numpy.array(ss._getspectrum(0)))
     565                    sel.reset()
     566                    ss.set_selection()
     567                    sel.set_ifs(ifnos[j])
     568                    sel.set_polarizations(polnos[k])
     569                    sel.set_scans(pairScans[1])
     570                    sel.set_types(types[i])
     571                    try:
     572                        ss.set_selection(sel)
     573                    except:
     574                        ll.pop()
     575                        continue
     576                    ll2.append(numpy.array(ss._getspectrum(0)))
     577                    sel.reset()
     578                    ss.set_selection()
     579            key='%s%s' %(pairScans[0],keys[i])
     580            precal[key]=ll
     581            key='%s%s' %(pairScans[1],keys[i])
     582            precal[key]=ll2
     583            #del ss
     584        keys=precal.keys()
     585        for j in range(len(ifnos)):
     586            for k in range(len(polnos)):
     587                sel.set_ifs(ifnos[j])
     588                sel.set_polarizations(polnos[k])
     589                sel.set_scans(pairScans[0])
     590                try:
     591                    resspec.set_selection(sel)
     592                except:
     593                    continue
     594                postcal.append(numpy.array(resspec._getspectrum(0)))
     595                sel.reset()
     596                resspec.set_selection()
     597        del sel
     598        # plot
     599        print_log()
     600        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
     601        print_log('WARN')
     602        p=asaplotgui.asaplotgui()
     603        #nr=min(6,len(ifnos)*len(polnos))
     604        nr=len(ifnos)*len(polnos)
     605        titles=[]
     606        btics=[]
     607        if nr<4:
     608            p.set_panels(rows=nr,cols=2,nplots=2*nr,ganged=False)
     609            for i in range(2*nr):
     610                b=False
     611                if i >= 2*nr-2:
     612                    b=True
     613                btics.append(b)
     614        elif nr==4:
     615            p.set_panels(rows=2,cols=4,nplots=8,ganged=False)
     616            for i in range(2*nr):
     617                b=False
     618                if i >= 2*nr-4:
     619                    b=True
     620                btics.append(b)
     621        elif nr<7:
     622            p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False)
     623            for i in range(2*nr):
     624                if i >= 2*nr-4:
     625                    b=True
     626                btics.append(b)
     627        else:
     628            print_log()
     629            asaplog.push('Only first 6 [if,pol] pairs are plotted.')
     630            print_log('WARN')
     631            nr=6
     632            for i in range(2*nr):
     633                b=False
     634                if i >= 2*nr-4:
     635                    b=True
     636                btics.append(b)
     637            p.set_panels(rows=3,cols=4,nplots=2*nr,ganged=False)
     638        for i in range(nr):
     639            p.subplot(2*i)
     640            p.color=0
     641            title='raw data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)])
     642            titles.append(title)
     643            #p.set_axes('title',title,fontsize=40)
     644            ymin=1.0e100
     645            ymax=-1.0e100
     646            nchan=scantab.nchan()
     647            edge=int(nchan*0.01)
     648            for j in range(4):
     649                spmin=min(precal[keys[j]][i][edge:nchan-edge])
     650                spmax=max(precal[keys[j]][i][edge:nchan-edge])
     651                ymin=min(ymin,spmin)
     652                ymax=max(ymax,spmax)
     653            for j in range(4):
     654                if i==0:
     655                    p.set_line(label=keys[j])
     656                else:
     657                    p.legend()
     658                p.plot(precal[keys[j]][i])
     659            p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax))
     660            if not btics[2*i]:
     661                p.axes.set_xticks([])
     662            p.subplot(2*i+1)
     663            p.color=0
     664            title='cal data IF%s POL%s' % (ifnos[int(i/len(polnos))],polnos[i%len(polnos)])
     665            titles.append(title)
     666            #p.set_axes('title',title)
     667            p.legend()
     668            ymin=postcal[i][edge:nchan-edge].min()
     669            ymax=postcal[i][edge:nchan-edge].max()
     670            p.plot(postcal[i])
     671            p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax))
     672            if not btics[2*i+1]:
     673                p.axes.set_xticks([])
     674        for i in range(2*nr):
     675            p.subplot(i)
     676            p.set_axes('title',titles[i],fontsize='medium')
     677        x=raw_input('Accept calibration ([y]/n): ' )
     678        if x.upper() == 'N':
     679            p.unmap()
     680            del p
     681            return scabtab
     682        p.unmap()
     683        del p
     684    ###
    309685    resspec._add_history("calnod",varlist)
     686    print_log()
    310687    return resspec
    311688
    312 @print_log_dec
    313 def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0):
     689#@print_log_dec
     690def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    314691    """
    315692    Calibrate GBT frequency switched data.
     
    333710    varlist = vars()
    334711    from asap._asap import stmath
     712    from asap._asap import srctype
    335713    stm = stmath()
    336714    stm._setinsitu(False)
     
    348726
    349727    resspec = scantable(stm._dofs(s, scannos, smooth, tsysval,tauval,tcalval))
     728    ###
     729    if verify:
     730        # get data
     731        ssub = s.get_scan(scannos)
     732        #ssubon = ssub.get_scan('*calon')
     733        #ssuboff = ssub.get_scan('*[^calon]')
     734        sel = selector()
     735        sel.set_types( [srctype.foncal,srctype.foffcal] )
     736        ssub.set_selection( sel )
     737        ssubon = ssub.copy()
     738        ssub.set_selection()
     739        sel.reset()
     740        sel.set_types( [srctype.fson,srctype.fsoff] )
     741        ssub.set_selection( sel )
     742        ssuboff = ssub.copy()
     743        ssub.set_selection()
     744        sel.reset()
     745        import numpy
     746        precal={}
     747        postcal=[]
     748        keys=['fs','fs_calon','fsr','fsr_calon']
     749        types=[srctype.fson,srctype.foncal,srctype.fsoff,srctype.foffcal]
     750        ifnos=list(ssub.getifnos())
     751        polnos=list(ssub.getpolnos())
     752        for i in range(2):
     753            #ss=ssuboff.get_scan('*'+keys[2*i])
     754            ll=[]
     755            for j in range(len(ifnos)):
     756                for k in range(len(polnos)):
     757                    sel.set_ifs(ifnos[j])
     758                    sel.set_polarizations(polnos[k])
     759                    sel.set_types(types[2*i])
     760                    try:
     761                        #ss.set_selection(sel)
     762                        ssuboff.set_selection(sel)
     763                    except:
     764                        continue
     765                    ll.append(numpy.array(ss._getspectrum(0)))
     766                    sel.reset()
     767                    #ss.set_selection()
     768                    ssuboff.set_selection()
     769            precal[keys[2*i]]=ll
     770            #del ss
     771            #ss=ssubon.get_scan('*'+keys[2*i+1])
     772            ll=[]
     773            for j in range(len(ifnos)):
     774                for k in range(len(polnos)):
     775                    sel.set_ifs(ifnos[j])
     776                    sel.set_polarizations(polnos[k])
     777                    sel.set_types(types[2*i+1])
     778                    try:
     779                        #ss.set_selection(sel)
     780                        ssubon.set_selection(sel)
     781                    except:
     782                        continue
     783                    ll.append(numpy.array(ss._getspectrum(0)))
     784                    sel.reset()
     785                    #ss.set_selection()
     786                    ssubon.set_selection()
     787            precal[keys[2*i+1]]=ll
     788            #del ss
     789        #sig=resspec.get_scan('*_fs')
     790        #ref=resspec.get_scan('*_fsr')
     791        sel.set_types( srctype.fson )
     792        resspec.set_selection( sel )
     793        sig=resspec.copy()
     794        resspec.set_selection()
     795        sel.reset()
     796        sel.set_type( srctype.fsoff )
     797        resspec.set_selection( sel )
     798        ref=resspec.copy()
     799        resspec.set_selection()
     800        sel.reset()
     801        for k in range(len(polnos)):
     802            for j in range(len(ifnos)):
     803                sel.set_ifs(ifnos[j])
     804                sel.set_polarizations(polnos[k])
     805                try:
     806                    sig.set_selection(sel)
     807                    postcal.append(numpy.array(sig._getspectrum(0)))
     808                except:
     809                    ref.set_selection(sel)
     810                    postcal.append(numpy.array(ref._getspectrum(0)))
     811                sel.reset()
     812                resspec.set_selection()
     813        del sel
     814        # plot
     815        print_log()
     816        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
     817        print_log('WARN')
     818        p=asaplotgui.asaplotgui()
     819        #nr=min(6,len(ifnos)*len(polnos))
     820        nr=len(ifnos)/2*len(polnos)
     821        titles=[]
     822        btics=[]
     823        if nr>3:
     824            print_log()
     825            asaplog.push('Only first 3 [if,pol] pairs are plotted.')
     826            print_log('WARN')
     827            nr=3
     828        p.set_panels(rows=nr,cols=3,nplots=3*nr,ganged=False)
     829        for i in range(3*nr):
     830            b=False
     831            if i >= 3*nr-3:
     832                b=True
     833            btics.append(b)
     834        for i in range(nr):
     835            p.subplot(3*i)
     836            p.color=0
     837            title='raw data IF%s,%s POL%s' % (ifnos[2*int(i/len(polnos))],ifnos[2*int(i/len(polnos))+1],polnos[i%len(polnos)])
     838            titles.append(title)
     839            #p.set_axes('title',title,fontsize=40)
     840            ymin=1.0e100
     841            ymax=-1.0e100
     842            nchan=s.nchan()
     843            edge=int(nchan*0.01)
     844            for j in range(4):
     845                spmin=min(precal[keys[j]][i][edge:nchan-edge])
     846                spmax=max(precal[keys[j]][i][edge:nchan-edge])
     847                ymin=min(ymin,spmin)
     848                ymax=max(ymax,spmax)
     849            for j in range(4):
     850                if i==0:
     851                    p.set_line(label=keys[j])
     852                else:
     853                    p.legend()
     854                p.plot(precal[keys[j]][i])
     855            p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax))
     856            if not btics[3*i]:
     857                p.axes.set_xticks([])
     858            p.subplot(3*i+1)
     859            p.color=0
     860            title='sig data IF%s POL%s' % (ifnos[2*int(i/len(polnos))],polnos[i%len(polnos)])
     861            titles.append(title)
     862            #p.set_axes('title',title)
     863            p.legend()
     864            ymin=postcal[2*i][edge:nchan-edge].min()
     865            ymax=postcal[2*i][edge:nchan-edge].max()
     866            p.plot(postcal[2*i])
     867            p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax))
     868            if not btics[3*i+1]:
     869                p.axes.set_xticks([])
     870            p.subplot(3*i+2)
     871            p.color=0
     872            title='ref data IF%s POL%s' % (ifnos[2*int(i/len(polnos))+1],polnos[i%len(polnos)])
     873            titles.append(title)
     874            #p.set_axes('title',title)
     875            p.legend()
     876            ymin=postcal[2*i+1][edge:nchan-edge].min()
     877            ymax=postcal[2*i+1][edge:nchan-edge].max()
     878            p.plot(postcal[2*i+1])
     879            p.axes.set_ylim(ymin-0.1*abs(ymin),ymax+0.1*abs(ymax))
     880            if not btics[3*i+2]:
     881                p.axes.set_xticks([])
     882        for i in range(3*nr):
     883            p.subplot(i)
     884            p.set_axes('title',titles[i],fontsize='medium')
     885        x=raw_input('Accept calibration ([y]/n): ' )
     886        if x.upper() == 'N':
     887            p.unmap()
     888            del p
     889            return scabtab
     890        p.unmap()
     891        del p
     892    ###
    350893    resspec._add_history("calfs",varlist)
     894    print_log()
    351895    return resspec
    352896
    353 
    354 @print_log_dec
     897#@print_log_dec
    355898def merge(*args):
    356899    """
     
    380923            msg = "Please give a list of scantables"
    381924            if rcParams['verbose']:
    382                 print msg
     925                #print msg
     926                asaplog.push(msg)
     927                print_log('ERROR')
    383928                return
    384929            else:
     
    386931    s = scantable(stm._merge(lst))
    387932    s._add_history("merge", varlist)
     933    print_log()
    388934    return s
     935
     936def calibrate( scantab, scannos=[], calmode='none', verify=None ):
     937    """
     938    Calibrate data.
     939   
     940    Parameters:
     941        scantab:       scantable
     942        scannos:       list of scan number
     943        calmode:       calibration mode
     944        verify:        verify calibration     
     945    """
     946    antname = scantab.get_antennaname()
     947    if ( calmode == 'nod' ):
     948        asaplog.push( 'Calibrating nod data.' )
     949        print_log()
     950        scal = calnod( scantab, scannos=scannos, verify=verify )
     951    elif ( calmode == 'quotient' ):
     952        asaplog.push( 'Calibrating using quotient.' )
     953        print_log()
     954        scal = scantab.auto_quotient( verify=verify )
     955    elif ( calmode == 'ps' ):
     956        asaplog.push( 'Calibrating %s position-switched data.' % antname )
     957        print_log()
     958        if ( antname.find( 'APEX' ) != -1 ):
     959            scal = apexcal( scantab, scannos, calmode, verify )
     960        elif ( antname.find( 'ALMA' ) != -1 or antname.find( 'OSF' ) != -1 ):
     961            scal = almacal( scantab, scannos, calmode, verify )
     962        else:
     963            scal = calps( scantab, scannos=scannos, verify=verify )
     964    elif ( calmode == 'fs' or calmode == 'fsotf' ):
     965        asaplog.push( 'Calibrating %s frequency-switched data.' % antname )
     966        print_log()
     967        if ( antname.find( 'APEX' ) != -1 ):
     968            scal = apexcal( scantab, scannos, calmode, verify )
     969        elif ( antname.find( 'ALMA' ) != -1 or antname.find( 'OSF' ) != -1 ):
     970            scal = almacal( scantab, scannos, calmode, verify )
     971        else:
     972            scal = calfs( scantab, scannos=scannos, verify=verify )
     973    elif ( calmode == 'otf' ):
     974        asaplog.push( 'Calibrating %s On-The-Fly data.' % antname )
     975        print_log()
     976        scal = almacal( scantab, scannos, calmode, verify )
     977    else:
     978        asaplog.push( 'No calibration.' )
     979        scal = scantab.copy()
     980
     981    return scal
     982
     983def apexcal( scantab, scannos=[], calmode='none', verify=False ):
     984    """
     985    Calibrate APEX data
     986
     987    Parameters:
     988        scantab:       scantable
     989        scannos:       list of scan number
     990        calmode:       calibration mode
     991
     992        verify:        verify calibration     
     993    """
     994    from asap._asap import stmath
     995    stm = stmath()
     996    antname = scantab.get_antennaname()
     997    ssub = scantab.get_scan( scannos )
     998    scal = scantable( stm.cwcal( ssub, calmode, antname ) )
     999    return scal
     1000
     1001def almacal( scantab, scannos=[], calmode='none', verify=False ):
     1002    """
     1003    Calibrate ALMA data
     1004
     1005    Parameters:
     1006        scantab:       scantable
     1007        scannos:       list of scan number
     1008        calmode:       calibration mode
     1009
     1010        verify:        verify calibration     
     1011    """
     1012    from asap._asap import stmath
     1013    stm = stmath()
     1014    ssub = scantab.get_scan( scannos )
     1015    scal = scantable( stm.almacal( ssub, calmode ) )
     1016    return scal
     1017
     1018def splitant(filename, outprefix='',overwrite=False):
     1019    """
     1020    Split Measurement set by antenna name, save data as a scantables,
     1021    and return a list of filename.
     1022    Notice this method can only be available from CASA.
     1023    Prameter
     1024       filename:    the name of Measurement set to be read.
     1025       outprefix:   the prefix of output scantable name.
     1026                    the names of output scantable will be
     1027                    outprefix.antenna1, outprefix.antenna2, ....
     1028                    If not specified, outprefix = filename is assumed.
     1029       overwrite    If the file should be overwritten if it exists.
     1030                    The default False is to return with warning
     1031                    without writing the output. USE WITH CARE.
     1032                   
     1033    """
     1034    # Import the table toolkit from CASA
     1035    try:
     1036       import casac
     1037    except ImportError:
     1038       if rcParams['verbose']:
     1039           #print "failed to load casa"
     1040           print_log()
     1041           asaplog.push("failed to load casa")
     1042           print_log('ERROR')
     1043       else: raise
     1044       return False
     1045    try:
     1046       tbtool = casac.homefinder.find_home_by_name('tableHome')
     1047       tb = tbtool.create()
     1048       tb2 = tbtool.create()
     1049    except:
     1050       if rcParams['verbose']:
     1051           #print "failed to load a table tool:\n", e
     1052           print_log()
     1053           asaplog.push("failed to load table tool")
     1054           print_log('ERROR')
     1055       else: raise
     1056       return False
     1057    # Check the input filename
     1058    if isinstance(filename, str):
     1059        import os.path
     1060        filename = os.path.expandvars(filename)
     1061        filename = os.path.expanduser(filename)
     1062        if not os.path.exists(filename):
     1063            s = "File '%s' not found." % (filename)
     1064            if rcParams['verbose']:
     1065                print_log()
     1066                asaplog.push(s)
     1067                print_log('ERROR')
     1068                return
     1069            raise IOError(s)
     1070        # check if input file is MS
     1071        if not os.path.isdir(filename) \
     1072               or not os.path.exists(filename+'/ANTENNA') \
     1073               or not os.path.exists(filename+'/table.f1'):
     1074            s = "File '%s' is not a Measurement set." % (filename)
     1075            if rcParams['verbose']:
     1076                print_log()
     1077                asaplog.push(s)
     1078                print_log('ERROR')
     1079                return
     1080            raise IOError(s)
     1081    else:
     1082        s = "The filename should be string. "
     1083        if rcParams['verbose']:
     1084            print_log()
     1085            asaplog.push(s)
     1086            print_log('ERROR')
     1087            return
     1088        raise TypeError(s)
     1089    # Check out put file name
     1090    outname=''
     1091    if len(outprefix) > 0: prefix=outprefix+'.'
     1092    else:
     1093        prefix=filename.rstrip('/')
     1094    # Now do the actual splitting.
     1095    outfiles=[]
     1096    tb.open(tablename=filename+'/ANTENNA',nomodify=True)
     1097    nant=tb.nrows()
     1098    antnames=tb.getcol('NAME',0,nant,1)
     1099    antpos=tb.getcol('POSITION',0,nant,1).transpose()
     1100    tb.close()
     1101    tb.open(tablename=filename,nomodify=True)
     1102    ant1=tb.getcol('ANTENNA1',0,-1,1)
     1103    tb.close()
     1104    for antid in set(ant1):
     1105        scan=scantable(filename,average=False,getpt=True,antenna=int(antid))
     1106        outname=prefix+antnames[antid]+'.asap'
     1107        scan.save(outname,format='ASAP',overwrite=overwrite)
     1108        del scan
     1109        outfiles.append(outname)
     1110    del tb, tb2
     1111    return outfiles
     1112
     1113def _array2dOp( scan, value, mode="ADD", tsys=False ):
     1114    """
     1115    This function is workaround on the basic operation of scantable
     1116    with 2 dimensional float list.
     1117
     1118    scan:    scantable operand
     1119    value:   float list operand
     1120    mode:    operation mode (ADD, SUB, MUL, DIV)
     1121    tsys:    if True, operate tsys as well
     1122    """
     1123    nrow = scan.nrow()
     1124    s = None
     1125    if len( value ) == 1:
     1126        from asap._asap import stmath
     1127        stm = stmath()
     1128        s = scantable( stm._arrayop( scan.copy(), value[0], mode, tsys ) )
     1129        del stm
     1130    elif len( value ) != nrow:
     1131        asaplog.push( 'len(value) must be 1 or conform to scan.nrow()' )
     1132        print_log( 'ERROR' )
     1133    else:
     1134        from asap._asap import stmath
     1135        stm = stmath()
     1136        # insitu must be True
     1137        stm._setinsitu( True )
     1138        s = scan.copy()
     1139        sel = selector()
     1140        for irow in range( nrow ):
     1141            sel.set_rows( irow )
     1142            s.set_selection( sel )
     1143            if len( value[irow] ) == 1:
     1144                stm._unaryop( s, value[irow][0], mode, tsys )
     1145            else:
     1146                stm._arrayop( s, value[irow], mode, tsys, 'channel' )
     1147            s.set_selection()
     1148            sel.reset()
     1149        del sel
     1150        del stm
     1151    return s
     1152
     1153           
     1154           
  • branches/mergetest/python/asapplotter.py

    r1739 r1779  
    11from asap import rcParams, print_log, print_log_dec
    22from asap import selector, scantable
     3from asap import asaplog
    34import matplotlib.axes
    45from matplotlib.font_manager import FontProperties
     
    2122            self._visible = visible
    2223        self._plotter = self._newplotter(**kwargs)
     24        # additional tool bar
     25        self._plotter.figmgr.casabar=self._newcasabar()
    2326
    2427        self._panelling = None
     
    4346        self._hist = rcParams['plotter.histogram']
    4447        self._fp = FontProperties()
     48        self._panellayout = self.set_panellayout(refresh=False)
    4549
    4650    def _translate(self, instr):
     
    5357
    5458    def _newplotter(self, **kwargs):
    55         if self._visible:
     59        backend=matplotlib.get_backend()
     60        if not self._visible:
     61            from asap.asaplot import asaplot
     62        elif backend == 'TkAgg':
    5663            from asap.asaplotgui import asaplotgui as asaplot
     64        elif backend == 'Qt4Agg':
     65            from asap.asaplotgui_qt4 import asaplotgui as asaplot
     66        elif backend == 'GTkAgg':
     67            from asap.asaplotgui_gtk import asaplotgui as asaplot
    5768        else:
    5869            from asap.asaplot import asaplot
    5970        return asaplot(**kwargs)
    6071
    61     @print_log_dec
     72    def _newcasabar(self):
     73        backend=matplotlib.get_backend()
     74        if self._visible and backend == "TkAgg":
     75            from asap.casatoolbar import CustomToolbarTkAgg
     76            return CustomToolbarTkAgg(self)
     77        else: return None
     78
     79    #@print_log_dec
    6280    def plot(self, scan=None):
    6381        """
     
    7290        """
    7391        if self._plotter.is_dead:
     92            if hasattr(self._plotter.figmgr,'casabar'):
     93                del self._plotter.figmgr.casabar
    7494            self._plotter = self._newplotter()
     95            self._plotter.figmgr.casabar=self._newcasabar()
    7596        self._plotter.hold()
    7697        self._plotter.clear()
    77         from asap import scantable
    7898        if not self._data and not scan:
    7999            msg = "Input is not a scantable"
    80100            if rcParams['verbose']:
    81                 print msg
     101                #print msg
     102                asaplog.push( msg )
     103                print_log( 'ERROR' )
    82104                return
    83105            raise TypeError(msg)
    84         if isinstance(scan, scantable):
    85             if self._data is not None:
    86                 if scan != self._data:
    87                     self._data = scan
    88                     # reset
    89                     self._reset()
    90             else:
    91                 self._data = scan
    92                 self._reset()
    93         # ranges become invalid when unit changes
    94         if self._abcunit and self._abcunit != self._data.get_unit():
    95             self._minmaxx = None
    96             self._minmaxy = None
    97             self._abcunit = self._data.get_unit()
    98             self._datamask = None
     106        if scan: self.set_data(scan,refresh=False)
    99107        self._plot(self._data)
    100108        if self._minmaxy is not None:
    101109            self._plotter.set_limits(ylim=self._minmaxy)
     110        if self._plotter.figmgr.casabar: self._plotter.figmgr.casabar.enable_button()
    102111        self._plotter.release()
    103112        self._plotter.tidy()
    104113        self._plotter.show(hardrefresh=False)
     114        print_log()
    105115        return
    106116
     
    170180    def text(self, *args, **kwargs):
    171181        if kwargs.has_key("interactive"):
    172             if kwargs.pop("interactive"):
    173                 pos = self._plotter.get_point()
    174                 args = tuple(pos)+args
     182            #if kwargs.pop("interactive"):
     183            #    pos = self._plotter.get_point()
     184            #    args = tuple(pos)+args
     185            kwargs.pop("interactive")
    175186        self._axes_callback("text", *args, **kwargs)
    176187
     
    179190    def arrow(self, *args, **kwargs):
    180191        if kwargs.has_key("interactive"):
    181             if kwargs.pop("interactive"):
    182                 pos = self._plotter.get_region()
    183                 dpos = (pos[0][0], pos[0][1],
    184                         pos[1][0]-pos[0][0],
    185                         pos[1][1] - pos[0][1])
    186                 args = dpos + args
     192            #if kwargs.pop("interactive"):
     193            #    pos = self._plotter.get_region()
     194            #    dpos = (pos[0][0], pos[0][1],
     195            #            pos[1][0]-pos[0][0],
     196            #            pos[1][1] - pos[0][1])
     197            #    args = dpos + args
     198            kwargs.pop("interactive")
    187199        self._axes_callback("arrow", *args, **kwargs)
    188200
     
    191203    def annotate(self, text, xy=None, xytext=None, **kwargs):
    192204        if kwargs.has_key("interactive"):
    193             if kwargs.pop("interactive"):
    194                 xy = self._plotter.get_point()
    195                 xytext = self._plotter.get_point()
     205            #if kwargs.pop("interactive"):
     206            #    xy = self._plotter.get_point()
     207            #    xytext = self._plotter.get_point()
     208            kwargs.pop("interactive")
    196209        if not kwargs.has_key("arrowprops"):
    197210            kwargs["arrowprops"] = dict(arrowstyle="->")
     
    202215    def axvline(self, *args, **kwargs):
    203216        if kwargs.has_key("interactive"):
    204             if kwargs.pop("interactive"):
    205                 pos = self._plotter.get_point()
    206                 args = (pos[0],)+args
     217            #if kwargs.pop("interactive"):
     218            #    pos = self._plotter.get_point()
     219            #    args = (pos[0],)+args
     220            kwargs.pop("interactive")
    207221        self._axes_callback("axvline", *args, **kwargs)
    208222
     
    211225    def axhline(self, *args, **kwargs):
    212226        if kwargs.has_key("interactive"):
    213             if kwargs.pop("interactive"):
    214                 pos = self._plotter.get_point()
    215                 args = (pos[1],)+args
     227            #if kwargs.pop("interactive"):
     228            #    pos = self._plotter.get_point()
     229            #    args = (pos[1],)+args
     230            kwargs.pop("interactive")
    216231        self._axes_callback("axhline", *args, **kwargs)
    217232
     
    220235    def axvspan(self, *args, **kwargs):
    221236        if kwargs.has_key("interactive"):
    222             if kwargs.pop("interactive"):
    223                 pos = self._plotter.get_region()
    224                 dpos = (pos[0][0], pos[1][0])
    225                 args = dpos + args
     237            #if kwargs.pop("interactive"):
     238            #    pos = self._plotter.get_region()
     239            #    dpos = (pos[0][0], pos[1][0])
     240            #    args = dpos + args
     241            kwargs.pop("interactive")
    226242        self._axes_callback("axvspan", *args, **kwargs)
    227243        # hack to preventy mpl from redrawing the patch
     
    234250    def axhspan(self, *args, **kwargs):
    235251        if kwargs.has_key("interactive"):
    236             if kwargs.pop("interactive"):
    237                 pos = self._plotter.get_region()
    238                 dpos = (pos[0][1], pos[1][1])
    239                 args = dpos + args
    240 
     252            #if kwargs.pop("interactive"):
     253            #    pos = self._plotter.get_region()
     254            #    dpos = (pos[0][1], pos[1][1])
     255            #    args = dpos + args
     256            kwargs.pop("interactive")
    241257        self._axes_callback("axhspan", *args, **kwargs)
    242258        # hack to preventy mpl from redrawing the patch
     
    265281    # end matplotlib.axes fowarding functions
    266282
    267 
    268     def set_mode(self, stacking=None, panelling=None):
     283    def set_data(self, scan, refresh=True):
     284        """
     285        Set a scantable to plot.
     286        Parameters:
     287            scan:      a scantable
     288            refresh:   True (default) or False. If True, the plot is
     289                       replotted based on the new parameter setting(s).
     290                       Otherwise,the parameter(s) are set without replotting.
     291        Note:
     292           The user specified masks and data selections will be reset
     293           if a new scantable is set. This method should be called before
     294           setting data selections (set_selection) and/or masks (set_mask).
     295        """
     296        from asap import scantable
     297        if isinstance(scan, scantable):
     298            if self._data is not None:
     299                if scan != self._data:
     300                    self._data = scan
     301                    # reset
     302                    self._reset()
     303                    msg = "A new scantable is set to the plotter. The masks and data selections are reset."
     304                    asaplog.push( msg )
     305                    print_log( 'INFO' )
     306            else:
     307                self._data = scan
     308                self._reset()
     309        else:
     310            msg = "Input is not a scantable"
     311            if rcParams['verbose']:
     312                #print msg
     313                asaplog.push( msg )
     314                print_log( 'ERROR' )
     315                return
     316            raise TypeError(msg)
     317
     318        # ranges become invalid when unit changes
     319        if self._abcunit and self._abcunit != self._data.get_unit():
     320            self._minmaxx = None
     321            self._minmaxy = None
     322            self._abcunit = self._data.get_unit()
     323            self._datamask = None
     324        if refresh: self.plot()
     325       
     326
     327    def set_mode(self, stacking=None, panelling=None, refresh=True):
    269328        """
    270329        Set the plots look and feel, i.e. what you want to see on the plot.
     
    274333            panelling:    tell the plotter which variable to plot
    275334                          across multiple panels (default 'scan'
     335            refresh:      True (default) or False. If True, the plot is
     336                          replotted based on the new parameter setting(s).
     337                          Otherwise,the parameter(s) are set without replotting.
    276338        Note:
    277339            Valid modes are:
     
    286348               not self.set_stacking(stacking):
    287349            if rcParams['verbose']:
    288                 print msg
     350                #print msg
     351                asaplog.push( msg )
     352                print_log( 'ERROR' )
    289353                return
    290354            else:
    291355                raise TypeError(msg)
    292         if self._data: self.plot(self._data)
     356        if refresh and self._data: self.plot(self._data)
    293357        return
    294358
     
    304368        return False
    305369
    306     def set_layout(self,rows=None,cols=None):
     370    def set_layout(self,rows=None,cols=None,refresh=True):
    307371        """
    308372        Set the multi-panel layout, i.e. how many rows and columns plots
     
    311375             rows:   The number of rows of plots
    312376             cols:   The number of columns of plots
     377             refresh:  True (default) or False. If True, the plot is
     378                       replotted based on the new parameter setting(s).
     379                       Otherwise,the parameter(s) are set without replotting.
    313380        Note:
    314381             If no argument is given, the potter reverts to its auto-plot
     
    317384        self._rows = rows
    318385        self._cols = cols
    319         if self._data: self.plot(self._data)
     386        if refresh and self._data: self.plot(self._data)
    320387        return
    321388
     
    331398        return False
    332399
    333     def set_range(self,xstart=None,xend=None,ystart=None,yend=None):
     400    def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True):
    334401        """
    335402        Set the range of interest on the abcissa of the plot
    336403        Parameters:
    337404            [x,y]start,[x,y]end:  The start and end points of the 'zoom' window
     405            refresh:  True (default) or False. If True, the plot is
     406                      replotted based on the new parameter setting(s).
     407                      Otherwise,the parameter(s) are set without replotting.
    338408        Note:
    339409            These become non-sensical when the unit changes.
     
    349419        else:
    350420            self._minmaxy = [ystart,yend]
    351         if self._data: self.plot(self._data)
     421        if refresh and self._data: self.plot(self._data)
    352422        return
    353423
    354     def set_legend(self, mp=None, fontsize = None, mode = 0):
     424    def set_legend(self, mp=None, fontsize = None, mode = 0, refresh=True):
    355425        """
    356426        Specify a mapping for the legend instead of using the default
     
    376446                        9: upper center
    377447                        10: center
     448            refresh:    True (default) or False. If True, the plot is
     449                        replotted based on the new parameter setting(s).
     450                        Otherwise,the parameter(s) are set without replotting.
    378451
    379452        Example:
     
    390463            from matplotlib import rc as rcp
    391464            rcp('legend', fontsize=fontsize)
    392         if self._data:
    393             self.plot(self._data)
     465        if refresh and self._data: self.plot(self._data)
    394466        return
    395467
    396     def set_title(self, title=None, fontsize=None):
     468    def set_title(self, title=None, fontsize=None, refresh=True):
    397469        """
    398470        Set the title of the plot. If multiple panels are plotted,
    399471        multiple titles have to be specified.
     472        Parameters:
     473            refresh:    True (default) or False. If True, the plot is
     474                        replotted based on the new parameter setting(s).
     475                        Otherwise,the parameter(s) are set without replotting.
    400476        Example:
    401477             # two panels are visible on the plotter
     
    406482            from matplotlib import rc as rcp
    407483            rcp('axes', titlesize=fontsize)
    408         if self._data: self.plot(self._data)
     484        if refresh and self._data: self.plot(self._data)
    409485        return
    410486
    411     def set_ordinate(self, ordinate=None, fontsize=None):
     487    def set_ordinate(self, ordinate=None, fontsize=None, refresh=True):
    412488        """
    413489        Set the y-axis label of the plot. If multiple panels are plotted,
     
    416492            ordinate:    a list of ordinate labels. None (default) let
    417493                         data determine the labels
     494            refresh:     True (default) or False. If True, the plot is
     495                         replotted based on the new parameter setting(s).
     496                         Otherwise,the parameter(s) are set without replotting.
    418497        Example:
    419498             # two panels are visible on the plotter
     
    425504            rcp('axes', labelsize=fontsize)
    426505            rcp('ytick', labelsize=fontsize)
    427         if self._data: self.plot(self._data)
     506        if refresh and self._data: self.plot(self._data)
    428507        return
    429508
    430     def set_abcissa(self, abcissa=None, fontsize=None):
     509    def set_abcissa(self, abcissa=None, fontsize=None, refresh=True):
    431510        """
    432511        Set the x-axis label of the plot. If multiple panels are plotted,
     
    435514            abcissa:     a list of abcissa labels. None (default) let
    436515                         data determine the labels
     516            refresh:     True (default) or False. If True, the plot is
     517                         replotted based on the new parameter setting(s).
     518                         Otherwise,the parameter(s) are set without replotting.
    437519        Example:
    438520             # two panels are visible on the plotter
     
    444526            rcp('axes', labelsize=fontsize)
    445527            rcp('xtick', labelsize=fontsize)
    446         if self._data: self.plot(self._data)
     528        if refresh and self._data: self.plot(self._data)
    447529        return
    448530
    449     def set_colors(self, colmap):
     531    def set_colors(self, colmap, refresh=True):
    450532        """
    451533        Set the colours to be used. The plotter will cycle through
     
    453535        Parameters:
    454536            colmap:     a list of colour names
     537            refresh:    True (default) or False. If True, the plot is
     538                        replotted based on the new parameter setting(s).
     539                        Otherwise,the parameter(s) are set without replotting.
    455540        Example:
    456541             plotter.set_colors("red green blue")
     
    462547            colmap = colmap.split()
    463548        self._plotter.palette(0, colormap=colmap)
    464         if self._data: self.plot(self._data)
     549        if refresh and self._data: self.plot(self._data)
    465550
    466551    # alias for english speakers
    467552    set_colours = set_colors
    468553
    469     def set_histogram(self, hist=True, linewidth=None):
     554    def set_histogram(self, hist=True, linewidth=None, refresh=True):
    470555        """
    471556        Enable/Disable histogram-like plotting.
     
    474559                         is taken from the .asaprc setting
    475560                         plotter.histogram
     561            refresh:     True (default) or False. If True, the plot is
     562                         replotted based on the new parameter setting(s).
     563                         Otherwise,the parameter(s) are set without replotting.
    476564        """
    477565        self._hist = hist
     
    479567            from matplotlib import rc as rcp
    480568            rcp('lines', linewidth=linewidth)
    481         if self._data: self.plot(self._data)
    482 
    483     def set_linestyles(self, linestyles=None, linewidth=None):
     569        if refresh and self._data: self.plot(self._data)
     570
     571    def set_linestyles(self, linestyles=None, linewidth=None, refresh=True):
    484572        """
    485573        Set the linestyles to be used. The plotter will cycle through
     
    491579                             'dashdotdot' and 'dashdashdot' are
    492580                             possible
    493 
     581            refresh:         True (default) or False. If True, the plot is
     582                             replotted based on the new parameter setting(s).
     583                             Otherwise,the parameter(s) are set without replotting.
    494584        Example:
    495585             plotter.set_colors("black")
     
    505595            from matplotlib import rc as rcp
    506596            rcp('lines', linewidth=linewidth)
    507         if self._data: self.plot(self._data)
    508 
    509     def set_font(self, **kwargs):
     597        if refresh and self._data: self.plot(self._data)
     598
     599    def set_font(self, refresh=True,**kwargs):
    510600        """
    511601        Set font properties.
     
    516606            size:      the 'general' font size, individual elements can be adjusted
    517607                       seperately
     608            refresh:   True (default) or False. If True, the plot is
     609                       replotted based on the new parameter setting(s).
     610                       Otherwise,the parameter(s) are set without replotting.
    518611        """
    519612        from matplotlib import rc as rcp
     
    523616                fdict[k] = v
    524617        self._fp = FontProperties(**fdict)
    525         if self._data:
    526             self.plot()
     618        if refresh and self._data: self.plot(self._data)
     619
     620    def set_panellayout(self,layout=[],refresh=True):
     621        """
     622        Set the layout of subplots.
     623        Parameters:
     624            layout:   a list of subplots layout in figure coordinate (0-1),
     625                      i.e., fraction of the figure width or height.
     626                      The order of elements should be:
     627                      [left, bottom, right, top, horizontal space btw panels,
     628                      vertical space btw panels].
     629            refresh:  True (default) or False. If True, the plot is
     630                      replotted based on the new parameter setting(s).
     631                      Otherwise,the parameter(s) are set without replotting.
     632        Note
     633        * When layout is not specified, the values are reset to the defaults
     634          of matplotlib.
     635        * If any element is set to be None, the current value is adopted.
     636        """
     637        if layout == []: self._panellayout=self._reset_panellayout()
     638        else:
     639            self._panellayout=[None]*6
     640            self._panellayout[0:len(layout)]=layout
     641        #print "panel layout set to ",self._panellayout
     642        if refresh and self._data: self.plot(self._data)
     643
     644    def _reset_panellayout(self):
     645        ks=map(lambda x: 'figure.subplot.'+x,
     646               ['left','bottom','right','top','hspace','wspace'])
     647        return map(matplotlib.rcParams.get,ks)
    527648
    528649    def plot_lines(self, linecat=None, doppler=0.0, deltachan=10, rotate=90.0,
     
    622743
    623744
    624     def set_mask(self, mask=None, selection=None):
     745    def set_mask(self, mask=None, selection=None, refresh=True):
    625746        """
    626747        Set a plotting mask for a specific polarization.
     
    629750             mask:           a mask from scantable.create_mask
    630751             selection:      the spectra to apply the mask to.
     752             refresh:        True (default) or False. If True, the plot is
     753                             replotted based on the new parameter setting(s).
     754                             Otherwise,the parameter(s) are set without replotting.
    631755        Example:
    632756             select = selector()
     
    637761            msg = "Can only set mask after a first call to plot()"
    638762            if rcParams['verbose']:
    639                 print msg
     763                #print msg
     764                asaplog.push( msg )
     765                print_log( 'ERROR' )
    640766                return
    641767            else:
     
    657783        else:
    658784            self._maskselection = None
    659         self.plot(self._data)
     785        if refresh: self.plot(self._data)
    660786
    661787    def _slice_indeces(self, data):
     
    671797            inc = -1
    672798        # find min index
    673         while start > 0 and data[start] < mn:
    674             start+= inc
     799        #while start > 0 and data[start] < mn:
     800        #    start+= inc
     801        minind=start
     802        for ind in xrange(start,end+inc,inc):
     803            if data[ind] > mn: break
     804            minind=ind
    675805        # find max index
    676         while end > 0 and data[end] > mx:
    677             end-=inc
    678         if end > 0: end +=1
     806        #while end > 0 and data[end] > mx:
     807        #    end-=inc
     808        #if end > 0: end +=1
     809        maxind=end
     810        for ind in xrange(end,start-inc,-inc):
     811            if data[ind] < mx: break
     812            maxind=ind
     813        start=minind
     814        end=maxind
    679815        if start > end:
    680             return end,start
    681         return start,end
     816            return end,start+1
     817        elif start < end:
     818            return start,end+1
     819        else:
     820            return start,end
    682821
    683822    def _reset(self):
     
    708847        maxpanel, maxstack = 16,16
    709848        if n > maxpanel or nstack > maxstack:
    710             from asap import asaplog
    711849            maxn = 0
    712850            if nstack > maxstack: maxn = maxstack
     
    715853                  "Selecting first %d selections..." % (maxn, maxn)
    716854            asaplog.push(msg)
    717             print_log()
     855            print_log('WARN')
    718856            n = min(n,maxpanel)
    719857            nstack = min(nstack,maxstack)
    720858        if n > 1:
    721859            ganged = rcParams['plotter.ganged']
     860            if self._panelling == 'i':
     861                ganged = False
    722862            if self._rows and self._cols:
    723863                n = min(n,self._rows*self._cols)
    724864                self._plotter.set_panels(rows=self._rows,cols=self._cols,
    725                                          nplots=n,ganged=ganged)
     865#                                         nplots=n,ganged=ganged)
     866                                         nplots=n,layout=self._panellayout,ganged=ganged)
    726867            else:
    727                 self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged)
     868#                self._plotter.set_panels(rows=n,cols=0,nplots=n,ganged=ganged)
     869                self._plotter.set_panels(rows=n,cols=0,nplots=n,layout=self._panellayout,ganged=ganged)
    728870        else:
    729             self._plotter.set_panels()
     871#            self._plotter.set_panels()
     872            self._plotter.set_panels(layout=self._panellayout)
    730873        r=0
    731874        nr = scan.nrow()
     
    799942                    ylim= self._minmaxy or [ma.minimum(y),ma.maximum(y)]
    800943                    allylim += ylim
     944                else:
     945                    xlim = self._minmaxx or []
     946                    allxlim += xlim
     947                    ylim= self._minmaxy or []
     948                    allylim += ylim
    801949                stackcount += 1
    802950                # last in colour stack -> autoscale x
    803                 if stackcount == nstack:
     951                if stackcount == nstack and len(allxlim) > 0:
    804952                    allxlim.sort()
    805                     self._plotter.axes.set_xlim([allxlim[0],allxlim[-1]])
     953                    self._plotter.subplots[panelcount-1]['axes'].set_xlim([allxlim[0],allxlim[-1]])
    806954                    # clear
    807955                    allxlim =[]
     
    813961            if (panelcount == n) and (stackcount == nstack):
    814962                # last panel -> autoscale y if ganged
    815                 if rcParams['plotter.ganged']:
     963                if rcParams['plotter.ganged'] and len(allylim) > 0:
    816964                    allylim.sort()
    817965                    self._plotter.set_limits(ylim=[allylim[0],allylim[-1]])
     
    820968        #reset the selector to the scantable's original
    821969        scan.set_selection(savesel)
    822         if self._fp is not None:
     970       
     971        #temporary switch-off for older matplotlib
     972        #if self._fp is not None:
     973        if self._fp is not None and getattr(self._plotter.figure,'findobj',False):
    823974            for o in self._plotter.figure.findobj(Text):
    824975                o.set_fontproperties(self._fp)
    825976
    826 
    827977    def set_selection(self, selection=None, refresh=True, **kw):
     978        """
     979        Parameters:
     980            selection:  a selector object (default unset the selection)
     981            refresh:    True (default) or False. If True, the plot is
     982                        replotted based on the new parameter setting(s).
     983                        Otherwise,the parameter(s) are set without replotting.
     984        """
    828985        if selection is None:
    829986            # reset
     
    8451002        order = [d0[self._panelling],d0[self._stacking]]
    8461003        self._selection.set_order(order)
    847         if self._data and refresh: self.plot(self._data)
     1004        if refresh and self._data: self.plot(self._data)
    8481005
    8491006    def _get_selected_n(self, scan):
     
    8681025            poleval = scan._getpollabel(scan.getpol(row),scan.poltype())
    8691026        d = {'b': "Beam "+str(scan.getbeam(row)),
    870              's': scan._getsourcename(row),
     1027             #'s': scan._getsourcename(row),
     1028             's': "Scan "+str(scan.getscan(row))+\
     1029                  " ("+str(scan._getsourcename(row))+")",
    8711030             'i': "IF"+str(scan.getif(row)),
    8721031             'p': poleval,
     
    8741033        return userlabel or d[mode]
    8751034
    876     def plotazel(self):
     1035    def plotazel(self, scan=None, outfile=None):
     1036    #def plotazel(self):
    8771037        """
    8781038        plot azimuth and elevation versus time of a scantable
     
    8831043        from matplotlib.ticker import MultipleLocator
    8841044        from numpy import array, pi
     1045        self._data = scan
     1046        self._outfile = outfile
    8851047        dates = self._data.get_time(asdatetime=True)
    8861048        t = PL.date2num(dates)
     
    8891051        PL.ioff()
    8901052        PL.clf()
     1053        # Adjust subplot layouts
     1054        if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
     1055        lef, bot, rig, top, wsp, hsp = self._panellayout
     1056        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     1057                                 wspace=wsp,hspace=hsp)
     1058       
    8911059        tdel = max(t) - min(t)
    8921060        ax = PL.subplot(2,1,1)
     
    9101078
    9111079        PL.title(dstr)
    912         PL.plot_date(t,el,'b,', tz=tz)
     1080        if tdel == 0.0:
     1081            th = (t - PL.floor(t))*24.0
     1082            PL.plot(th,el,'o',markersize=2, markerfacecolor='b', markeredgecolor='b')
     1083        else:
     1084            PL.plot_date(t,el,'o', markersize=2, markerfacecolor='b', markeredgecolor='b',tz=tz)
     1085            #ax.grid(True)
     1086            ax.xaxis.set_major_formatter(timefmt)
     1087            ax.xaxis.set_major_locator(majloc)
     1088            ax.xaxis.set_minor_locator(minloc)
    9131089        ax.yaxis.grid(True)
    914 
     1090        yloc = MultipleLocator(30)
     1091        ax.set_ylim(0,90)
     1092        ax.yaxis.set_major_locator(yloc)
    9151093        if tdel > 1.0:
    9161094            labels = ax.get_xticklabels()
    9171095        #    PL.setp(labels, fontsize=10, rotation=45)
    9181096            PL.setp(labels, fontsize=10)
     1097
    9191098        # Az plot
    9201099        az = array(self._data.get_azimuth())*180./pi
     
    9231102                if az[irow] < 0: az[irow] += 360.0
    9241103
    925         ax2 = ax.figure.add_subplot(2,1,2, sharex=ax)
    926         ax2.set_xlabel('Time (UT)')
    927         ax2.set_ylabel('Az [deg.]')
    928         ax2.plot_date(t,az,'b,', tz=tz)
     1104        ax2 = PL.subplot(2,1,2)
     1105        #PL.xlabel('Time (UT [hour])')
     1106        PL.ylabel('Az [deg.]')
     1107        if tdel == 0.0:
     1108            PL.plot(th,az,'o',markersize=2, markeredgecolor='b',markerfacecolor='b')
     1109        else:
     1110            PL.plot_date(t,az,'o', markersize=2,markeredgecolor='b',markerfacecolor='b',tz=tz)
     1111            ax2.xaxis.set_major_formatter(timefmt)
     1112            ax2.xaxis.set_major_locator(majloc)
     1113            ax2.xaxis.set_minor_locator(minloc)
     1114        #ax2.grid(True)
     1115        ax2.set_ylim(0,360)
    9291116        ax2.yaxis.grid(True)
    930         # set this last as x axis is shared
    931         ax.xaxis.set_major_formatter(timefmt)
    932         ax.xaxis.set_major_locator(majloc)
    933         ax.xaxis.set_minor_locator(minloc)
     1117        #hfmt = DateFormatter('%H')
     1118        #hloc = HourLocator()
     1119        yloc = MultipleLocator(60)
     1120        ax2.yaxis.set_major_locator(yloc)
     1121        if tdel > 1.0:
     1122            labels = ax2.get_xticklabels()
     1123            PL.setp(labels, fontsize=10)
     1124            PL.xlabel('Time (UT [day])')
     1125        else:
     1126            PL.xlabel('Time (UT [hour])')
     1127
    9341128        PL.ion()
    9351129        PL.draw()
    936 
    937     def plotpointing(self):
     1130        if (self._outfile is not None):
     1131           PL.savefig(self._outfile)
     1132
     1133    def plotpointing(self, scan=None, outfile=None):
     1134    #def plotpointing(self):
    9381135        """
    9391136        plot telescope pointings
    9401137        """
    9411138        from matplotlib import pylab as PL
    942         from numpy import array
     1139        from numpy import array, pi
     1140        self._data = scan
     1141        self._outfile = outfile
    9431142        dir = array(self._data.get_directionval()).transpose()
    9441143        ra = dir[0]*180./pi
    9451144        dec = dir[1]*180./pi
    9461145        PL.cla()
    947         PL.ioff()
     1146        #PL.ioff()
    9481147        PL.clf()
    949         ax = PL.axes([0.1,0.1,0.8,0.8])
    950         ax = PL.axes([0.1,0.1,0.8,0.8])
     1148        # Adjust subplot layouts
     1149        if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
     1150        lef, bot, rig, top, wsp, hsp = self._panellayout
     1151        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     1152                                 wspace=wsp,hspace=hsp)
     1153        ax = PL.gca()
     1154        #ax = PL.axes([0.1,0.1,0.8,0.8])
     1155        #ax = PL.axes([0.1,0.1,0.8,0.8])
    9511156        ax.set_aspect('equal')
    9521157        PL.plot(ra, dec, 'b,')
     
    9561161        [xmin,xmax,ymin,ymax] = PL.axis()
    9571162        PL.axis([xmax,xmin,ymin,ymax])
    958         PL.ion()
     1163        #PL.ion()
    9591164        PL.draw()
     1165        if (self._outfile is not None):
     1166           PL.savefig(self._outfile)
     1167
     1168    # plot total power data
     1169    # plotting in time is not yet implemented..
     1170    def plottp(self, scan=None, outfile=None):
     1171        if self._plotter.is_dead:
     1172            if hasattr(self._plotter.figmgr,'casabar'):
     1173                del self._plotter.figmgr.casabar
     1174            self._plotter = self._newplotter()
     1175            self._plotter.figmgr.casabar=self._newcasabar()
     1176        self._plotter.hold()
     1177        self._plotter.clear()
     1178        from asap import scantable
     1179        if not self._data and not scan:
     1180            msg = "Input is not a scantable"
     1181            if rcParams['verbose']:
     1182                #print msg
     1183                asaplog.push( msg )
     1184                print_log( 'ERROR' )
     1185                return
     1186            raise TypeError(msg)
     1187        if isinstance(scan, scantable):
     1188            if self._data is not None:
     1189                if scan != self._data:
     1190                    self._data = scan
     1191                    # reset
     1192                    self._reset()
     1193            else:
     1194                self._data = scan
     1195                self._reset()
     1196        # ranges become invalid when abcissa changes?
     1197        #if self._abcunit and self._abcunit != self._data.get_unit():
     1198        #    self._minmaxx = None
     1199        #    self._minmaxy = None
     1200        #    self._abcunit = self._data.get_unit()
     1201        #    self._datamask = None
     1202
     1203        # Adjust subplot layouts
     1204        if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
     1205        lef, bot, rig, top, wsp, hsp = self._panellayout
     1206        self._plotter.figure.subplots_adjust(
     1207            left=lef,bottom=bot,right=rig,top=top,wspace=wsp,hspace=hsp)
     1208        if self._plotter.figmgr.casabar: self._plotter.figmgr.casabar.disable_button()
     1209        self._plottp(self._data)
     1210        if self._minmaxy is not None:
     1211            self._plotter.set_limits(ylim=self._minmaxy)
     1212        self._plotter.release()
     1213        self._plotter.tidy()
     1214        self._plotter.show(hardrefresh=False)
     1215        print_log()
     1216        return
     1217
     1218    def _plottp(self,scan):
     1219        """
     1220        private method for plotting total power data
     1221        """
     1222        from matplotlib.numerix import ma, array, arange, logical_not
     1223        r=0
     1224        nr = scan.nrow()
     1225        a0,b0 = -1,-1
     1226        allxlim = []
     1227        allylim = []
     1228        y=[]
     1229        self._plotter.set_panels()
     1230        self._plotter.palette(0)
     1231        #title
     1232        #xlab = self._abcissa and self._abcissa[panelcount] \
     1233        #       or scan._getabcissalabel()
     1234        #ylab = self._ordinate and self._ordinate[panelcount] \
     1235        #       or scan._get_ordinate_label()
     1236        xlab = self._abcissa or 'row number' #or Time
     1237        ylab = self._ordinate or scan._get_ordinate_label()
     1238        self._plotter.set_axes('xlabel',xlab)
     1239        self._plotter.set_axes('ylabel',ylab)
     1240        lbl = self._get_label(scan, r, 's', self._title)
     1241        if isinstance(lbl, list) or isinstance(lbl, tuple):
     1242        #    if 0 <= panelcount < len(lbl):
     1243        #        lbl = lbl[panelcount]
     1244        #    else:
     1245                # get default label
     1246             lbl = self._get_label(scan, r, self._panelling, None)
     1247        self._plotter.set_axes('title',lbl)
     1248        y=array(scan._get_column(scan._getspectrum,-1))
     1249        m = array(scan._get_column(scan._getmask,-1))
     1250        y = ma.masked_array(y,mask=logical_not(array(m,copy=False)))
     1251        x = arange(len(y))
     1252        # try to handle spectral data somewhat...
     1253        l,m = y.shape
     1254        if m > 1:
     1255            y=y.mean(axis=1)
     1256        plotit = self._plotter.plot
     1257        llbl = self._get_label(scan, r, self._stacking, None)
     1258        self._plotter.set_line(label=llbl)
     1259        if len(x) > 0:
     1260            plotit(x,y)
     1261
     1262
     1263    # forwards to matplotlib.Figure.text
     1264    def figtext(self, *args, **kwargs):
     1265        """
     1266        Add text to figure at location x,y (relative 0-1 coords).
     1267        This method forwards *args and **kwargs to a Matplotlib method,
     1268        matplotlib.Figure.text.
     1269        See the method help for detailed information.
     1270        """
     1271        self._plotter.text(*args, **kwargs)
     1272    # end matplotlib.Figure.text forwarding function
     1273
     1274
     1275    # printing header information
     1276    def print_header(self, plot=True, fontsize=9, logger=False, selstr='', extrastr=''):
     1277        """
     1278        print data (scantable) header on the plot and/or logger.
     1279        Parameters:
     1280            plot:      whether or not print header info on the plot.
     1281            fontsize:  header font size (valid only plot=True)
     1282            autoscale: whether or not autoscale the plot (valid only plot=True)
     1283            logger:    whether or not print header info on the logger.
     1284            selstr:    additional selection string (not verified)
     1285            extrastr:  additional string to print (not verified)
     1286        """
     1287        if not plot and not logger: return
     1288        if not self._data: raise RuntimeError("No scantable has been set yet.")
     1289        # Now header will be printed on plot and/or logger.
     1290        # Get header information and format it.
     1291        ssum=self._data.__str__()
     1292        # Print Observation header to the upper-left corner of plot
     1293        if plot:
     1294            headstr=[ssum[ssum.find('Observer:'):ssum.find('Flux Unit:')]]
     1295            headstr.append(ssum[ssum.find('Beams:'):ssum.find('Observer:')]
     1296                         +ssum[ssum.find('Rest Freqs:'):ssum.find('Abcissa:')])
     1297            if extrastr != '': headstr[0]=extrastr+'\n'+headstr[0]
     1298            #headstr[1]='Data File:     '+(filestr or 'unknown')+'\n'+headstr[1]
     1299            ssel='***Selections***\n'+(selstr+self._data.get_selection().__str__() or 'none')
     1300            headstr.append(ssel)
     1301            nstcol=len(headstr)
     1302           
     1303            self._plotter.hold()
     1304            for i in range(nstcol):
     1305                self._plotter.figure.text(0.03+float(i)/nstcol,0.98,
     1306                             headstr[i],
     1307                             horizontalalignment='left',
     1308                             verticalalignment='top',
     1309                             fontsize=fontsize)
     1310            import time
     1311            self._plotter.figure.text(0.99,0.0,
     1312                            time.strftime("%a %d %b %Y  %H:%M:%S %Z"),
     1313                            horizontalalignment='right',
     1314                            verticalalignment='bottom',fontsize=8)
     1315            self._plotter.release()
     1316            del headstr, ssel
     1317        if logger:
     1318            asaplog.push("----------------\n  Plot Summary\n----------------")
     1319            asaplog.push(extrastr)
     1320            asaplog.push(ssum[ssum.find('Beams:'):])
     1321            print_log()
     1322        del ssum
     1323
     1324
  • branches/mergetest/python/asapreader.py

    r1695 r1779  
    11from asap._asap import stfiller
    2 from asap import print_log_dec
     2from asap import print_log, print_log_dec
    33
    44class reader(stfiller):
     
    2525               rpfits ONLY.
    2626    """
    27     @print_log_dec
     27    #@print_log_dec
    2828    def __init__(self, filename, unit=None, theif=None, thebeam=None):
    2929        self.unit = unit
     
    4646        filename = expandvars(filename)
    4747        stfiller.__init__(self, filename, theif, thebeam)
     48        print_log()
    4849
    49     @print_log_dec
     50    #@print_log_dec
    5051    def read(self):
    5152        """
     
    5960        if self.unit is not None:
    6061            tbl.set_fluxunit(self.unit)
     62        print_log()
    6163        return scantable(tbl)
    6264
  • branches/mergetest/python/linecatalog.py

    r1534 r1779  
    88from asap._asap import linecatalog as lcbase
    99from asap import rcParams
     10from asap import asaplog
    1011import os
    1112
     
    3031            msg = "File '%s' not found" % fpath
    3132            if rcParams['verbose']:
    32                 print msg
     33                #print msg
     34                asaplog.push( msg )
     35                print_log( 'ERROR' )
    3336                return
    3437            else:
     
    97100                msg = "File %s exists." % name
    98101                if rcParams['verbose']:
    99                     print msg
     102                    #print msg
     103                    asaplog.push( msg )
     104                    print_log( 'ERROR' )
    100105                    return
    101106                else:
  • branches/mergetest/python/scantable.py

    r1731 r1779  
    3535        The ASAP container for scans
    3636    """
    37     @print_log_dec
    38     def __init__(self, filename, average=None, unit=None, parallactify=None):
     37
     38    #@print_log_dec
     39    def __init__(self, filename, average=None, unit=None, getpt=None, antenna=None, parallactify=None):
    3940        """
    4041        Create a scantable from a saved one or make a reference
     
    5455                         (input rpfits/sdfits/ms) or replaces the value
    5556                         in existing scantables
     57            getpt:       for MeasurementSet input data only:
     58                         If True, all pointing data are filled.
     59                         The deafult is False, which makes time to load
     60                         the MS data faster in some cases.
     61            antenna:     Antenna selection. integer (id) or string (name
     62                         or id).
    5663            parallactify: Indcicate that the data had been parallatified.
    5764                          Default is taken form rc file.
     
    5966        if average is None:
    6067            average = rcParams['scantable.autoaverage']
     68        if getpt is None:
     69            getpt = True
     70        if antenna is None:
     71            antenna = ''
     72        elif type(antenna) == int:
     73            antenna = '%s'%antenna
     74        elif type(antenna) == list:
     75            tmpstr = ''
     76            for i in range( len(antenna) ):
     77                if type(antenna[i]) == int:
     78                    tmpstr = tmpstr + ('%s,'%(antenna[i]))
     79                elif type(antenna[i]) == str:
     80                    tmpstr=tmpstr+antenna[i]+','
     81                else:
     82                    asaplog.push('Bad antenna selection.')
     83                    print_log('ERROR')
     84                    return
     85            antenna = tmpstr.rstrip(',')
    6186        parallactify = parallactify or rcParams['scantable.parallactify']
    6287        varlist = vars()
    6388        from asap._asap import stmath
    64         self._math = stmath()
     89        self._math = stmath( rcParams['insitu'] )
    6590        if isinstance(filename, Scantable):
    6691            Scantable.__init__(self, filename)
     
    7398                    if rcParams['verbose']:
    7499                        asaplog.push(s)
     100                        print_log('ERROR')
    75101                        return
    76102                    raise IOError(s)
     
    80106                    if unit is not None:
    81107                        self.set_fluxunit(unit)
    82                     self.set_freqframe(rcParams['scantable.freqframe'])
     108                    # do not reset to the default freqframe
     109                    #self.set_freqframe(rcParams['scantable.freqframe'])
     110                elif os.path.isdir(filename) \
     111                         and not os.path.exists(filename+'/table.f1'):
     112                    msg = "The given file '%s'is not a valid " \
     113                          "asap table." % (filename)
     114                    if rcParams['verbose']:
     115                        #print msg
     116                        asaplog.push( msg )
     117                        print_log( 'ERROR' )
     118                        return
     119                    else:
     120                        raise IOError(msg)
    83121                else:
    84                     self._fill([filename], unit, average)
     122                    self._fill([filename], unit, average, getpt, antenna)
    85123            elif (isinstance(filename, list) or isinstance(filename, tuple)) \
    86124                  and isinstance(filename[-1], str):
    87                 self._fill(filename, unit, average)
     125                self._fill(filename, unit, average, getpt, antenna)
    88126        self.parallactify(parallactify)
    89127        self._add_history("scantable", varlist)
    90 
    91     @print_log_dec
     128        print_log()
     129
     130    #@print_log_dec
    92131    def save(self, name=None, format=None, overwrite=False):
    93132        """
     
    126165                msg = "File %s exists." % name
    127166                if rcParams['verbose']:
    128                     print msg
     167                    #print msg
     168                    asaplog.push( msg )
     169                    print_log( 'ERROR' )
    129170                    return
    130171                else:
     
    137178            writer = stw(format2)
    138179            writer.write(self, name)
     180        print_log()
    139181        return
    140182
     
    164206        if not _is_valid(scanid):
    165207            if rcParams['verbose']:
    166                 print "Please specify a scanno to drop from the scantable"
     208                #print "Please specify a scanno to drop from the scantable"
     209                asaplog.push( 'Please specify a scanno to drop from the scantable' )
     210                print_log( 'ERROR' )
    167211                return
    168212            else:
     
    176220        except ValueError:
    177221            if rcParams['verbose']:
    178                 print "Couldn't find any match."
     222                #print "Couldn't find any match."
     223                print_log()
     224                asaplog.push( "Couldn't find any match." )
     225                print_log( 'ERROR' )
    179226                return
    180227            else: raise
     
    184231        except RuntimeError:
    185232            if rcParams['verbose']:
    186                 print "Couldn't find any match."
     233                #print "Couldn't find any match."
     234                print_log()
     235                asaplog.push( "Couldn't find any match." )
     236                print_log( 'ERROR' )
    187237            else:
    188238                raise
     
    215265        if scanid is None:
    216266            if rcParams['verbose']:
    217                 print "Please specify a scan no or name to " \
    218                       "retrieve from the scantable"
     267                #print "Please specify a scan no or name to " \
     268                #      "retrieve from the scantable"
     269                asaplog.push( 'Please specify a scan no or name to retrieve from the scantable' )
     270                print_log( 'ERROR' )
    219271                return
    220272            else:
     
    236288                msg = "Illegal scanid type, use 'int' or 'list' if ints."
    237289                if rcParams['verbose']:
    238                     print msg
     290                    #print msg
     291                    asaplog.push( msg )
     292                    print_log( 'ERROR' )
    239293                else:
    240294                    raise TypeError(msg)
    241295        except RuntimeError:
    242             if rcParams['verbose']: print "Couldn't find any match."
     296            if rcParams['verbose']:
     297                #print "Couldn't find any match."
     298                print_log()
     299                asaplog.push( "Couldn't find any match." )
     300                print_log( 'ERROR' )
    243301            else: raise
    244302
     
    266324                msg = "Illegal file name '%s'." % (filename)
    267325                if rcParams['verbose']:
    268                     print msg
     326                    #print msg
     327                    asaplog.push( msg )
     328                    print_log( 'ERROR' )
    269329                else:
    270330                    raise IOError(msg)
     
    367427        self._setselection(selection)
    368428
    369     def stats(self, stat='stddev', mask=None):
     429    def get_row(self, row=0, insitu=None):
     430        """
     431        Select a row in the scantable.
     432        Return a scantable with single row.
     433        Parameters:
     434            row: row no of integration, default is 0.
     435            insitu: if False a new scantable is returned.
     436                    Otherwise, the scaling is done in-situ
     437                    The default is taken from .asaprc (False)
     438        """
     439        if insitu is None: insitu = rcParams['insitu']
     440        if not insitu:
     441            workscan = self.copy()
     442        else:
     443            workscan = self
     444        # Select a row
     445        sel=selector()
     446        sel.set_scans([workscan.getscan(row)])
     447        sel.set_cycles([workscan.getcycle(row)])
     448        sel.set_beams([workscan.getbeam(row)])
     449        sel.set_ifs([workscan.getif(row)])
     450        sel.set_polarisations([workscan.getpol(row)])
     451        sel.set_name(workscan._getsourcename(row))
     452        workscan.set_selection(sel)
     453        if not workscan.nrow() == 1:
     454            msg = "Cloud not identify single row. %d rows selected."%(workscan.nrow())
     455            raise RuntimeError(msg)
     456        del sel
     457        if insitu:
     458            self._assign(workscan)
     459        else:
     460            return workscan
     461
     462    #def stats(self, stat='stddev', mask=None):
     463    def stats(self, stat='stddev', mask=None, form='3.3f'):
    370464        """
    371465        Determine the specified statistic of the current beam/if/pol
     
    373467        channels should be excluded.
    374468        Parameters:
    375             stat:    'min', 'max', 'sumsq', 'sum', 'mean'
    376                      'var', 'stddev', 'avdev', 'rms', 'median'
     469            stat:    'min', 'max', 'min_abc', 'max_abc', 'sumsq', 'sum',
     470                     'mean', 'var', 'stddev', 'avdev', 'rms', 'median'
    377471            mask:    an optional mask specifying where the statistic
    378472                     should be determined.
     473            form:    format string to print statistic values
    379474        Example:
    380475            scan.set_unit('channel')
     
    387482                             "number of channels. Please use setselection() "
    388483                             "to select individual IFs")
    389 
    390         statvals = self._math._stats(self, mask, stat)
    391         def cb(i):
    392             return statvals[i]
    393 
    394         return self._row_callback(cb, stat)
     484        rtnabc = False
     485        if stat.lower().endswith('_abc'): rtnabc = True
     486        getchan = False
     487        if stat.lower().startswith('min') or stat.lower().startswith('max'):
     488            chan = self._math._minmaxchan(self, mask, stat)
     489            getchan = True
     490            statvals = []
     491        if not rtnabc: statvals = self._math._stats(self, mask, stat)
     492
     493        #def cb(i):
     494        #    return statvals[i]
     495
     496        #return self._row_callback(cb, stat)
     497
     498        label=stat
     499        #callback=cb
     500        out = ""
     501        #outvec = []
     502        sep = '-'*50
     503        for i in range(self.nrow()):
     504            refstr = ''
     505            statunit= ''
     506            if getchan:
     507                qx, qy = self.chan2data(rowno=i, chan=chan[i])
     508                if rtnabc:
     509                    statvals.append(qx['value'])
     510                    refstr = ('(value: %'+form) % (qy['value'])+' ['+qy['unit']+'])'
     511                    statunit= '['+qx['unit']+']'
     512                else:
     513                    refstr = ('(@ %'+form) % (qx['value'])+' ['+qx['unit']+'])'
     514
     515            tm = self._gettime(i)
     516            src = self._getsourcename(i)
     517            out += 'Scan[%d] (%s) ' % (self.getscan(i), src)
     518            out += 'Time[%s]:\n' % (tm)
     519            if self.nbeam(-1) > 1:
     520                out +=  ' Beam[%d] ' % (self.getbeam(i))
     521            if self.nif(-1) > 1: out +=  ' IF[%d] ' % (self.getif(i))
     522            if self.npol(-1) > 1: out +=  ' Pol[%d] ' % (self.getpol(i))
     523            #outvec.append(callback(i))
     524            #out += ('= %'+form) % (outvec[i]) +'   '+refstr+'\n'
     525            out += ('= %'+form) % (statvals[i]) +'   '+refstr+'\n'
     526            out +=  sep+"\n"
     527
     528        if rcParams['verbose']:
     529            import os
     530            if os.environ.has_key( 'USER' ):
     531                usr=os.environ['USER']
     532            else:
     533                import commands
     534                usr=commands.getoutput( 'whoami' )
     535            tmpfile='/tmp/tmp_'+usr+'_casapy_asap_scantable_stats'
     536            f=open(tmpfile,'w')
     537            print >> f, sep
     538            print >> f, ' %s %s' % (label, statunit)
     539            print >> f, sep
     540            print >> f, out
     541            f.close()
     542            f=open(tmpfile,'r')
     543            x=f.readlines()
     544            f.close()
     545            blanc=''
     546            asaplog.push(blanc.join(x), False)
     547            #for xx in x:
     548            #    asaplog.push( xx, False )
     549            print_log()
     550        return statvals
     551
     552    def chan2data(self, rowno=0, chan=0):
     553        """
     554        Returns channel/frequency/velocity and spectral value
     555        at an arbitrary row and channel in the scantable.
     556        Parameters:
     557            rowno:   a row number in the scantable. Default is the
     558                     first row, i.e. rowno=0
     559            chan:    a channel in the scantable. Default is the first
     560                     channel, i.e. pos=0
     561        """
     562        if isinstance(rowno, int) and isinstance(chan, int):
     563            qx = {'unit': self.get_unit(),
     564                  'value': self._getabcissa(rowno)[chan]}
     565            qy = {'unit': self.get_fluxunit(),
     566                  'value': self._getspectrum(rowno)[chan]}
     567            return qx, qy
    395568
    396569    def stddev(self, mask=None):
     
    462635            out +=  sep+'\n'
    463636        if rcParams['verbose']:
    464             print sep
    465             print " %s" % (label)
    466             print sep
    467             print out
     637            asaplog.push(sep)
     638            asaplog.push(" %s" % (label))
     639            asaplog.push(sep)
     640            asaplog.push(out)
     641            print_log()
    468642        return outvec
    469643
     
    474648            return [callback(i) for i in range(self.nrow())]
    475649        else:
    476             if 0 <= row < self.nrow():
     650            if  0 <= row < self.nrow():
    477651                return callback(row)
    478652
     
    578752        return self._get_column(self._getdirectionvec, row)
    579753
    580     @print_log_dec
     754    #@print_log_dec
    581755    def set_unit(self, unit='channel'):
    582756        """
     
    594768        self._add_history("set_unit", varlist)
    595769
    596     @print_log_dec
     770    #@print_log_dec
    597771    def set_instrument(self, instr):
    598772        """
     
    604778        self._setInstrument(instr)
    605779        self._add_history("set_instument", vars())
    606 
    607     @print_log_dec
     780        print_log()
     781
     782    #@print_log_dec
    608783    def set_feedtype(self, feedtype):
    609784        """
     
    614789        self._setfeedtype(feedtype)
    615790        self._add_history("set_feedtype", vars())
    616 
    617     @print_log_dec
     791        print_log()
     792
     793    #@print_log_dec
    618794    def set_doppler(self, doppler='RADIO'):
    619795        """
     
    627803        self._setcoordinfo(inf)
    628804        self._add_history("set_doppler", vars())
    629 
    630     @print_log_dec
     805        print_log()
     806
     807    #@print_log_dec
    631808    def set_freqframe(self, frame=None):
    632809        """
     
    634811        Parameters:
    635812            frame:   an optional frame type, default 'LSRK'. Valid frames are:
    636                      'REST', 'TOPO', 'LSRD', 'LSRK', 'BARY',
     813                     'TOPO', 'LSRD', 'LSRK', 'BARY',
    637814                     'GEO', 'GALACTO', 'LGROUP', 'CMB'
    638815        Examples:
     
    641818        frame = frame or rcParams['scantable.freqframe']
    642819        varlist = vars()
    643         valid = ['REST', 'TOPO', 'LSRD', 'LSRK', 'BARY', \
     820        # "REST" is not implemented in casacore
     821        #valid = ['REST', 'TOPO', 'LSRD', 'LSRK', 'BARY', \
     822        #           'GEO', 'GALACTO', 'LGROUP', 'CMB']
     823        valid = ['TOPO', 'LSRD', 'LSRK', 'BARY', \
    644824                   'GEO', 'GALACTO', 'LGROUP', 'CMB']
    645825
     
    652832            msg  = "Please specify a valid freq type. Valid types are:\n", valid
    653833            if rcParams['verbose']:
    654                 print msg
     834                #print msg
     835                asaplog.push( msg )
     836                print_log( 'ERROR' )
    655837            else:
    656838                raise TypeError(msg)
     839        print_log()
    657840
    658841    def set_dirframe(self, frame=""):
     
    670853        except RuntimeError, msg:
    671854            if rcParams['verbose']:
    672                 print msg
     855                #print msg
     856                print_log()
     857                asaplog.push( str(msg) )
     858                print_log( 'ERROR' )
    673859            else:
    674860                raise
     
    698884        abc = self._getabcissa(rowno)
    699885        lbl = self._getabcissalabel(rowno)
     886        print_log()
    700887        return abc, lbl
    701888
    702     def flag(self, mask=None):
     889    def flag(self, mask=None, unflag=False):
    703890        """
    704891        Flag the selected data using an optional channel mask.
     
    706893            mask:   an optional channel mask, created with create_mask. Default
    707894                    (no mask) is all channels.
     895            unflag:    if True, unflag the data
    708896        """
    709897        varlist = vars()
    710898        mask = mask or []
    711899        try:
    712             self._flag(mask)
     900            self._flag(mask, unflag)
    713901        except RuntimeError, msg:
    714902            if rcParams['verbose']:
    715                 print msg
     903                #print msg
     904                print_log()
     905                asaplog.push( str(msg) )
     906                print_log( 'ERROR' )
    716907                return
    717908            else: raise
    718909        self._add_history("flag", varlist)
    719910
    720     @print_log_dec
     911    def flag_row(self, rows=[], unflag=False):
     912        """
     913        Flag the selected data in row-based manner.
     914        Parameters:
     915            rows:   list of row numbers to be flagged. Default is no row (must be explicitly specified to execute row-based flagging).
     916            unflag: if True, unflag the data.
     917        """
     918        varlist = vars()
     919        try:
     920            self._flag_row(rows, unflag)
     921        except RuntimeError, msg:
     922            if rcParams['verbose']:
     923                print_log()
     924                asaplog.push( str(msg) )
     925                print_log('ERROR')
     926                return
     927            else: raise
     928        self._add_history("flag_row", varlist)
     929       
     930    def clip(self, uthres=None, dthres=None, clipoutside=True, unflag=False):
     931        """
     932        Flag the selected data outside a specified range (in channel-base)
     933        Parameters:
     934            uthres:      upper threshold.
     935            dthres:      lower threshold
     936            clipoutside: True for flagging data outside the range [dthres:uthres].
     937                         False for glagging data inside the range.
     938            unflag     : if True, unflag the data.
     939        """
     940        varlist = vars()
     941        try:
     942            self._clip(uthres, dthres, clipoutside, unflag)
     943        except RuntimeError, msg:
     944            if rcParams['verbose']:
     945                print_log()
     946                asaplog.push(str(msg))
     947                print_log('ERROR')
     948                return
     949            else: raise
     950        self._add_history("clip", varlist)
     951
     952    #@print_log_dec
    721953    def lag_flag(self, start, end, unit="MHz", insitu=None):
     954    #def lag_flag(self, frequency, width=0.0, unit="GHz", insitu=None):
    722955        """
    723956        Flag the data in 'lag' space by providing a frequency to remove.
     
    748981        except RuntimeError, msg:
    749982            if rcParams['verbose']:
    750                 print msg
     983                #print msg
     984                print_log()
     985                asaplog.push( str(msg) )
     986                print_log( 'ERROR' )
    751987                return
    752988            else: raise
    753989        s._add_history("lag_flag", varlist)
     990        print_log()
    754991        if insitu:
    755992            self._assign(s)
     
    757994            return s
    758995
    759     @print_log_dec
     996    #@print_log_dec
    760997    def create_mask(self, *args, **kwargs):
    761998        """
     
    8191056            if kwargs.get('invert'):
    8201057                msk = mask_not(msk)
     1058        print_log()
    8211059        return msk
    8221060
    823     def get_restfreqs(self):
     1061    def get_masklist(self, mask=None, row=0):
     1062        """
     1063        Compute and return a list of mask windows, [min, max].
     1064        Parameters:
     1065            mask:       channel mask, created with create_mask.
     1066            row:        calcutate the masklist using the specified row
     1067                        for unit conversions, default is row=0
     1068                        only necessary if frequency varies over rows.
     1069        Returns:
     1070            [min, max], [min2, max2], ...
     1071                Pairs of start/end points (inclusive)specifying
     1072                the masked regions
     1073        """
     1074        if not (isinstance(mask,list) or isinstance(mask, tuple)):
     1075            raise TypeError("The mask should be list or tuple.")
     1076        if len(mask) < 2:
     1077            raise TypeError("The mask elements should be > 1")
     1078        if self.nchan() != len(mask):
     1079            msg = "Number of channels in scantable != number of mask elements"
     1080            raise TypeError(msg)
     1081        data = self._getabcissa(row)
     1082        u = self._getcoordinfo()[0]
     1083        if rcParams['verbose']:
     1084            if u == "": u = "channel"
     1085            msg = "The current mask window unit is %s" % u
     1086            i = self._check_ifs()
     1087            if not i:
     1088                msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
     1089            asaplog.push(msg)
     1090        masklist=[]
     1091        ist, ien = None, None
     1092        ist, ien=self.get_mask_indices(mask)
     1093        if ist is not None and ien is not None:
     1094            for i in xrange(len(ist)):
     1095                range=[data[ist[i]],data[ien[i]]]
     1096                range.sort()
     1097                masklist.append([range[0],range[1]])
     1098        return masklist
     1099
     1100    def get_mask_indices(self, mask=None):
     1101        """
     1102        Compute and Return lists of mask start indices and mask end indices.
     1103         Parameters:
     1104            mask:       channel mask, created with create_mask.
     1105        Returns:
     1106            List of mask start indices and that of mask end indices,
     1107            i.e., [istart1,istart2,....], [iend1,iend2,....].
     1108        """
     1109        if not (isinstance(mask,list) or isinstance(mask, tuple)):
     1110            raise TypeError("The mask should be list or tuple.")
     1111        if len(mask) < 2:
     1112            raise TypeError("The mask elements should be > 1")
     1113        istart=[]
     1114        iend=[]
     1115        if mask[0]: istart.append(0)
     1116        for i in range(len(mask)-1):
     1117            if not mask[i] and mask[i+1]:
     1118                istart.append(i+1)
     1119            elif mask[i] and not mask[i+1]:
     1120                iend.append(i)
     1121        if mask[len(mask)-1]: iend.append(len(mask)-1)
     1122        if len(istart) != len(iend):
     1123            raise RuntimeError("Numbers of mask start != mask end.")
     1124        for i in range(len(istart)):
     1125            if istart[i] > iend[i]:
     1126                raise RuntimeError("Mask start index > mask end index")
     1127                break
     1128        return istart,iend
     1129
     1130#    def get_restfreqs(self):
     1131#        """
     1132#        Get the restfrequency(s) stored in this scantable.
     1133#        The return value(s) are always of unit 'Hz'
     1134#        Parameters:
     1135#            none
     1136#        Returns:
     1137#            a list of doubles
     1138#        """
     1139#        return list(self._getrestfreqs())
     1140
     1141    def get_restfreqs(self, ids=None):
    8241142        """
    8251143        Get the restfrequency(s) stored in this scantable.
    8261144        The return value(s) are always of unit 'Hz'
    8271145        Parameters:
    828             none
     1146            ids: (optional) a list of MOLECULE_ID for that restfrequency(s) to
     1147                 be retrieved
    8291148        Returns:
    830             a list of doubles
    831         """
    832         return list(self._getrestfreqs())
    833 
     1149            dictionary containing ids and a list of doubles for each id
     1150        """
     1151        if ids is None:
     1152            rfreqs={}
     1153            idlist = self.getmolnos()
     1154            for i in idlist:
     1155                rfreqs[i]=list(self._getrestfreqs(i))
     1156            return rfreqs
     1157        else:
     1158            if type(ids)==list or type(ids)==tuple:
     1159                rfreqs={}
     1160                for i in ids:
     1161                    rfreqs[i]=list(self._getrestfreqs(i))
     1162                return rfreqs
     1163            else:
     1164                return list(self._getrestfreqs(ids))
     1165            #return list(self._getrestfreqs(ids))
    8341166
    8351167    def set_restfreqs(self, freqs=None, unit='Hz'):
    8361168        """
     1169        ********NEED TO BE UPDATED begin************
    8371170        Set or replace the restfrequency specified and
    8381171        If the 'freqs' argument holds a scalar,
     
    8461179        E.g. 'freqs=[1e9, 2e9]'  would mean IF 0 gets restfreq 1e9 and
    8471180        IF 1 gets restfreq 2e9.
     1181        ********NEED TO BE UPDATED end************
    8481182        You can also specify the frequencies via a linecatalog.
    8491183
     
    8531187
    8541188        Example:
    855             # set the given restfrequency for the whole table
     1189            # set the given restfrequency for the all currently selected IFs
    8561190            scan.set_restfreqs(freqs=1.4e9)
    857             # If thee number of IFs in the data is >= 2 IF0 gets the first
    858             # value IF1 the second...
    859             scan.set_restfreqs(freqs=[1.4e9, 1.67e9])
     1191            # set multiple restfrequencies to all the selected data
     1192            scan.set_restfreqs(freqs=[1.4e9, 1.41e9, 1.42e9])
     1193            # If the number of IFs in the data is >= 2 the IF0 gets the first
     1194            # value IF1 the second... NOTE that freqs needs to be
     1195            # specified in list of list (e.g. [[],[],...] ).
     1196            scan.set_restfreqs(freqs=[[1.4e9],[1.67e9]])
    8601197            #set the given restfrequency for the whole table (by name)
    8611198            scan.set_restfreqs(freqs="OH1667")
     
    8771214        # simple  value
    8781215        if isinstance(freqs, int) or isinstance(freqs, float):
    879             self._setrestfreqs(freqs, "",unit)
     1216            # TT mod
     1217            #self._setrestfreqs(freqs, "",unit)
     1218            self._setrestfreqs([freqs], [""],unit)
    8801219        # list of values
    8811220        elif isinstance(freqs, list) or isinstance(freqs, tuple):
    8821221            # list values are scalars
    8831222            if isinstance(freqs[-1], int) or isinstance(freqs[-1], float):
     1223                self._setrestfreqs(freqs, [""],unit)
     1224            # list values are tuples, (value, name)
     1225            elif isinstance(freqs[-1], dict):
     1226                #sel = selector()
     1227                #savesel = self._getselection()
     1228                #iflist = self.getifnos()
     1229                #for i in xrange(len(freqs)):
     1230                #    sel.set_ifs(iflist[i])
     1231                #    self._setselection(sel)
     1232                #    self._setrestfreqs(freqs[i], "",unit)
     1233                #self._setselection(savesel)
     1234                self._setrestfreqs(freqs["value"],
     1235                                   freqs["name"], "MHz")
     1236            elif isinstance(freqs[-1], list) or isinstance(freqs[-1], tuple):
    8841237                sel = selector()
    8851238                savesel = self._getselection()
    8861239                iflist = self.getifnos()
    887                 for i in xrange(len(freqs)):
    888                     sel.set_ifs(iflist[i])
    889                     self._setselection(sel)
    890                     self._setrestfreqs(freqs[i], "",unit)
    891                 self._setselection(savesel)
    892             # list values are tuples, (value, name)
    893             elif isinstance(freqs[-1], dict):
    894                 sel = selector()
    895                 savesel = self._getselection()
    896                 iflist = self.getifnos()
     1240                if len(freqs)>len(iflist):
     1241                    raise ValueError("number of elements in list of list exeeds the current IF selections")
    8971242                for i in xrange(len(freqs)):
    8981243                    sel.set_ifs(iflist[i])
     
    9051250            sel = selector()
    9061251            savesel = self._getselection()
    907             iflist = self.getifnos()
    9081252            for i in xrange(freqs.nrow()):
    9091253                sel.set_ifs(iflist[i])
     
    9631307                msg = "Illegal file name '%s'." % (filename)
    9641308                if rcParams['verbose']:
    965                     print msg
     1309                    #print msg
     1310                    asaplog.push( msg )
     1311                    print_log( 'ERROR' )
    9661312                else:
    9671313                    raise IOError(msg)
     
    9781324    # Maths business
    9791325    #
    980     @print_log_dec
     1326    #@print_log_dec
    9811327    def average_time(self, mask=None, scanav=False, weight='tint', align=False):
    9821328        """
     
    10201366        except RuntimeError, msg:
    10211367            if rcParams['verbose']:
    1022                 print msg
     1368                #print msg
     1369                print_log()
     1370                asaplog.push( str(msg) )
     1371                print_log( 'ERROR' )
    10231372                return
    10241373            else: raise
    10251374        s._add_history("average_time", varlist)
     1375        print_log()
    10261376        return s
    10271377
    1028     @print_log_dec
     1378    #@print_log_dec
    10291379    def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None):
    10301380        """
     
    10511401        s = scantable(self._math._convertflux(self, d, eta, jyperk))
    10521402        s._add_history("convert_flux", varlist)
     1403        print_log()
    10531404        if insitu: self._assign(s)
    10541405        else: return s
    10551406
    1056     @print_log_dec
     1407    #@print_log_dec
    10571408    def gain_el(self, poly=None, filename="", method="linear", insitu=None):
    10581409        """
     
    11031454        s = scantable(self._math._gainel(self, poly, filename, method))
    11041455        s._add_history("gain_el", varlist)
     1456        print_log()
    11051457        if insitu:
    11061458            self._assign(s)
     
    11081460            return s
    11091461
    1110     @print_log_dec
     1462    #@print_log_dec
    11111463    def freq_align(self, reftime=None, method='cubic', insitu=None):
    11121464        """
     
    11301482        s = scantable(self._math._freq_align(self, reftime, method))
    11311483        s._add_history("freq_align", varlist)
     1484        print_log()
    11321485        if insitu: self._assign(s)
    11331486        else: return s
    11341487
    1135     @print_log_dec
     1488    #@print_log_dec
    11361489    def opacity(self, tau=None, insitu=None):
    11371490        """
     
    11581511        s = scantable(self._math._opacity(self, tau))
    11591512        s._add_history("opacity", varlist)
     1513        print_log()
    11601514        if insitu: self._assign(s)
    11611515        else: return s
    11621516
    1163     @print_log_dec
     1517    #@print_log_dec
    11641518    def bin(self, width=5, insitu=None):
    11651519        """
     
    11761530        s = scantable(self._math._bin(self, width))
    11771531        s._add_history("bin", varlist)
     1532        print_log()
    11781533        if insitu:
    11791534            self._assign(s)
     
    11811536            return s
    11821537
    1183     @print_log_dec
     1538    #@print_log_dec
    11841539    def resample(self, width=5, method='cubic', insitu=None):
    11851540        """
    11861541        Return a scan where all spectra have been binned up.
    1187 
     1542       
    11881543        Parameters:
    11891544            width:       The bin width (default=5) in pixels
     
    12001555        s = scantable(self._math._resample(self, method, width))
    12011556        s._add_history("resample", varlist)
     1557        print_log()
    12021558        if insitu: self._assign(s)
    12031559        else: return s
    12041560
    1205     @print_log_dec
     1561    #@print_log_dec
    12061562    def average_pol(self, mask=None, weight='none'):
    12071563        """
     
    12181574        s = scantable(self._math._averagepol(self, mask, weight.upper()))
    12191575        s._add_history("average_pol", varlist)
     1576        print_log()
    12201577        return s
    12211578
    1222     @print_log_dec
     1579    #@print_log_dec
    12231580    def average_beam(self, mask=None, weight='none'):
    12241581        """
     
    12351592        s = scantable(self._math._averagebeams(self, mask, weight.upper()))
    12361593        s._add_history("average_beam", varlist)
     1594        print_log()
    12371595        return s
    12381596
     
    12491607        self._add_history("parallactify", varlist)
    12501608
    1251     @print_log_dec
     1609    #@print_log_dec
    12521610    def convert_pol(self, poltype=None):
    12531611        """
     
    12631621        except RuntimeError, msg:
    12641622            if rcParams['verbose']:
    1265                 print msg
     1623                #print msg
     1624                print_log()
     1625                asaplog.push( str(msg) )
     1626                print_log( 'ERROR' )
    12661627                return
    12671628            else:
    12681629                raise
    12691630        s._add_history("convert_pol", varlist)
     1631        print_log()
    12701632        return s
    12711633
    1272     @print_log_dec
    1273     def smooth(self, kernel="hanning", width=5.0, order=2, insitu=None):
     1634    #@print_log_dec
     1635    def smooth(self, kernel="hanning", width=5.0, order=2, plot=False, insitu=None):
    12741636        """
    12751637        Smooth the spectrum by the specified kernel (conserving flux).
     
    12861648                        specify the order of the polnomial. Ignored by all other
    12871649                        kernels.
     1650            plot:       plot the original and the smoothed spectra.
     1651                        In this each indivual fit has to be approved, by
     1652                        typing 'y' or 'n'
    12881653            insitu:     if False a new scantable is returned.
    12891654                        Otherwise, the scaling is done in-situ
     
    12951660        self._math._setinsitu(insitu)
    12961661        varlist = vars()
     1662
     1663        if plot: orgscan = self.copy()
     1664
    12971665        s = scantable(self._math._smooth(self, kernel.lower(), width, order))
    12981666        s._add_history("smooth", varlist)
     1667
     1668        if plot:
     1669            if rcParams['plotter.gui']:
     1670                from asap.asaplotgui import asaplotgui as asaplot
     1671            else:
     1672                from asap.asaplot import asaplot
     1673            self._p=asaplot()
     1674            self._p.set_panels()
     1675            ylab=s._get_ordinate_label()
     1676            #self._p.palette(0,["#777777","red"])
     1677            for r in xrange(s.nrow()):
     1678                xsm=s._getabcissa(r)
     1679                ysm=s._getspectrum(r)
     1680                xorg=orgscan._getabcissa(r)
     1681                yorg=orgscan._getspectrum(r)
     1682                self._p.clear()
     1683                self._p.hold()
     1684                self._p.set_axes('ylabel',ylab)
     1685                self._p.set_axes('xlabel',s._getabcissalabel(r))
     1686                self._p.set_axes('title',s._getsourcename(r))
     1687                self._p.set_line(label='Original',color="#777777")
     1688                self._p.plot(xorg,yorg)
     1689                self._p.set_line(label='Smoothed',color="red")
     1690                self._p.plot(xsm,ysm)
     1691                ### Ugly part for legend
     1692                for i in [0,1]:
     1693                    self._p.subplots[0]['lines'].append([self._p.subplots[0]['axes'].lines[i]])
     1694                self._p.release()
     1695                ### Ugly part for legend
     1696                self._p.subplots[0]['lines']=[]
     1697                res = raw_input("Accept smoothing ([y]/n): ")
     1698                if res.upper() == 'N':
     1699                    s._setspectrum(yorg, r)
     1700            self._p.unmap()
     1701            self._p = None
     1702            del orgscan
     1703
     1704        print_log()
    12991705        if insitu: self._assign(s)
    13001706        else: return s
    13011707
    1302     @print_log_dec
     1708    #@print_log_dec
    13031709    def poly_baseline(self, mask=None, order=0, plot=False, uselin=False,
    13041710                      insitu=None):
     
    13211727        """
    13221728        if insitu is None: insitu = rcParams['insitu']
     1729        if not insitu:
     1730            workscan = self.copy()
     1731        else:
     1732            workscan = self
    13231733        varlist = vars()
    13241734        if mask is None:
    13251735            mask = [True for i in xrange(self.nchan(-1))]
     1736       
    13261737        from asap.asapfitter import fitter
    13271738        try:
    13281739            f = fitter()
    1329             f.set_scan(self, mask)
    1330             #f.set_function(poly=order)
    13311740            if uselin:
    13321741                f.set_function(lpoly=order)
    13331742            else:
    13341743                f.set_function(poly=order)
    1335             s = f.auto_fit(insitu, plot=plot)
    1336             s._add_history("poly_baseline", varlist)
    1337             if insitu: self._assign(s)
    1338             else: return s
     1744
     1745            rows = range(workscan.nrow())
     1746            if len(rows) > 0:
     1747                self.blpars = []
     1748           
     1749            for r in rows:
     1750                # take into account flagtra info (CAS-1434)
     1751                flagtra = workscan._getmask(r)
     1752                actualmask = mask[:]
     1753                if len(actualmask) == 0:
     1754                    actualmask = list(flagtra[:])
     1755                else:
     1756                    if len(actualmask) != len(flagtra):
     1757                        raise RuntimeError, "Mask and flagtra have different length"
     1758                    else:
     1759                        for i in range(0, len(actualmask)):
     1760                            actualmask[i] = actualmask[i] and flagtra[i]
     1761                f.set_scan(workscan, actualmask)
     1762                f.x = workscan._getabcissa(r)
     1763                f.y = workscan._getspectrum(r)
     1764                f.data = None
     1765                f.fit()
     1766                if plot:
     1767                    f.plot(residual=True)
     1768                    x = raw_input("Accept fit ( [y]/n ): ")
     1769                    if x.upper() == 'N':
     1770                        self.blpars.append(None)
     1771                        continue
     1772                workscan._setspectrum(f.fitter.getresidual(), r)
     1773                self.blpars.append(f.get_parameters())
     1774
     1775            if plot:
     1776                f._p.unmap()
     1777                f._p = None
     1778            workscan._add_history("poly_baseline", varlist)
     1779            print_log()
     1780            if insitu: self._assign(workscan)
     1781            else: return workscan
    13391782        except RuntimeError:
    13401783            msg = "The fit failed, possibly because it didn't converge."
    13411784            if rcParams['verbose']:
    1342                 print msg
     1785                #print msg
     1786                print_log()
     1787                asaplog.push( str(msg) )
     1788                print_log( 'ERROR' )
    13431789                return
    13441790            else:
    13451791                raise RuntimeError(msg)
     1792
    13461793
    13471794    def auto_poly_baseline(self, mask=[], edge=(0, 0), order=0,
     
    14271874
    14281875        rows = range(workscan.nrow())
     1876        # Save parameters of baseline fits & masklists as a class attribute.
     1877        # NOTICE: It does not reflect changes in scantable!
     1878        if len(rows) > 0:
     1879            self.blpars=[]
     1880            self.masklists=[]
    14291881        asaplog.push("Processing:")
    14301882        for r in rows:
     
    14411893                    curedge = edge[workscan.getif(r)]
    14421894
     1895            # take into account flagtra info (CAS-1434)
     1896            flagtra = workscan._getmask(r)
     1897            actualmask = mask[:]
     1898            if len(actualmask) == 0:
     1899                actualmask = list(flagtra[:])
     1900            else:
     1901                if len(actualmask) != len(flagtra):
     1902                    raise RuntimeError, "Mask and flagtra have different length"
     1903                else:
     1904                    for i in range(0, len(actualmask)):
     1905                        actualmask[i] = actualmask[i] and flagtra[i]
     1906
    14431907            # setup line finder
    1444             fl.find_lines(r, mask, curedge)
    1445             f.set_data(workscan._getabcissa(r),  workscan._getspectrum(r),
    1446                         mask_and(workscan._getmask(r), fl.get_mask()))
     1908            fl.find_lines(r, actualmask, curedge)
     1909            outmask=fl.get_mask()
     1910            f.set_scan(workscan, fl.get_mask())
     1911            f.x = workscan._getabcissa(r)
     1912            f.y = workscan._getspectrum(r)
     1913            f.data = None
    14471914            f.fit()
    1448             x = f.get_parameters()
     1915           
     1916            # Show mask list
     1917            masklist=workscan.get_masklist(fl.get_mask(),row=r)
     1918            msg = "mask range: "+str(masklist)
     1919            asaplog.push(msg, False)
     1920
    14491921            if plot:
    14501922                f.plot(residual=True)
    14511923                x = raw_input("Accept fit ( [y]/n ): ")
    14521924                if x.upper() == 'N':
     1925                    self.blpars.append(None)
     1926                    self.masklists.append(None)
    14531927                    continue
     1928
    14541929            workscan._setspectrum(f.fitter.getresidual(), r)
     1930            self.blpars.append(f.get_parameters())
     1931            self.masklists.append(masklist)
    14551932        if plot:
    14561933            f._p.unmap()
     
    14621939            return workscan
    14631940
    1464     @print_log_dec
     1941    #@print_log_dec
    14651942    def rotate_linpolphase(self, angle):
    14661943        """
     
    14761953        self._math._rotate_linpolphase(self, angle)
    14771954        self._add_history("rotate_linpolphase", varlist)
     1955        print_log()
    14781956        return
    14791957
    1480     @print_log_dec
     1958    #@print_log_dec
    14811959    def rotate_xyphase(self, angle):
    14821960        """
     
    14921970        self._math._rotate_xyphase(self, angle)
    14931971        self._add_history("rotate_xyphase", varlist)
     1972        print_log()
    14941973        return
    14951974
    1496     @print_log_dec
     1975    #@print_log_dec
    14971976    def swap_linears(self):
    14981977        """
     
    15031982        self._math._swap_linears(self)
    15041983        self._add_history("swap_linears", varlist)
     1984        print_log()
    15051985        return
    15061986
    1507     @print_log_dec
     1987    #@print_log_dec
    15081988    def invert_phase(self):
    15091989        """
     
    15131993        self._math._invert_phase(self)
    15141994        self._add_history("invert_phase", varlist)
     1995        print_log()
    15151996        return
    15161997
    1517     @print_log_dec
     1998    #@print_log_dec
    15181999    def add(self, offset, insitu=None):
    15192000        """
     
    15302011        s = scantable(self._math._unaryop(self, offset, "ADD", False))
    15312012        s._add_history("add", varlist)
     2013        print_log()
    15322014        if insitu:
    15332015            self._assign(s)
     
    15352017            return s
    15362018
    1537     @print_log_dec
     2019    #@print_log_dec
    15382020    def scale(self, factor, tsys=True, insitu=None):
    15392021        """
    15402022        Return a scan where all spectra are scaled by the give 'factor'
    15412023        Parameters:
    1542             factor:      the scaling factor
     2024            factor:      the scaling factor (float or 1D float list)
    15432025            insitu:      if False a new scantable is returned.
    15442026                         Otherwise, the scaling is done in-situ
     
    15502032        self._math._setinsitu(insitu)
    15512033        varlist = vars()
    1552         s = scantable(self._math._unaryop(self, factor, "MUL", tsys))
     2034        s = None
     2035        import numpy
     2036        if isinstance(factor, list) or isinstance(factor, numpy.ndarray):
     2037            if isinstance(factor[0], list) or isinstance(factor[0], numpy.ndarray):
     2038                from asapmath import _array2dOp
     2039                s = _array2dOp( self.copy(), factor, "MUL", tsys )
     2040            else:
     2041                s = scantable( self._math._arrayop( self.copy(), factor, "MUL", tsys ) )
     2042        else:
     2043            s = scantable(self._math._unaryop(self.copy(), factor, "MUL", tsys))
    15532044        s._add_history("scale", varlist)
     2045        print_log()
    15542046        if insitu:
    15552047            self._assign(s)
     
    15932085        self._add_history("set_sourcetype", varlist)
    15942086
    1595     @print_log_dec
    1596     def auto_quotient(self, preserve=True, mode='paired'):
     2087    #@print_log_dec
     2088    def auto_quotient(self, preserve=True, mode='paired', verify=False):
    15972089        """
    15982090        This function allows to build quotients automatically.
    1599         It assumes the observation to have the same numer of
     2091        It assumes the observation to have the same number of
    16002092        "ons" and "offs"
    16012093        Parameters:
     
    16342126            s = scantable(self._math._auto_quotient(self, mode, preserve))
    16352127        s._add_history("auto_quotient", varlist)
     2128        print_log()
    16362129        return s
    16372130
    1638     @print_log_dec
     2131    #@print_log_dec
    16392132    def mx_quotient(self, mask = None, weight='median', preserve=True):
    16402133        """
     
    16562149        q = quotient(on, off, preserve)
    16572150        q._add_history("mx_quotient", varlist)
     2151        print_log()
    16582152        return q
    16592153
    1660     @print_log_dec
     2154    #@print_log_dec
    16612155    def freq_switch(self, insitu=None):
    16622156        """
     
    16742168        s = scantable(self._math._freqswitch(self))
    16752169        s._add_history("freq_switch", varlist)
     2170        print_log()
    16762171        if insitu: self._assign(s)
    16772172        else: return s
    16782173
    1679     @print_log_dec
     2174    #@print_log_dec
    16802175    def recalc_azel(self):
    16812176        """
     
    16882183        self._recalcazel()
    16892184        self._add_history("recalc_azel", varlist)
     2185        print_log()
    16902186        return
    16912187
    1692     @print_log_dec
     2188    #@print_log_dec
    16932189    def __add__(self, other):
    1694         varlist = vars()
    1695         s = None
    1696         if isinstance(other, scantable):
    1697             s = scantable(self._math._binaryop(self, other, "ADD"))
    1698         elif isinstance(other, float):
    1699             s = scantable(self._math._unaryop(self, other, "ADD", False))
    1700         else:
    1701             raise TypeError("Other input is not a scantable or float value")
    1702         s._add_history("operator +", varlist)
    1703         return s
    1704 
    1705     @print_log_dec
     2190        """
     2191        implicit on all axes and on Tsys
     2192        """
     2193        return self._operation( other, "ADD" )
     2194
     2195    #@print_log_dec
    17062196    def __sub__(self, other):
    17072197        """
    17082198        implicit on all axes and on Tsys
    17092199        """
    1710         varlist = vars()
    1711         s = None
    1712         if isinstance(other, scantable):
    1713             s = scantable(self._math._binaryop(self, other, "SUB"))
    1714         elif isinstance(other, float):
    1715             s = scantable(self._math._unaryop(self, other, "SUB", False))
    1716         else:
    1717             raise TypeError("Other input is not a scantable or float value")
    1718         s._add_history("operator -", varlist)
    1719         return s
    1720 
    1721     @print_log_dec
     2200        return self._operation( other, 'SUB' )
     2201
     2202    #@print_log_dec
    17222203    def __mul__(self, other):
    17232204        """
    17242205        implicit on all axes and on Tsys
    17252206        """
    1726         varlist = vars()
    1727         s = None
    1728         if isinstance(other, scantable):
    1729             s = scantable(self._math._binaryop(self, other, "MUL"))
    1730         elif isinstance(other, float):
    1731             s = scantable(self._math._unaryop(self, other, "MUL", False))
    1732         else:
    1733             raise TypeError("Other input is not a scantable or float value")
    1734         s._add_history("operator *", varlist)
    1735         return s
    1736 
    1737 
    1738     @print_log_dec
     2207        return self._operation( other, 'MUL' )
     2208
     2209    #@print_log_dec
    17392210    def __div__(self, other):
    17402211        """
    17412212        implicit on all axes and on Tsys
    17422213        """
    1743         varlist = vars()
    1744         s = None
    1745         if isinstance(other, scantable):
    1746             s = scantable(self._math._binaryop(self, other, "DIV"))
    1747         elif isinstance(other, float):
    1748             if other == 0.0:
    1749                 raise ZeroDivisionError("Dividing by zero is not recommended")
    1750             s = scantable(self._math._unaryop(self, other, "DIV", False))
    1751         else:
    1752             raise TypeError("Other input is not a scantable or float value")
    1753         s._add_history("operator /", varlist)
    1754         return s
     2214        return self._operation( other, 'DIV' )
    17552215
    17562216    def get_fit(self, row=0):
     
    17652225        fit = asapfit(self._getfit(row))
    17662226        if rcParams['verbose']:
    1767             print fit
     2227            #print fit
     2228            asaplog.push( '%s' %(fit) )
     2229            print_log()
    17682230            return
    17692231        else:
     
    18622324        return (sum(nchans)/len(nchans) == nchans[0])
    18632325
    1864     def _fill(self, names, unit, average):
     2326    def _fill(self, names, unit, average, getpt, antenna):
    18652327        import os
    18662328        from asap._asap import stfiller
     
    18742336                if rcParams['verbose']:
    18752337                    asaplog.push(msg)
    1876                     print asaplog.pop().strip()
     2338                    #print asaplog.pop().strip()
     2339                    print_log( 'ERROR' )
    18772340                    return
    18782341                raise IOError(msg)
     
    18892352            asaplog.push(msg, False)
    18902353            print_log()
    1891             r._open(name, -1, -1)
     2354            r._open(name, antenna, -1, -1, getpt)
    18922355            r._read()
    18932356            if average:
     
    19012364        if unit is not None:
    19022365            self.set_fluxunit(unit)
    1903         self.set_freqframe(rcParams['scantable.freqframe'])
     2366        #self.set_freqframe(rcParams['scantable.freqframe'])
    19042367
    19052368    def __getitem__(self, key):
     
    19262389        for i in range(len(self)):
    19272390            yield self[i]
     2391
     2392    def _operation(self, other, opmode):
     2393        varlist = vars()
     2394        s = None
     2395        import numpy
     2396        if isinstance(other, scantable):
     2397            s = scantable(self._math._binaryop(self.copy(), other, opmode))
     2398        elif isinstance(other, float) or isinstance(other, int):
     2399            if opmode == 'DIV' and float(other) == 0.0:
     2400                raise ZeroDivisionError("Dividing by zero is not recommended")
     2401            s = scantable(self._math._unaryop(self.copy(), other, opmode, False))
     2402        elif isinstance(other, list) or isinstance(other, numpy.ndarray):
     2403            if isinstance(other[0], list) or isinstance(other[0], numpy.ndarray):
     2404                from asapmath import _array2dOp
     2405                s = _array2dOp( self.copy(), other, opmode, False )
     2406            else:
     2407                s = scantable(self._math._arrayop(self.copy(), other, opmode, False))
     2408        else:
     2409            raise TypeError("Other input is not a scantable or float value or float list")
     2410        opdic = {}
     2411        opdic['ADD'] = '+'
     2412        opdic['SUB'] = '-'
     2413        opdic['MUL'] = '*'
     2414        opdic['DIV'] = '/'
     2415        s._add_history("operator %s" % opdic[opmode], varlist)
     2416        print_log()
     2417        return s
     2418
     2419       
  • branches/mergetest/python/selector.py

    r1596 r1779  
    160160        """
    161161        self._setorder(order)
     162
     163    def set_rows(self, rows=[]):
     164        """
     165        Set a sequence of row numbers (0-based). Power users Only!
     166        NOTICE row numbers can be changed easily by sorting,
     167        prior selection, etc.
     168        Parameters:
     169            rows:    a list of integers. Default [] is to unset the selection.
     170        """
     171        vec = _to_list(rows, int)
     172        if isinstance(vec,list):
     173            self._setrows(vec)
     174        else:
     175            raise TypeError('Unknown row number type. Use lists of integers.')
     176
     177    def set_types(self, types=[]):
     178        """
     179        Set a sequence of source types.
     180        Parameters:
     181            types:    a list of integers. Default [] is to unset the selection.
     182        """
     183        vec = _to_list(types, int)
     184        if isinstance(vec,list):
     185            self._settypes(vec)
     186        else:
     187            raise TypeError('Unknown row number type. Use lists of integers.')
    162188
    163189    def get_scans(self):
     
    175201    def get_order(self):
    176202        return list(self._getorder())
     203    def get_types(self):
     204        return list(self._gettypes())
    177205    def get_query(self):
    178206        prefix = "SELECT FROM $1 WHERE "
Note: See TracChangeset for help on using the changeset viewer.