Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/scantable.py

    r1948 r1846  
    22
    33import os
    4 import numpy
    54try:
    65    from functools import wraps as wraps_dec
     
    1211from asap._asap import filler
    1312from asap.parameters import rcParams
    14 from asap.logging import asaplog, asaplog_post_dec
     13from asap.logging import asaplog, print_log, print_log_dec
    1514from asap.selector import selector
    1615from asap.linecatalog import linecatalog
    1716from asap.coordinate import coordinate
    18 from asap.utils import _n_bools, mask_not, mask_and, mask_or, page
    19 from asap.asapfitter import fitter
     17from asap.utils import _n_bools, mask_not, mask_and, mask_or
    2018
    2119
     
    2422    def wrap(obj, *args, **kw):
    2523        basesel = obj.get_selection()
    26         try:
    27             val = func(obj, *args, **kw)
    28         finally:
    29             obj.set_selection(basesel)
     24        val = func(obj, *args, **kw)
     25        obj.set_selection(basesel)
    3026        return val
    3127    return wrap
     
    3935
    4036    """
    41     if ( os.path.isdir(filename)
    42          and os.path.exists(filename+'/table.info')
    43          and os.path.exists(filename+'/table.dat') ):
    44         f=open(filename+'/table.info')
    45         l=f.readline()
    46         f.close()
    47         #if ( l.find('Scantable') != -1 ):
    48         if ( l.find('Measurement Set') == -1 ):
    49             return True
    50         else:
    51             return False
    52     else:
    53         return False
    54 ##     return (os.path.isdir(filename)
    55 ##             and not os.path.exists(filename+'/table.f1')
    56 ##             and os.path.exists(filename+'/table.info'))
    57 
    58 def is_ms(filename):
    59     """Is the given file a MeasurementSet?
    60 
    61     Parameters:
    62 
    63         filename: the name of the file/directory to test
    64 
    65     """
    66     if ( os.path.isdir(filename)
    67          and os.path.exists(filename+'/table.info')
    68          and os.path.exists(filename+'/table.dat') ):
    69         f=open(filename+'/table.info')
    70         l=f.readline()
    71         f.close()
    72         if ( l.find('Measurement Set') != -1 ):
    73             return True
    74         else:
    75             return False
    76     else:
    77         return False
    78    
     37    return (os.path.isdir(filename)
     38            and not os.path.exists(filename+'/table.f1')
     39            and os.path.exists(filename+'/table.info'))
     40
     41
    7942class scantable(Scantable):
    8043    """\
     
    8245    """
    8346
    84     @asaplog_post_dec
    85     #def __init__(self, filename, average=None, unit=None, getpt=None,
    86     #             antenna=None, parallactify=None):
    87     def __init__(self, filename, average=None, unit=None, parallactify=None, **args):
     47    @print_log_dec
     48    def __init__(self, filename, average=None, unit=None, getpt=None,
     49                 antenna=None, parallactify=None):
    8850        """\
    8951        Create a scantable from a saved one or make a reference
     
    11173                          the MS data faster in some cases.
    11274
    113             antenna:      for MeasurementSet input data only:
    114                           Antenna selection. integer (id) or string (name or id).
     75            antenna:      Antenna selection. integer (id) or string (name or id).
    11576
    11677            parallactify: Indicate that the data had been parallatified. Default
     
    12081        if average is None:
    12182            average = rcParams['scantable.autoaverage']
    122         #if getpt is None:
    123         #    getpt = True
    124         #if antenna is not None:
    125         #    asaplog.push("Antenna selection currently unsupported."
    126         #                 "Using ''")
    127         #    asaplog.post('WARN')
    128         #if antenna is None:
    129         #    antenna = ''
    130         #elif type(antenna) == int:
    131         #    antenna = '%s' % antenna
    132         #elif type(antenna) == list:
    133         #    tmpstr = ''
    134         #    for i in range( len(antenna) ):
    135         #        if type(antenna[i]) == int:
    136         #            tmpstr = tmpstr + ('%s,'%(antenna[i]))
    137         #        elif type(antenna[i]) == str:
    138         #            tmpstr=tmpstr+antenna[i]+','
    139         #        else:
    140         #            raise TypeError('Bad antenna selection.')
    141         #    antenna = tmpstr.rstrip(',')
     83        if getpt is None:
     84            getpt = True
     85        if antenna is not None:
     86            asaplog.push("Antenna selection currently unsupported."
     87                         "Using '0'")
     88            print_log('WARN')
     89        if antenna is None:
     90            antenna = ''
     91        elif type(antenna) == int:
     92            antenna = '%s' % antenna
     93        elif type(antenna) == list:
     94            tmpstr = ''
     95            for i in range( len(antenna) ):
     96                if type(antenna[i]) == int:
     97                    tmpstr = tmpstr + ('%s,'%(antenna[i]))
     98                elif type(antenna[i]) == str:
     99                    tmpstr=tmpstr+antenna[i]+','
     100                else:
     101                    asaplog.push('Bad antenna selection.')
     102                    print_log('ERROR')
     103                    return
     104            antenna = tmpstr.rstrip(',')
    142105        parallactify = parallactify or rcParams['scantable.parallactify']
    143106        varlist = vars()
     
    152115                if not os.path.exists(filename):
    153116                    s = "File '%s' not found." % (filename)
     117                    if rcParams['verbose']:
     118                        asaplog.push(s)
     119                        print_log('ERROR')
     120                        return
    154121                    raise IOError(s)
    155122                if is_scantable(filename):
     
    160127                    # do not reset to the default freqframe
    161128                    #self.set_freqframe(rcParams['scantable.freqframe'])
    162                 #elif os.path.isdir(filename) \
    163                 #         and not os.path.exists(filename+'/table.f1'):
    164                 elif is_ms(filename):
    165                     # Measurement Set
    166                     opts={'ms': {}}
    167                     mskeys=['getpt','antenna']
    168                     for key in mskeys:
    169                         if key in args.keys():
    170                             opts['ms'][key] = args[key]
    171                     #self._fill([filename], unit, average, getpt, antenna)
    172                     self._fill([filename], unit, average, opts)
    173                 elif os.path.isfile(filename):
    174                     #self._fill([filename], unit, average, getpt, antenna)
    175                     self._fill([filename], unit, average)
    176                 else:
     129                elif os.path.isdir(filename) \
     130                         and not os.path.exists(filename+'/table.f1'):
    177131                    msg = "The given file '%s'is not a valid " \
    178132                          "asap table." % (filename)
    179                     raise IOError(msg)
     133                    if rcParams['verbose']:
     134                        #print msg
     135                        asaplog.push( msg )
     136                        print_log( 'ERROR' )
     137                        return
     138                    else:
     139                        raise IOError(msg)
     140                else:
     141                    self._fill([filename], unit, average, getpt, antenna)
    180142            elif (isinstance(filename, list) or isinstance(filename, tuple)) \
    181143                  and isinstance(filename[-1], str):
    182                 #self._fill(filename, unit, average, getpt, antenna)
    183                 self._fill(filename, unit, average)
     144                self._fill(filename, unit, average, getpt, antenna)
    184145        self.parallactify(parallactify)
    185146        self._add_history("scantable", varlist)
    186 
    187     @asaplog_post_dec
     147        print_log()
     148
     149    @print_log_dec
    188150    def save(self, name=None, format=None, overwrite=False):
    189151        """\
     
    196158                         this is the root file name (data in 'name'.txt
    197159                         and header in 'name'_header.txt)
    198 
    199160            format:      an optional file format. Default is ASAP.
    200                          Allowed are:
    201 
    202                             * 'ASAP' (save as ASAP [aips++] Table),
    203                             * 'SDFITS' (save as SDFITS file)
    204                             * 'ASCII' (saves as ascii text file)
    205                             * 'MS2' (saves as an casacore MeasurementSet V2)
    206                             * 'FITS' (save as image FITS - not readable by class)
    207                             * 'CLASS' (save as FITS readable by CLASS)
    208 
     161                         Allowed are - 'ASAP' (save as ASAP [aips++] Table),
     162                                       'SDFITS' (save as SDFITS file)
     163                                       'ASCII' (saves as ascii text file)
     164                                       'MS2' (saves as an aips++
     165                                              MeasurementSet V2)
     166                                       'FITS' (save as image FITS - not
     167                                               readable by class)
     168                                       'CLASS' (save as FITS readable by CLASS)
    209169            overwrite:   If the file should be overwritten if it exists.
    210170                         The default False is to return with warning
    211171                         without writing the output. USE WITH CARE.
    212 
    213172        Example::
    214173
     
    228187            if not overwrite:
    229188                msg = "File %s exists." % name
    230                 raise IOError(msg)
     189                if rcParams['verbose']:
     190                    #print msg
     191                    asaplog.push( msg )
     192                    print_log( 'ERROR' )
     193                    return
     194                else:
     195                    raise IOError(msg)
    231196        format2 = format.upper()
    232197        if format2 == 'ASAP':
     
    236201            writer = stw(format2)
    237202            writer.write(self, name)
     203        print_log()
    238204        return
    239205
     
    267233        from asap import unique
    268234        if not _is_valid(scanid):
    269             raise RuntimeError( 'Please specify a scanno to drop from the scantable' )
    270         scanid = _to_list(scanid)
    271         allscans = unique([ self.getscan(i) for i in range(self.nrow())])
    272         for sid in scanid: allscans.remove(sid)
    273         if len(allscans) == 0:
    274             raise ValueError("Can't remove all scans")
    275         sel = selector(scans=allscans)
    276         return self._select_copy(sel)
     235            if rcParams['verbose']:
     236                #print "Please specify a scanno to drop from the scantable"
     237                asaplog.push( 'Please specify a scanno to drop from the scantable' )
     238                print_log( 'ERROR' )
     239                return
     240            else:
     241                raise RuntimeError("No scan given")
     242        try:
     243            scanid = _to_list(scanid)
     244            allscans = unique([ self.getscan(i) for i in range(self.nrow())])
     245            for sid in scanid: allscans.remove(sid)
     246            if len(allscans) == 0:
     247                raise ValueError("Can't remove all scans")
     248        except ValueError:
     249            if rcParams['verbose']:
     250                #print "Couldn't find any match."
     251                print_log()
     252                asaplog.push( "Couldn't find any match." )
     253                print_log( 'ERROR' )
     254                return
     255            else: raise
     256        try:
     257            sel = selector(scans=allscans)
     258            return self._select_copy(sel)
     259        except RuntimeError:
     260            if rcParams['verbose']:
     261                #print "Couldn't find any match."
     262                print_log()
     263                asaplog.push( "Couldn't find any match." )
     264                print_log( 'ERROR' )
     265            else:
     266                raise
    277267
    278268    def _select_copy(self, selection):
     
    284274
    285275    def get_scan(self, scanid=None):
    286         """\
     276        """
    287277        Return a specific scan (by scanno) or collection of scans (by
    288278        source name) in a new scantable.
     
    309299        """
    310300        if scanid is None:
    311             raise RuntimeError( 'Please specify a scan no or name to '
    312                                 'retrieve from the scantable' )
     301            if rcParams['verbose']:
     302                #print "Please specify a scan no or name to " \
     303                #      "retrieve from the scantable"
     304                asaplog.push( 'Please specify a scan no or name to retrieve'
     305                             ' from the scantable' )
     306                print_log( 'ERROR' )
     307                return
     308            else:
     309                raise RuntimeError("No scan given")
     310
    313311        try:
    314312            bsel = self.get_selection()
     
    325323            else:
    326324                msg = "Illegal scanid type, use 'int' or 'list' if ints."
    327                 raise TypeError(msg)
     325                if rcParams['verbose']:
     326                    #print msg
     327                    asaplog.push( msg )
     328                    print_log( 'ERROR' )
     329                else:
     330                    raise TypeError(msg)
    328331        except RuntimeError:
    329             raise
     332            if rcParams['verbose']:
     333                #print "Couldn't find any match."
     334                print_log()
     335                asaplog.push( "Couldn't find any match." )
     336                print_log( 'ERROR' )
     337            else: raise
    330338
    331339    def __str__(self):
     
    354362            else:
    355363                msg = "Illegal file name '%s'." % (filename)
    356                 raise IOError(msg)
    357         return page(info)
     364                if rcParams['verbose']:
     365                    #print msg
     366                    asaplog.push( msg )
     367                    print_log( 'ERROR' )
     368                else:
     369                    raise IOError(msg)
     370        if rcParams['verbose']:
     371            try:
     372                from IPython.genutils import page as pager
     373            except ImportError:
     374                from pydoc import pager
     375            pager(info)
     376        else:
     377            return info
    358378
    359379    def get_spectrum(self, rowno):
     
    378398
    379399    def set_spectrum(self, spec, rowno):
    380         """Set the spectrum for the current row in the scantable.
    381 
    382         Parameters:
    383 
    384              spec:   the new spectrum
    385 
    386              rowno:  the row number to set the spectrum for
     400        """Return the spectrum for the current row in the scantable as a list.
     401
     402        Parameters:
     403
     404             spec:   the spectrum
     405             rowno:    the row number to set the spectrum for
    387406
    388407        """
     
    498517            return workscan
    499518
    500     @asaplog_post_dec
    501     def stats(self, stat='stddev', mask=None, form='3.3f', row=None):
     519    #def stats(self, stat='stddev', mask=None):
     520    def stats(self, stat='stddev', mask=None, form='3.3f'):
    502521        """\
    503522        Determine the specified statistic of the current beam/if/pol
     
    509528            stat:    'min', 'max', 'min_abc', 'max_abc', 'sumsq', 'sum',
    510529                     'mean', 'var', 'stddev', 'avdev', 'rms', 'median'
    511 
    512530            mask:    an optional mask specifying where the statistic
    513531                     should be determined.
    514 
    515532            form:    format string to print statistic values
    516533
    517             row:     row number of spectrum to process.
    518                      (default is None: for all rows)
    519 
    520         Example:
     534        Example::
     535
    521536            scan.set_unit('channel')
    522537            msk = scan.create_mask([100, 200], [500, 600])
     
    536551            getchan = True
    537552            statvals = []
    538         if not rtnabc:
    539             if row == None:
    540                 statvals = self._math._stats(self, mask, stat)
    541             else:
    542                 statvals = self._math._statsrow(self, mask, stat, int(row))
     553        if not rtnabc: statvals = self._math._stats(self, mask, stat)
    543554
    544555        #def cb(i):
     
    552563        #outvec = []
    553564        sep = '-'*50
    554 
    555         if row == None:
    556             rows = xrange(self.nrow())
    557         elif isinstance(row, int):
    558             rows = [ row ]
    559 
    560         for i in rows:
     565        for i in range(self.nrow()):
    561566            refstr = ''
    562567            statunit= ''
     
    574579            out += 'Scan[%d] (%s) ' % (self.getscan(i), src)
    575580            out += 'Time[%s]:\n' % (tm)
    576             if self.nbeam(-1) > 1: out +=  ' Beam[%d] ' % (self.getbeam(i))
    577             if self.nif(-1) > 1:   out +=  ' IF[%d] ' % (self.getif(i))
    578             if self.npol(-1) > 1:  out +=  ' Pol[%d] ' % (self.getpol(i))
     581            if self.nbeam(-1) > 1:
     582                out +=  ' Beam[%d] ' % (self.getbeam(i))
     583            if self.nif(-1) > 1: out +=  ' IF[%d] ' % (self.getif(i))
     584            if self.npol(-1) > 1: out +=  ' Pol[%d] ' % (self.getpol(i))
    579585            #outvec.append(callback(i))
    580             if len(rows) > 1:
    581                 # out += ('= %'+form) % (outvec[i]) +'   '+refstr+'\n'
    582                 out += ('= %'+form) % (statvals[i]) +'   '+refstr+'\n'
     586            #out += ('= %'+form) % (outvec[i]) +'   '+refstr+'\n'
     587            out += ('= %'+form) % (statvals[i]) +'   '+refstr+'\n'
     588            out +=  sep+"\n"
     589
     590        if rcParams['verbose']:
     591            import os
     592            if os.environ.has_key( 'USER' ):
     593                usr=os.environ['USER']
    583594            else:
    584                 # out += ('= %'+form) % (outvec[0]) +'   '+refstr+'\n'
    585                 out += ('= %'+form) % (statvals[0]) +'   '+refstr+'\n'
    586             out +=  sep+"\n"
    587 
    588         import os
    589         if os.environ.has_key( 'USER' ):
    590             usr = os.environ['USER']
    591         else:
    592             import commands
    593             usr = commands.getoutput( 'whoami' )
    594         tmpfile = '/tmp/tmp_'+usr+'_casapy_asap_scantable_stats'
    595         f = open(tmpfile,'w')
    596         print >> f, sep
    597         print >> f, ' %s %s' % (label, statunit)
    598         print >> f, sep
    599         print >> f, out
    600         f.close()
    601         f = open(tmpfile,'r')
    602         x = f.readlines()
    603         f.close()
    604         asaplog.push(''.join(x), False)
    605 
     595                import commands
     596                usr=commands.getoutput( 'whoami' )
     597            tmpfile='/tmp/tmp_'+usr+'_casapy_asap_scantable_stats'
     598            f=open(tmpfile,'w')
     599            print >> f, sep
     600            print >> f, ' %s %s' % (label, statunit)
     601            print >> f, sep
     602            print >> f, out
     603            f.close()
     604            f=open(tmpfile,'r')
     605            x=f.readlines()
     606            f.close()
     607            blanc=''
     608            asaplog.push(blanc.join(x), False)
     609            #for xx in x:
     610            #    asaplog.push( xx, False )
     611            print_log()
    606612        return statvals
    607613
     
    615621            rowno:   a row number in the scantable. Default is the
    616622                     first row, i.e. rowno=0
    617 
    618623            chan:    a channel in the scantable. Default is the first
    619624                     channel, i.e. pos=0
     
    718723            out += '= %3.3f\n' % (outvec[i])
    719724            out +=  sep+'\n'
    720 
    721         asaplog.push(sep)
    722         asaplog.push(" %s" % (label))
    723         asaplog.push(sep)
    724         asaplog.push(out)
    725         asaplog.post()
     725        if rcParams['verbose']:
     726            asaplog.push(sep)
     727            asaplog.push(" %s" % (label))
     728            asaplog.push(sep)
     729            asaplog.push(out)
     730            print_log()
    726731        return outvec
    727732
    728     def _get_column(self, callback, row=-1, *args):
     733    def _get_column(self, callback, row=-1):
    729734        """
    730735        """
    731736        if row == -1:
    732             return [callback(i, *args) for i in range(self.nrow())]
     737            return [callback(i) for i in range(self.nrow())]
    733738        else:
    734739            if  0 <= row < self.nrow():
    735                 return callback(row, *args)
    736 
    737 
    738     def get_time(self, row=-1, asdatetime=False, prec=-1):
     740                return callback(row)
     741
     742
     743    def get_time(self, row=-1, asdatetime=False):
    739744        """\
    740745        Get a list of time stamps for the observations.
    741         Return a datetime object or a string (default) for each
    742         integration time stamp in the scantable.
     746        Return a datetime object for each integration time stamp in the scantable.
    743747
    744748        Parameters:
    745749
    746750            row:          row no of integration. Default -1 return all rows
    747 
    748751            asdatetime:   return values as datetime objects rather than strings
    749752
    750             prec:         number of digits shown. Default -1 to automatic calculation.
    751                           Note this number is equals to the digits of MVTime,
    752                           i.e., 0<prec<3: dates with hh:: only,
    753                           <5: with hh:mm:, <7 or 0: with hh:mm:ss,
    754                           and 6> : with hh:mm:ss.tt... (prec-6 t's added)
    755 
    756         """
     753        """
     754        from time import strptime
    757755        from datetime import datetime
    758         if prec < 0:
    759             # automagically set necessary precision +1
    760             prec = 7 - numpy.floor(numpy.log10(min(self.get_inttime())))
    761             prec = max(6, int(prec))
    762         else:
    763             prec = max(0, prec)
    764         if asdatetime:
    765             #precision can be 1 millisecond at max
    766             prec = min(12, prec)
    767 
    768         times = self._get_column(self._gettime, row, prec)
     756        times = self._get_column(self._gettime, row)
    769757        if not asdatetime:
    770758            return times
    771         format = "%Y/%m/%d/%H:%M:%S.%f"
    772         if prec < 7:
    773             nsub = 1 + (((6-prec)/2) % 3)
    774             substr = [".%f","%S","%M"]
    775             for i in range(nsub):
    776                 format = format.replace(substr[i],"")
     759        format = "%Y/%m/%d/%H:%M:%S"
    777760        if isinstance(times, list):
    778             return [datetime.strptime(i, format) for i in times]
    779         else:
    780             return datetime.strptime(times, format)
     761            return [datetime(*strptime(i, format)[:6]) for i in times]
     762        else:
     763            return datetime(*strptime(times, format)[:6])
    781764
    782765
     
    844827        Get a list of Positions on the sky (direction) for the observations.
    845828        Return a string for each integration in the scantable.
    846 
    847         Parameters:
    848 
     829        Parameters:
    849830            row:    row no of integration. Default -1 return all rows
    850 
     831        Example:
     832            none
    851833        """
    852834        return self._get_column(self._getdirection, row)
     
    864846        return self._get_column(self._getdirectionvec, row)
    865847
    866     @asaplog_post_dec
     848    @print_log_dec
    867849    def set_unit(self, unit='channel'):
    868850        """\
     
    883865        self._add_history("set_unit", varlist)
    884866
    885     @asaplog_post_dec
     867    @print_log_dec
    886868    def set_instrument(self, instr):
    887869        """\
     
    896878        self._setInstrument(instr)
    897879        self._add_history("set_instument", vars())
    898 
    899     @asaplog_post_dec
     880        print_log()
     881
     882    @print_log_dec
    900883    def set_feedtype(self, feedtype):
    901884        """\
     
    909892        self._setfeedtype(feedtype)
    910893        self._add_history("set_feedtype", vars())
    911 
    912     @asaplog_post_dec
     894        print_log()
     895
     896    @print_log_dec
    913897    def set_doppler(self, doppler='RADIO'):
    914898        """\
     
    925909        self._setcoordinfo(inf)
    926910        self._add_history("set_doppler", vars())
    927 
    928     @asaplog_post_dec
     911        print_log()
     912
     913    @print_log_dec
    929914    def set_freqframe(self, frame=None):
    930915        """\
     
    957942        else:
    958943            msg  = "Please specify a valid freq type. Valid types are:\n", valid
    959             raise TypeError(msg)
    960 
    961     @asaplog_post_dec
     944            if rcParams['verbose']:
     945                #print msg
     946                asaplog.push( msg )
     947                print_log( 'ERROR' )
     948            else:
     949                raise TypeError(msg)
     950        print_log()
     951
    962952    def set_dirframe(self, frame=""):
    963953        """\
     
    975965        """
    976966        varlist = vars()
    977         Scantable.set_dirframe(self, frame)
     967        try:
     968            Scantable.set_dirframe(self, frame)
     969        except RuntimeError, msg:
     970            if rcParams['verbose']:
     971                #print msg
     972                print_log()
     973                asaplog.push( str(msg) )
     974                print_log( 'ERROR' )
     975            else:
     976                raise
    978977        self._add_history("set_dirframe", varlist)
    979978
     
    992991        return unit
    993992
    994     @asaplog_post_dec
    995993    def get_abcissa(self, rowno=0):
    996994        """\
     
    10101008        abc = self._getabcissa(rowno)
    10111009        lbl = self._getabcissalabel(rowno)
     1010        print_log()
    10121011        return abc, lbl
    10131012
    1014     @asaplog_post_dec
    10151013    def flag(self, mask=None, unflag=False):
    10161014        """\
     
    10211019            mask:   an optional channel mask, created with create_mask. Default
    10221020                    (no mask) is all channels.
    1023 
    10241021            unflag:    if True, unflag the data
    10251022
     
    10271024        varlist = vars()
    10281025        mask = mask or []
    1029         self._flag(mask, unflag)
     1026        try:
     1027            self._flag(mask, unflag)
     1028        except RuntimeError, msg:
     1029            if rcParams['verbose']:
     1030                #print msg
     1031                print_log()
     1032                asaplog.push( str(msg) )
     1033                print_log( 'ERROR' )
     1034                return
     1035            else: raise
    10301036        self._add_history("flag", varlist)
    10311037
    1032     @asaplog_post_dec
    10331038    def flag_row(self, rows=[], unflag=False):
    10341039        """\
     
    10391044            rows:   list of row numbers to be flagged. Default is no row
    10401045                    (must be explicitly specified to execute row-based flagging).
    1041 
    10421046            unflag: if True, unflag the data.
    10431047
    10441048        """
    10451049        varlist = vars()
    1046         self._flag_row(rows, unflag)
     1050        try:
     1051            self._flag_row(rows, unflag)
     1052        except RuntimeError, msg:
     1053            if rcParams['verbose']:
     1054                print_log()
     1055                asaplog.push( str(msg) )
     1056                print_log('ERROR')
     1057                return
     1058            else: raise
    10471059        self._add_history("flag_row", varlist)
    10481060
    1049     @asaplog_post_dec
    10501061    def clip(self, uthres=None, dthres=None, clipoutside=True, unflag=False):
    10511062        """\
     
    10551066
    10561067            uthres:      upper threshold.
    1057 
    10581068            dthres:      lower threshold
    10591069
    10601070            clipoutside: True for flagging data outside the range [dthres:uthres].
    1061                          False for flagging data inside the range.
    1062 
     1071                         False for glagging data inside the range.
    10631072            unflag:      if True, unflag the data.
    10641073
    10651074        """
    10661075        varlist = vars()
    1067         self._clip(uthres, dthres, clipoutside, unflag)
     1076        try:
     1077            self._clip(uthres, dthres, clipoutside, unflag)
     1078        except RuntimeError, msg:
     1079            if rcParams['verbose']:
     1080                print_log()
     1081                asaplog.push(str(msg))
     1082                print_log('ERROR')
     1083                return
     1084            else: raise
    10681085        self._add_history("clip", varlist)
    10691086
    1070     @asaplog_post_dec
     1087    @print_log_dec
    10711088    def lag_flag(self, start, end, unit="MHz", insitu=None):
    10721089        """\
     
    10791096            start:    the start frequency (really a period within the
    10801097                      bandwidth)  or period to remove
    1081 
    10821098            end:      the end frequency or period to remove
    1083 
    10841099            unit:     the frequency unit (default "MHz") or "" for
    10851100                      explicit lag channels
     
    10971112        if not (unit == "" or base.has_key(unit)):
    10981113            raise ValueError("%s is not a valid unit." % unit)
    1099         if unit == "":
    1100             s = scantable(self._math._lag_flag(self, start, end, "lags"))
    1101         else:
    1102             s = scantable(self._math._lag_flag(self, start*base[unit],
    1103                                                end*base[unit], "frequency"))
     1114        try:
     1115            if unit == "":
     1116                s = scantable(self._math._lag_flag(self, start, end, "lags"))
     1117            else:
     1118                s = scantable(self._math._lag_flag(self, start*base[unit],
     1119                                                   end*base[unit], "frequency"))
     1120        except RuntimeError, msg:
     1121            if rcParams['verbose']:
     1122                #print msg
     1123                print_log()
     1124                asaplog.push( str(msg) )
     1125                print_log( 'ERROR' )
     1126                return
     1127            else: raise
    11041128        s._add_history("lag_flag", varlist)
     1129        print_log()
    11051130        if insitu:
    11061131            self._assign(s)
     
    11081133            return s
    11091134
    1110     @asaplog_post_dec
     1135    @print_log_dec
    11111136    def create_mask(self, *args, **kwargs):
    11121137        """\
     
    11201145                Pairs of start/end points (inclusive)specifying the regions
    11211146                to be masked
    1122 
    11231147            invert:     optional argument. If specified as True,
    11241148                        return an inverted mask, i.e. the regions
    11251149                        specified are EXCLUDED
    1126 
    11271150            row:        create the mask using the specified row for
    11281151                        unit conversions, default is row=0
     
    11501173        data = self._getabcissa(row)
    11511174        u = self._getcoordinfo()[0]
    1152         if u == "":
    1153             u = "channel"
    1154         msg = "The current mask window unit is %s" % u
    1155         i = self._check_ifs()
    1156         if not i:
    1157             msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
    1158         asaplog.push(msg)
     1175        if rcParams['verbose']:
     1176            if u == "": u = "channel"
     1177            msg = "The current mask window unit is %s" % u
     1178            i = self._check_ifs()
     1179            if not i:
     1180                msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
     1181            asaplog.push(msg)
    11591182        n = self.nchan()
    11601183        msk = _n_bools(n, False)
     
    11781201            if kwargs.get('invert'):
    11791202                msk = mask_not(msk)
     1203        print_log()
    11801204        return msk
    11811205
    1182     def get_masklist(self, mask=None, row=0, silent=False):
     1206    def get_masklist(self, mask=None, row=0):
    11831207        """\
    11841208        Compute and return a list of mask windows, [min, max].
     
    11871211
    11881212            mask:       channel mask, created with create_mask.
    1189 
    11901213            row:        calcutate the masklist using the specified row
    11911214                        for unit conversions, default is row=0
     
    12081231        data = self._getabcissa(row)
    12091232        u = self._getcoordinfo()[0]
    1210         if u == "":
    1211             u = "channel"
    1212         msg = "The current mask window unit is %s" % u
    1213         i = self._check_ifs()
    1214         if not i:
    1215             msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
    1216         if not silent:
     1233        if rcParams['verbose']:
     1234            if u == "": u = "channel"
     1235            msg = "The current mask window unit is %s" % u
     1236            i = self._check_ifs()
     1237            if not i:
     1238                msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
    12171239            asaplog.push(msg)
    12181240        masklist=[]
     
    12291251        """\
    12301252        Compute and Return lists of mask start indices and mask end indices.
    1231 
    1232         Parameters:
    1233 
     1253         Parameters:
    12341254            mask:       channel mask, created with create_mask.
    12351255
     
    13061326        """\
    13071327        Set or replace the restfrequency specified and
    1308         if the 'freqs' argument holds a scalar,
     1328        If the 'freqs' argument holds a scalar,
    13091329        then that rest frequency will be applied to all the selected
    13101330        data.  If the 'freqs' argument holds
     
    13221342
    13231343            freqs:   list of rest frequency values or string idenitfiers
    1324 
    13251344            unit:    unit for rest frequency (default 'Hz')
    13261345
     
    14331452        Scantable.shift_refpix(self, delta)
    14341453
    1435     @asaplog_post_dec
    14361454    def history(self, filename=None):
    14371455        """\
     
    14401458        Parameters:
    14411459
    1442             filename:    The name of the file to save the history to.
     1460            filename:    The name  of the file to save the history to.
    14431461
    14441462        """
     
    14471465        for h in hist:
    14481466            if h.startswith("---"):
    1449                 out = "\n".join([out, h])
     1467                out += "\n"+h
    14501468            else:
    14511469                items = h.split("##")
     
    14561474                out += "Function: %s\n  Parameters:" % (func)
    14571475                for i in items:
    1458                     if i == '':
    1459                         continue
    14601476                    s = i.split("=")
    14611477                    out += "\n   %s = %s" % (s[0], s[1])
    1462                 out = "\n".join([out, "-"*80])
     1478                out += "\n"+"-"*80
    14631479        if filename is not None:
    14641480            if filename is "":
     
    14721488            else:
    14731489                msg = "Illegal file name '%s'." % (filename)
    1474                 raise IOError(msg)
    1475         return page(out)
     1490                if rcParams['verbose']:
     1491                    #print msg
     1492                    asaplog.push( msg )
     1493                    print_log( 'ERROR' )
     1494                else:
     1495                    raise IOError(msg)
     1496        if rcParams['verbose']:
     1497            try:
     1498                from IPython.genutils import page as pager
     1499            except ImportError:
     1500                from pydoc import pager
     1501            pager(out)
     1502        else:
     1503            return out
     1504        return
    14761505    #
    14771506    # Maths business
    14781507    #
    1479     @asaplog_post_dec
     1508    @print_log_dec
    14801509    def average_time(self, mask=None, scanav=False, weight='tint', align=False):
    14811510        """\
     
    14901519            mask:     an optional mask (only used for 'var' and 'tsys'
    14911520                      weighting)
    1492 
    14931521            scanav:   True averages each scan separately
    14941522                      False (default) averages all scans together,
    1495 
    14961523            weight:   Weighting scheme.
    14971524                      'none'     (mean no weight)
     
    15021529                      'median'   ( median averaging)
    15031530                      The default is 'tint'
    1504 
    15051531            align:    align the spectra in velocity before averaging. It takes
    15061532                      the time of the first spectrum as reference time.
     
    15171543        scanav = (scanav and 'SCAN') or 'NONE'
    15181544        scan = (self, )
    1519 
    1520         if align:
    1521             scan = (self.freq_align(insitu=False), )
    1522         s = None
    1523         if weight.upper() == 'MEDIAN':
    1524             s = scantable(self._math._averagechannel(scan[0], 'MEDIAN',
    1525                                                      scanav))
    1526         else:
    1527             s = scantable(self._math._average(scan, mask, weight.upper(),
    1528                           scanav))
     1545        try:
     1546            if align:
     1547                scan = (self.freq_align(insitu=False), )
     1548            s = None
     1549            if weight.upper() == 'MEDIAN':
     1550                s = scantable(self._math._averagechannel(scan[0], 'MEDIAN',
     1551                                                         scanav))
     1552            else:
     1553                s = scantable(self._math._average(scan, mask, weight.upper(),
     1554                              scanav))
     1555        except RuntimeError, msg:
     1556            if rcParams['verbose']:
     1557                #print msg
     1558                print_log()
     1559                asaplog.push( str(msg) )
     1560                print_log( 'ERROR' )
     1561                return
     1562            else: raise
    15291563        s._add_history("average_time", varlist)
     1564        print_log()
    15301565        return s
    15311566
    1532     @asaplog_post_dec
     1567    @print_log_dec
    15331568    def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None):
    15341569        """\
     
    15431578
    15441579            jyperk:      the Jy / K conversion factor
    1545 
    15461580            eta:         the aperture efficiency
    1547 
    1548             d:           the geometric diameter (metres)
    1549 
     1581            d:           the geomtric diameter (metres)
    15501582            insitu:      if False a new scantable is returned.
    15511583                         Otherwise, the scaling is done in-situ
     
    15611593        s = scantable(self._math._convertflux(self, d, eta, jyperk))
    15621594        s._add_history("convert_flux", varlist)
     1595        print_log()
    15631596        if insitu: self._assign(s)
    15641597        else: return s
    15651598
    1566     @asaplog_post_dec
     1599    @print_log_dec
    15671600    def gain_el(self, poly=None, filename="", method="linear", insitu=None):
    15681601        """\
     
    15811614                         gain-elevation correction as a function of
    15821615                         elevation (in degrees).
    1583 
    15841616            filename:    The name of an ascii file holding correction factors.
    15851617                         The first row of the ascii file must give the column
     
    16001632                         0.5 80 0.8
    16011633                         0.6 90 0.75
    1602 
    16031634            method:      Interpolation method when correcting from a table.
    16041635                         Values are  "nearest", "linear" (default), "cubic"
    16051636                         and "spline"
    1606 
    16071637            insitu:      if False a new scantable is returned.
    16081638                         Otherwise, the scaling is done in-situ
     
    16191649        s = scantable(self._math._gainel(self, poly, filename, method))
    16201650        s._add_history("gain_el", varlist)
     1651        print_log()
    16211652        if insitu:
    16221653            self._assign(s)
     
    16241655            return s
    16251656
    1626     @asaplog_post_dec
     1657    @print_log_dec
    16271658    def freq_align(self, reftime=None, method='cubic', insitu=None):
    16281659        """\
     
    16321663
    16331664        Parameters:
    1634 
    16351665            reftime:     reference time to align at. By default, the time of
    16361666                         the first row of data is used.
    1637 
    16381667            method:      Interpolation method for regridding the spectra.
    16391668                         Choose from "nearest", "linear", "cubic" (default)
    16401669                         and "spline"
    1641 
    16421670            insitu:      if False a new scantable is returned.
    16431671                         Otherwise, the scaling is done in-situ
     
    16511679        s = scantable(self._math._freq_align(self, reftime, method))
    16521680        s._add_history("freq_align", varlist)
     1681        print_log()
    16531682        if insitu: self._assign(s)
    16541683        else: return s
    16551684
    1656     @asaplog_post_dec
     1685    @print_log_dec
    16571686    def opacity(self, tau=None, insitu=None):
    16581687        """\
     
    16611690
    16621691        Parameters:
    1663 
    16641692            tau:         (list of) opacity from which the correction factor is
    16651693                         exp(tau*ZD)
     
    16701698                         if tau is `None` the opacities are determined from a
    16711699                         model.
    1672 
    16731700            insitu:      if False a new scantable is returned.
    16741701                         Otherwise, the scaling is done in-situ
     
    16831710        s = scantable(self._math._opacity(self, tau))
    16841711        s._add_history("opacity", varlist)
     1712        print_log()
    16851713        if insitu: self._assign(s)
    16861714        else: return s
    16871715
    1688     @asaplog_post_dec
     1716    @print_log_dec
    16891717    def bin(self, width=5, insitu=None):
    16901718        """\
     
    16941722
    16951723            width:       The bin width (default=5) in pixels
    1696 
    16971724            insitu:      if False a new scantable is returned.
    16981725                         Otherwise, the scaling is done in-situ
     
    17051732        s = scantable(self._math._bin(self, width))
    17061733        s._add_history("bin", varlist)
     1734        print_log()
    17071735        if insitu:
    17081736            self._assign(s)
     
    17101738            return s
    17111739
    1712     @asaplog_post_dec
     1740    @print_log_dec
    17131741    def resample(self, width=5, method='cubic', insitu=None):
    17141742        """\
     
    17181746
    17191747            width:       The bin width (default=5) in pixels
    1720 
    17211748            method:      Interpolation method when correcting from a table.
    17221749                         Values are  "nearest", "linear", "cubic" (default)
    17231750                         and "spline"
    1724 
    17251751            insitu:      if False a new scantable is returned.
    17261752                         Otherwise, the scaling is done in-situ
     
    17331759        s = scantable(self._math._resample(self, method, width))
    17341760        s._add_history("resample", varlist)
     1761        print_log()
    17351762        if insitu: self._assign(s)
    17361763        else: return s
    17371764
    1738     @asaplog_post_dec
     1765    @print_log_dec
    17391766    def average_pol(self, mask=None, weight='none'):
    17401767        """\
     
    17461773                         averaging will be applied. The output will have all
    17471774                         specified points masked.
    1748 
    17491775            weight:      Weighting scheme. 'none' (default), 'var' (1/var(spec)
    17501776                         weighted), or 'tsys' (1/Tsys**2 weighted)
     
    17551781        s = scantable(self._math._averagepol(self, mask, weight.upper()))
    17561782        s._add_history("average_pol", varlist)
     1783        print_log()
    17571784        return s
    17581785
    1759     @asaplog_post_dec
     1786    @print_log_dec
    17601787    def average_beam(self, mask=None, weight='none'):
    17611788        """\
     
    17661793                         averaging will be applied. The output will have all
    17671794                         specified points masked.
    1768 
    17691795            weight:      Weighting scheme. 'none' (default), 'var' (1/var(spec)
    17701796                         weighted), or 'tsys' (1/Tsys**2 weighted)
     
    17751801        s = scantable(self._math._averagebeams(self, mask, weight.upper()))
    17761802        s._add_history("average_beam", varlist)
     1803        print_log()
    17771804        return s
    17781805
     
    17831810
    17841811        Parameters:
    1785 
    17861812            pflag:  Bool indicating whether to turn this on (True) or
    17871813                    off (False)
     
    17921818        self._add_history("parallactify", varlist)
    17931819
    1794     @asaplog_post_dec
     1820    @print_log_dec
    17951821    def convert_pol(self, poltype=None):
    17961822        """\
     
    17991825
    18001826        Parameters:
    1801 
    18021827            poltype:    The new polarisation type. Valid types are:
    18031828                        "linear", "circular", "stokes" and "linpol"
     
    18051830        """
    18061831        varlist = vars()
    1807         s = scantable(self._math._convertpol(self, poltype))
     1832        try:
     1833            s = scantable(self._math._convertpol(self, poltype))
     1834        except RuntimeError, msg:
     1835            if rcParams['verbose']:
     1836                #print msg
     1837                print_log()
     1838                asaplog.push( str(msg) )
     1839                print_log( 'ERROR' )
     1840                return
     1841            else:
     1842                raise
    18081843        s._add_history("convert_pol", varlist)
     1844        print_log()
    18091845        return s
    18101846
    1811     @asaplog_post_dec
     1847    @print_log_dec
    18121848    def smooth(self, kernel="hanning", width=5.0, order=2, plot=False, insitu=None):
    18131849        """\
     
    18191855                        'hanning' (default), 'gaussian', 'boxcar', 'rmedian'
    18201856                        or 'poly'
    1821 
    18221857            width:      The width of the kernel in pixels. For hanning this is
    18231858                        ignored otherwise it defauls to 5 pixels.
     
    18251860                        Maximum. For 'boxcar' it is the full width.
    18261861                        For 'rmedian' and 'poly' it is the half width.
    1827 
    18281862            order:      Optional parameter for 'poly' kernel (default is 2), to
    18291863                        specify the order of the polnomial. Ignored by all other
    18301864                        kernels.
    1831 
    18321865            plot:       plot the original and the smoothed spectra.
    18331866                        In this each indivual fit has to be approved, by
    18341867                        typing 'y' or 'n'
    1835 
    18361868            insitu:     if False a new scantable is returned.
    18371869                        Otherwise, the scaling is done in-situ
     
    18841916            del orgscan
    18851917
     1918        print_log()
    18861919        if insitu: self._assign(s)
    18871920        else: return s
    18881921
    1889     @asaplog_post_dec
    1890     def old_poly_baseline(self, mask=None, order=0, plot=False, uselin=False, insitu=None, rows=None):
     1922    @print_log_dec
     1923    def poly_baseline(self, mask=None, order=0, plot=False, uselin=False,
     1924                      insitu=None):
    18911925        """\
    18921926        Return a scan which has been baselined (all rows) by a polynomial.
    1893        
     1927
    18941928        Parameters:
    18951929
    18961930            mask:       an optional mask
    1897 
    18981931            order:      the order of the polynomial (default is 0)
    1899 
    19001932            plot:       plot the fit and the residual. In this each
    19011933                        indivual fit has to be approved, by typing 'y'
    19021934                        or 'n'
    1903 
    19041935            uselin:     use linear polynomial fit
    1905 
    19061936            insitu:     if False a new scantable is returned.
    19071937                        Otherwise, the scaling is done in-situ
    19081938                        The default is taken from .asaprc (False)
    19091939
    1910             rows:       row numbers of spectra to be processed.
    1911                         (default is None: for all rows)
    1912        
    1913         Example:
     1940        Example::
     1941
    19141942            # return a scan baselined by a third order polynomial,
    19151943            # not using a mask
     
    19241952        varlist = vars()
    19251953        if mask is None:
    1926             mask = [True for i in xrange(self.nchan())]
    1927 
     1954            mask = [True for i in xrange(self.nchan(-1))]
     1955
     1956        from asap.asapfitter import fitter
    19281957        try:
    19291958            f = fitter()
     
    19331962                f.set_function(poly=order)
    19341963
    1935             if rows == None:
    1936                 rows = xrange(workscan.nrow())
    1937             elif isinstance(rows, int):
    1938                 rows = [ rows ]
    1939            
     1964            rows = range(workscan.nrow())
    19401965            if len(rows) > 0:
    19411966                self.blpars = []
    1942                 self.masklists = []
    1943                 self.actualmask = []
    1944            
     1967
    19451968            for r in rows:
     1969                # take into account flagtra info (CAS-1434)
     1970                flagtra = workscan._getmask(r)
     1971                actualmask = mask[:]
     1972                if len(actualmask) == 0:
     1973                    actualmask = list(flagtra[:])
     1974                else:
     1975                    if len(actualmask) != len(flagtra):
     1976                        raise RuntimeError, "Mask and flagtra have different length"
     1977                    else:
     1978                        for i in range(0, len(actualmask)):
     1979                            actualmask[i] = actualmask[i] and flagtra[i]
     1980                f.set_scan(workscan, actualmask)
    19461981                f.x = workscan._getabcissa(r)
    19471982                f.y = workscan._getspectrum(r)
    1948                 f.mask = mask_and(mask, workscan._getmask(r))    # (CAS-1434)
    19491983                f.data = None
    19501984                f.fit()
     
    19541988                    if x.upper() == 'N':
    19551989                        self.blpars.append(None)
    1956                         self.masklists.append(None)
    1957                         self.actualmask.append(None)
    19581990                        continue
    19591991                workscan._setspectrum(f.fitter.getresidual(), r)
    19601992                self.blpars.append(f.get_parameters())
    1961                 self.masklists.append(workscan.get_masklist(f.mask, row=r, silent=True))
    1962                 self.actualmask.append(f.mask)
    19631993
    19641994            if plot:
     
    19661996                f._p = None
    19671997            workscan._add_history("poly_baseline", varlist)
    1968             if insitu:
    1969                 self._assign(workscan)
    1970             else:
    1971                 return workscan
     1998            print_log()
     1999            if insitu: self._assign(workscan)
     2000            else: return workscan
    19722001        except RuntimeError:
    19732002            msg = "The fit failed, possibly because it didn't converge."
    1974             raise RuntimeError(msg)
    1975 
    1976     @asaplog_post_dec
    1977     def poly_baseline(self, mask=None, order=0, plot=False, batch=False, insitu=None, rows=None):
    1978         """\
    1979         Return a scan which has been baselined (all rows) by a polynomial.
    1980         Parameters:
    1981             mask:       an optional mask
    1982             order:      the order of the polynomial (default is 0)
    1983             plot:       plot the fit and the residual. In this each
    1984                         indivual fit has to be approved, by typing 'y'
    1985                         or 'n'. Ignored if batch = True.
    1986             batch:      if True a faster algorithm is used and logs
    1987                         including the fit results are not output
    1988                         (default is False)
    1989             insitu:     if False a new scantable is returned.
    1990                         Otherwise, the scaling is done in-situ
    1991                         The default is taken from .asaprc (False)
    1992             rows:       row numbers of spectra to be baselined.
    1993                         (default is None: for all rows)
    1994         Example:
    1995             # return a scan baselined by a third order polynomial,
    1996             # not using a mask
    1997             bscan = scan.poly_baseline(order=3)
    1998         """
    1999        
    2000         varlist = vars()
    2001        
    2002         if insitu is None: insitu = rcParams["insitu"]
    2003         if insitu:
    2004             workscan = self
    2005         else:
    2006             workscan = self.copy()
    2007 
    2008         nchan = workscan.nchan()
    2009        
    2010         if mask is None:
    2011             mask = [True for i in xrange(nchan)]
    2012 
    2013         try:
    2014             if rows == None:
    2015                 rows = xrange(workscan.nrow())
    2016             elif isinstance(rows, int):
    2017                 rows = [ rows ]
    2018            
    2019             if len(rows) > 0:
    2020                 workscan.blpars = []
    2021                 workscan.masklists = []
    2022                 workscan.actualmask = []
    2023 
    2024             if batch:
    2025                 workscan._poly_baseline_batch(mask, order)
    2026             elif plot:
    2027                 f = fitter()
    2028                 f.set_function(lpoly=order)
    2029                 for r in rows:
    2030                     f.x = workscan._getabcissa(r)
    2031                     f.y = workscan._getspectrum(r)
    2032                     f.mask = mask_and(mask, workscan._getmask(r))    # (CAS-1434)
    2033                     f.data = None
    2034                     f.fit()
    2035                    
    2036                     f.plot(residual=True)
    2037                     accept_fit = raw_input("Accept fit ( [y]/n ): ")
    2038                     if accept_fit.upper() == "N":
    2039                         self.blpars.append(None)
    2040                         self.masklists.append(None)
    2041                         self.actualmask.append(None)
    2042                         continue
    2043                     workscan._setspectrum(f.fitter.getresidual(), r)
    2044                     workscan.blpars.append(f.get_parameters())
    2045                     workscan.masklists.append(workscan.get_masklist(f.mask, row=r))
    2046                     workscan.actualmask.append(f.mask)
    2047                    
    2048                 f._p.unmap()
    2049                 f._p = None
    2050             else:
    2051                 for r in rows:
    2052                     fitparams = workscan._poly_baseline(mask, order, r)
    2053                     params = fitparams.getparameters()
    2054                     fmtd = ", ".join(["p%d = %3.6f" % (i, v) for i, v in enumerate(params)])
    2055                     errors = fitparams.geterrors()
    2056                     fmask = mask_and(mask, workscan._getmask(r))
    2057 
    2058                     workscan.blpars.append({"params":params,
    2059                                             "fixed": fitparams.getfixedparameters(),
    2060                                             "formatted":fmtd, "errors":errors})
    2061                     workscan.masklists.append(workscan.get_masklist(fmask, r, silent=True))
    2062                     workscan.actualmask.append(fmask)
    2063                    
    2064                     asaplog.push(fmtd)
    2065            
    2066             workscan._add_history("poly_baseline", varlist)
    2067            
    2068             if insitu:
    2069                 self._assign(workscan)
    2070             else:
    2071                 return workscan
    2072            
    2073         except RuntimeError, e:
    2074             msg = "The fit failed, possibly because it didn't converge."
    2075             if rcParams["verbose"]:
    2076                 asaplog.push(str(e))
    2077                 asaplog.push(str(msg))
     2003            if rcParams['verbose']:
     2004                #print msg
     2005                print_log()
     2006                asaplog.push( str(msg) )
     2007                print_log( 'ERROR' )
    20782008                return
    20792009            else:
    2080                 raise RuntimeError(str(e)+'\n'+msg)
    2081 
    2082 
    2083     def auto_poly_baseline(self, mask=None, edge=(0, 0), order=0,
     2010                raise RuntimeError(msg)
     2011
     2012
     2013    def auto_poly_baseline(self, mask=[], edge=(0, 0), order=0,
    20842014                           threshold=3, chan_avg_limit=1, plot=False,
    2085                            insitu=None, rows=None):
     2015                           insitu=None):
    20862016        """\
    20872017        Return a scan which has been baselined (all rows) by a polynomial.
     
    21242054                        Otherwise, the scaling is done in-situ
    21252055                        The default is taken from .asaprc (False)
    2126             rows:       row numbers of spectra to be processed.
    2127                         (default is None: for all rows)
    21282056
    21292057
     
    21352063        if insitu is None: insitu = rcParams['insitu']
    21362064        varlist = vars()
     2065        from asap.asapfitter import fitter
    21372066        from asap.asaplinefind import linefinder
    21382067        from asap import _is_sequence_or_number as _is_valid
     
    21582087            curedge = edge;
    21592088
    2160         if not insitu:
    2161             workscan = self.copy()
    2162         else:
    2163             workscan = self
    2164 
    21652089        # setup fitter
    21662090        f = fitter()
    2167         f.set_function(lpoly=order)
     2091        f.set_function(poly=order)
    21682092
    21692093        # setup line finder
     
    21712095        fl.set_options(threshold=threshold,avg_limit=chan_avg_limit)
    21722096
     2097        if not insitu:
     2098            workscan = self.copy()
     2099        else:
     2100            workscan = self
     2101
    21732102        fl.set_scan(workscan)
    21742103
    2175         if mask is None:
    2176             mask = _n_bools(workscan.nchan(), True)
    2177        
    2178         if rows is None:
    2179             rows = xrange(workscan.nrow())
    2180         elif isinstance(rows, int):
    2181             rows = [ rows ]
    2182        
     2104        rows = range(workscan.nrow())
    21832105        # Save parameters of baseline fits & masklists as a class attribute.
    21842106        # NOTICE: It does not reflect changes in scantable!
     
    21862108            self.blpars=[]
    21872109            self.masklists=[]
    2188             self.actualmask=[]
    21892110        asaplog.push("Processing:")
    21902111        for r in rows:
     
    22012122                    curedge = edge[workscan.getif(r)]
    22022123
    2203             actualmask = mask_and(mask, workscan._getmask(r))    # (CAS-1434)
     2124            # take into account flagtra info (CAS-1434)
     2125            flagtra = workscan._getmask(r)
     2126            actualmask = mask[:]
     2127            if len(actualmask) == 0:
     2128                actualmask = list(flagtra[:])
     2129            else:
     2130                if len(actualmask) != len(flagtra):
     2131                    raise RuntimeError, "Mask and flagtra have different length"
     2132                else:
     2133                    for i in range(0, len(actualmask)):
     2134                        actualmask[i] = actualmask[i] and flagtra[i]
    22042135
    22052136            # setup line finder
    22062137            fl.find_lines(r, actualmask, curedge)
    2207            
     2138            outmask=fl.get_mask()
     2139            f.set_scan(workscan, fl.get_mask())
    22082140            f.x = workscan._getabcissa(r)
    22092141            f.y = workscan._getspectrum(r)
    2210             f.mask = fl.get_mask()
    22112142            f.data = None
    22122143            f.fit()
    22132144
    22142145            # Show mask list
    2215             masklist=workscan.get_masklist(f.mask, row=r, silent=True)
     2146            masklist=workscan.get_masklist(fl.get_mask(),row=r)
    22162147            msg = "mask range: "+str(masklist)
    22172148            asaplog.push(msg, False)
     
    22232154                    self.blpars.append(None)
    22242155                    self.masklists.append(None)
    2225                     self.actualmask.append(None)
    22262156                    continue
    22272157
     
    22292159            self.blpars.append(f.get_parameters())
    22302160            self.masklists.append(masklist)
    2231             self.actualmask.append(f.mask)
    22322161        if plot:
    22332162            f._p.unmap()
     
    22392168            return workscan
    22402169
    2241     @asaplog_post_dec
     2170    @print_log_dec
    22422171    def rotate_linpolphase(self, angle):
    22432172        """\
     
    22582187        self._math._rotate_linpolphase(self, angle)
    22592188        self._add_history("rotate_linpolphase", varlist)
     2189        print_log()
    22602190        return
    22612191
    2262     @asaplog_post_dec
     2192    @print_log_dec
    22632193    def rotate_xyphase(self, angle):
    22642194        """\
     
    22792209        self._math._rotate_xyphase(self, angle)
    22802210        self._add_history("rotate_xyphase", varlist)
     2211        print_log()
    22812212        return
    22822213
    2283     @asaplog_post_dec
     2214    @print_log_dec
    22842215    def swap_linears(self):
    22852216        """\
     
    22902221        self._math._swap_linears(self)
    22912222        self._add_history("swap_linears", varlist)
     2223        print_log()
    22922224        return
    22932225
    2294     @asaplog_post_dec
     2226    @print_log_dec
    22952227    def invert_phase(self):
    22962228        """\
     
    23022234        return
    23032235
    2304     @asaplog_post_dec
     2236    @print_log_dec
    23052237    def add(self, offset, insitu=None):
    23062238        """\
     
    23102242
    23112243            offset:      the offset
    2312 
    23132244            insitu:      if False a new scantable is returned.
    23142245                         Otherwise, the scaling is done in-situ
     
    23262257            return s
    23272258
    2328     @asaplog_post_dec
     2259    @print_log_dec
    23292260    def scale(self, factor, tsys=True, insitu=None):
    23302261        """\
    23312262
    2332         Return a scan where all spectra are scaled by the given 'factor'
     2263        Return a scan where all spectra are scaled by the give 'factor'
    23332264
    23342265        Parameters:
    23352266
    23362267            factor:      the scaling factor (float or 1D float list)
    2337 
    23382268            insitu:      if False a new scantable is returned.
    23392269                         Otherwise, the scaling is done in-situ
    23402270                         The default is taken from .asaprc (False)
    2341 
    23422271            tsys:        if True (default) then apply the operation to Tsys
    23432272                         as well as the data
     
    23582287            s = scantable(self._math._unaryop(self.copy(), factor, "MUL", tsys))
    23592288        s._add_history("scale", varlist)
     2289        print_log()
    23602290        if insitu:
    23612291            self._assign(s)
     
    23722302
    23732303            match:          a Unix style pattern, regular expression or selector
    2374 
    23752304            matchtype:      'pattern' (default) UNIX style pattern or
    23762305                            'regex' regular expression
    2377 
    23782306            sourcetype:     the type of the source to use (source/reference)
    23792307
     
    24042332        self._add_history("set_sourcetype", varlist)
    24052333
    2406     @asaplog_post_dec
    2407     @preserve_selection
     2334    @print_log_dec
    24082335    def auto_quotient(self, preserve=True, mode='paired', verify=False):
    24092336        """\
     
    24162343            preserve:       you can preserve (default) the continuum or
    24172344                            remove it.  The equations used are
    2418 
    24192345                            preserve: Output = Toff * (on/off) - Toff
    2420 
    24212346                            remove:   Output = Toff * (on/off) - Ton
    2422 
    24232347            mode:           the on/off detection mode
    24242348                            'paired' (default)
     
    24302354                            finds the closest off in time
    24312355
    2432         .. todo:: verify argument is not implemented
    2433 
    2434         """
    2435         varlist = vars()
     2356        """
    24362357        modes = ["time", "paired"]
    24372358        if not mode in modes:
    24382359            msg = "please provide valid mode. Valid modes are %s" % (modes)
    24392360            raise ValueError(msg)
     2361        varlist = vars()
    24402362        s = None
    24412363        if mode.lower() == "paired":
    2442             sel = self.get_selection()
    2443             sel.set_query("SRCTYPE==psoff")
     2364            basesel = self.get_selection()
     2365            sel = selector()+basesel
     2366            sel.set_query("SRCTYPE==1")
    24442367            self.set_selection(sel)
    24452368            offs = self.copy()
    2446             sel.set_query("SRCTYPE==pson")
     2369            sel.set_query("SRCTYPE==0")
    24472370            self.set_selection(sel)
    24482371            ons = self.copy()
    24492372            s = scantable(self._math._quotient(ons, offs, preserve))
     2373            self.set_selection(basesel)
    24502374        elif mode.lower() == "time":
    24512375            s = scantable(self._math._auto_quotient(self, mode, preserve))
    24522376        s._add_history("auto_quotient", varlist)
     2377        print_log()
    24532378        return s
    24542379
    2455     @asaplog_post_dec
     2380    @print_log_dec
    24562381    def mx_quotient(self, mask = None, weight='median', preserve=True):
    24572382        """\
     
    24612386
    24622387            mask:           an optional mask to be used when weight == 'stddev'
    2463 
    24642388            weight:         How to average the off beams.  Default is 'median'.
    2465 
    24662389            preserve:       you can preserve (default) the continuum or
    2467                             remove it.  The equations used are:
    2468 
    2469                                 preserve: Output = Toff * (on/off) - Toff
    2470 
    2471                                 remove:   Output = Toff * (on/off) - Ton
     2390                            remove it.  The equations used are
     2391                            preserve: Output = Toff * (on/off) - Toff
     2392                            remove:   Output = Toff * (on/off) - Ton
    24722393
    24732394        """
     
    24802401        q = quotient(on, off, preserve)
    24812402        q._add_history("mx_quotient", varlist)
     2403        print_log()
    24822404        return q
    24832405
    2484     @asaplog_post_dec
     2406    @print_log_dec
    24852407    def freq_switch(self, insitu=None):
    24862408        """\
     
    24992421        s = scantable(self._math._freqswitch(self))
    25002422        s._add_history("freq_switch", varlist)
    2501         if insitu:
    2502             self._assign(s)
    2503         else:
    2504             return s
    2505 
    2506     @asaplog_post_dec
     2423        print_log()
     2424        if insitu: self._assign(s)
     2425        else: return s
     2426
     2427    @print_log_dec
    25072428    def recalc_azel(self):
    25082429        """Recalculate the azimuth and elevation for each position."""
     
    25102431        self._recalcazel()
    25112432        self._add_history("recalc_azel", varlist)
     2433        print_log()
    25122434        return
    25132435
    2514     @asaplog_post_dec
     2436    @print_log_dec
    25152437    def __add__(self, other):
    25162438        varlist = vars()
     
    25252447        return s
    25262448
    2527     @asaplog_post_dec
     2449    @print_log_dec
    25282450    def __sub__(self, other):
    25292451        """
     
    25412463        return s
    25422464
    2543     @asaplog_post_dec
     2465    @print_log_dec
    25442466    def __mul__(self, other):
    25452467        """
     
    25582480
    25592481
    2560     @asaplog_post_dec
     2482    @print_log_dec
    25612483    def __div__(self, other):
    25622484        """
     
    25762498        return s
    25772499
    2578     @asaplog_post_dec
    25792500    def get_fit(self, row=0):
    25802501        """\
     
    25902511        from asap.asapfit import asapfit
    25912512        fit = asapfit(self._getfit(row))
    2592         asaplog.push( '%s' %(fit) )
    2593         return fit.as_dict()
     2513        if rcParams['verbose']:
     2514            #print fit
     2515            asaplog.push( '%s' %(fit) )
     2516            print_log()
     2517            return
     2518        else:
     2519            return fit.as_dict()
    25942520
    25952521    def flag_nans(self):
     
    26852611        return (sum(nchans)/len(nchans) == nchans[0])
    26862612
    2687     @asaplog_post_dec
    2688     #def _fill(self, names, unit, average, getpt, antenna):
    2689     def _fill(self, names, unit, average, opts={}):
     2613    def _fill(self, names, unit, average, getpt, antenna):
    26902614        first = True
    26912615        fullnames = []
     
    26952619            if not os.path.exists(name):
    26962620                msg = "File '%s' does not exists" % (name)
     2621                if rcParams['verbose']:
     2622                    asaplog.push(msg)
     2623                    print_log( 'ERROR' )
     2624                    return
    26972625                raise IOError(msg)
    26982626            fullnames.append(name)
     
    27072635            msg = "Importing %s..." % (name)
    27082636            asaplog.push(msg, False)
    2709             #opts = {'ms': {'antenna' : antenna, 'getpt': getpt} }
    2710             r.open(name, opts)# antenna, -1, -1, getpt)
     2637            print_log()
     2638            r.open(name)# antenna, -1, -1, getpt)
    27112639            r.fill()
    27122640            if average:
     
    27182646            del r, tbl
    27192647            first = False
    2720             #flush log
    2721         asaplog.post()
    27222648        if unit is not None:
    27232649            self.set_fluxunit(unit)
Note: See TracChangeset for help on using the changeset viewer.