Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/scantable.py

    r1846 r1948  
    22
    33import os
     4import numpy
    45try:
    56    from functools import wraps as wraps_dec
     
    1112from asap._asap import filler
    1213from asap.parameters import rcParams
    13 from asap.logging import asaplog, print_log, print_log_dec
     14from asap.logging import asaplog, asaplog_post_dec
    1415from asap.selector import selector
    1516from asap.linecatalog import linecatalog
    1617from asap.coordinate import coordinate
    17 from asap.utils import _n_bools, mask_not, mask_and, mask_or
     18from asap.utils import _n_bools, mask_not, mask_and, mask_or, page
     19from asap.asapfitter import fitter
    1820
    1921
     
    2224    def wrap(obj, *args, **kw):
    2325        basesel = obj.get_selection()
    24         val = func(obj, *args, **kw)
    25         obj.set_selection(basesel)
     26        try:
     27            val = func(obj, *args, **kw)
     28        finally:
     29            obj.set_selection(basesel)
    2630        return val
    2731    return wrap
     
    3539
    3640    """
    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 
     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
     58def 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   
    4279class scantable(Scantable):
    4380    """\
     
    4582    """
    4683
    47     @print_log_dec
    48     def __init__(self, filename, average=None, unit=None, getpt=None,
    49                  antenna=None, parallactify=None):
     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):
    5088        """\
    5189        Create a scantable from a saved one or make a reference
     
    73111                          the MS data faster in some cases.
    74112
    75             antenna:      Antenna selection. integer (id) or string (name or id).
     113            antenna:      for MeasurementSet input data only:
     114                          Antenna selection. integer (id) or string (name or id).
    76115
    77116            parallactify: Indicate that the data had been parallatified. Default
     
    81120        if average is None:
    82121            average = rcParams['scantable.autoaverage']
    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(',')
     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(',')
    105142        parallactify = parallactify or rcParams['scantable.parallactify']
    106143        varlist = vars()
     
    115152                if not os.path.exists(filename):
    116153                    s = "File '%s' not found." % (filename)
    117                     if rcParams['verbose']:
    118                         asaplog.push(s)
    119                         print_log('ERROR')
    120                         return
    121154                    raise IOError(s)
    122155                if is_scantable(filename):
     
    127160                    # do not reset to the default freqframe
    128161                    #self.set_freqframe(rcParams['scantable.freqframe'])
    129                 elif os.path.isdir(filename) \
    130                          and not os.path.exists(filename+'/table.f1'):
     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:
    131177                    msg = "The given file '%s'is not a valid " \
    132178                          "asap table." % (filename)
    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)
     179                    raise IOError(msg)
    142180            elif (isinstance(filename, list) or isinstance(filename, tuple)) \
    143181                  and isinstance(filename[-1], str):
    144                 self._fill(filename, unit, average, getpt, antenna)
     182                #self._fill(filename, unit, average, getpt, antenna)
     183                self._fill(filename, unit, average)
    145184        self.parallactify(parallactify)
    146185        self._add_history("scantable", varlist)
    147         print_log()
    148 
    149     @print_log_dec
     186
     187    @asaplog_post_dec
    150188    def save(self, name=None, format=None, overwrite=False):
    151189        """\
     
    158196                         this is the root file name (data in 'name'.txt
    159197                         and header in 'name'_header.txt)
     198
    160199            format:      an optional file format. Default is ASAP.
    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)
     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
    169209            overwrite:   If the file should be overwritten if it exists.
    170210                         The default False is to return with warning
    171211                         without writing the output. USE WITH CARE.
     212
    172213        Example::
    173214
     
    187228            if not overwrite:
    188229                msg = "File %s exists." % name
    189                 if rcParams['verbose']:
    190                     #print msg
    191                     asaplog.push( msg )
    192                     print_log( 'ERROR' )
    193                     return
    194                 else:
    195                     raise IOError(msg)
     230                raise IOError(msg)
    196231        format2 = format.upper()
    197232        if format2 == 'ASAP':
     
    201236            writer = stw(format2)
    202237            writer.write(self, name)
    203         print_log()
    204238        return
    205239
     
    233267        from asap import unique
    234268        if not _is_valid(scanid):
    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
     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)
    267277
    268278    def _select_copy(self, selection):
     
    274284
    275285    def get_scan(self, scanid=None):
    276         """
     286        """\
    277287        Return a specific scan (by scanno) or collection of scans (by
    278288        source name) in a new scantable.
     
    299309        """
    300310        if scanid is None:
    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 
     311            raise RuntimeError( 'Please specify a scan no or name to '
     312                                'retrieve from the scantable' )
    311313        try:
    312314            bsel = self.get_selection()
     
    323325            else:
    324326                msg = "Illegal scanid type, use 'int' or 'list' if ints."
    325                 if rcParams['verbose']:
    326                     #print msg
    327                     asaplog.push( msg )
    328                     print_log( 'ERROR' )
    329                 else:
    330                     raise TypeError(msg)
     327                raise TypeError(msg)
    331328        except RuntimeError:
    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
     329            raise
    338330
    339331    def __str__(self):
     
    362354            else:
    363355                msg = "Illegal file name '%s'." % (filename)
    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
     356                raise IOError(msg)
     357        return page(info)
    378358
    379359    def get_spectrum(self, rowno):
     
    398378
    399379    def set_spectrum(self, spec, rowno):
    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
     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
    406387
    407388        """
     
    517498            return workscan
    518499
    519     #def stats(self, stat='stddev', mask=None):
    520     def stats(self, stat='stddev', mask=None, form='3.3f'):
     500    @asaplog_post_dec
     501    def stats(self, stat='stddev', mask=None, form='3.3f', row=None):
    521502        """\
    522503        Determine the specified statistic of the current beam/if/pol
     
    528509            stat:    'min', 'max', 'min_abc', 'max_abc', 'sumsq', 'sum',
    529510                     'mean', 'var', 'stddev', 'avdev', 'rms', 'median'
     511
    530512            mask:    an optional mask specifying where the statistic
    531513                     should be determined.
     514
    532515            form:    format string to print statistic values
    533516
    534         Example::
    535 
     517            row:     row number of spectrum to process.
     518                     (default is None: for all rows)
     519
     520        Example:
    536521            scan.set_unit('channel')
    537522            msk = scan.create_mask([100, 200], [500, 600])
     
    551536            getchan = True
    552537            statvals = []
    553         if not rtnabc: statvals = self._math._stats(self, mask, stat)
     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))
    554543
    555544        #def cb(i):
     
    563552        #outvec = []
    564553        sep = '-'*50
    565         for i in range(self.nrow()):
     554
     555        if row == None:
     556            rows = xrange(self.nrow())
     557        elif isinstance(row, int):
     558            rows = [ row ]
     559
     560        for i in rows:
    566561            refstr = ''
    567562            statunit= ''
     
    579574            out += 'Scan[%d] (%s) ' % (self.getscan(i), src)
    580575            out += 'Time[%s]:\n' % (tm)
    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))
     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))
    585579            #outvec.append(callback(i))
    586             #out += ('= %'+form) % (outvec[i]) +'   '+refstr+'\n'
    587             out += ('= %'+form) % (statvals[i]) +'   '+refstr+'\n'
     580            if len(rows) > 1:
     581                # out += ('= %'+form) % (outvec[i]) +'   '+refstr+'\n'
     582                out += ('= %'+form) % (statvals[i]) +'   '+refstr+'\n'
     583            else:
     584                # out += ('= %'+form) % (outvec[0]) +'   '+refstr+'\n'
     585                out += ('= %'+form) % (statvals[0]) +'   '+refstr+'\n'
    588586            out +=  sep+"\n"
    589587
    590         if rcParams['verbose']:
    591             import os
    592             if os.environ.has_key( 'USER' ):
    593                 usr=os.environ['USER']
    594             else:
    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()
     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
    612606        return statvals
    613607
     
    621615            rowno:   a row number in the scantable. Default is the
    622616                     first row, i.e. rowno=0
     617
    623618            chan:    a channel in the scantable. Default is the first
    624619                     channel, i.e. pos=0
     
    723718            out += '= %3.3f\n' % (outvec[i])
    724719            out +=  sep+'\n'
    725         if rcParams['verbose']:
    726             asaplog.push(sep)
    727             asaplog.push(" %s" % (label))
    728             asaplog.push(sep)
    729             asaplog.push(out)
    730             print_log()
     720
     721        asaplog.push(sep)
     722        asaplog.push(" %s" % (label))
     723        asaplog.push(sep)
     724        asaplog.push(out)
     725        asaplog.post()
    731726        return outvec
    732727
    733     def _get_column(self, callback, row=-1):
     728    def _get_column(self, callback, row=-1, *args):
    734729        """
    735730        """
    736731        if row == -1:
    737             return [callback(i) for i in range(self.nrow())]
     732            return [callback(i, *args) for i in range(self.nrow())]
    738733        else:
    739734            if  0 <= row < self.nrow():
    740                 return callback(row)
    741 
    742 
    743     def get_time(self, row=-1, asdatetime=False):
     735                return callback(row, *args)
     736
     737
     738    def get_time(self, row=-1, asdatetime=False, prec=-1):
    744739        """\
    745740        Get a list of time stamps for the observations.
    746         Return a datetime object for each integration time stamp in the scantable.
     741        Return a datetime object or a string (default) for each
     742        integration time stamp in the scantable.
    747743
    748744        Parameters:
    749745
    750746            row:          row no of integration. Default -1 return all rows
     747
    751748            asdatetime:   return values as datetime objects rather than strings
    752749
    753         """
    754         from time import strptime
     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        """
    755757        from datetime import datetime
    756         times = self._get_column(self._gettime, row)
     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)
    757769        if not asdatetime:
    758770            return times
    759         format = "%Y/%m/%d/%H:%M:%S"
     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],"")
    760777        if isinstance(times, list):
    761             return [datetime(*strptime(i, format)[:6]) for i in times]
    762         else:
    763             return datetime(*strptime(times, format)[:6])
     778            return [datetime.strptime(i, format) for i in times]
     779        else:
     780            return datetime.strptime(times, format)
    764781
    765782
     
    827844        Get a list of Positions on the sky (direction) for the observations.
    828845        Return a string for each integration in the scantable.
    829         Parameters:
     846
     847        Parameters:
     848
    830849            row:    row no of integration. Default -1 return all rows
    831         Example:
    832             none
     850
    833851        """
    834852        return self._get_column(self._getdirection, row)
     
    846864        return self._get_column(self._getdirectionvec, row)
    847865
    848     @print_log_dec
     866    @asaplog_post_dec
    849867    def set_unit(self, unit='channel'):
    850868        """\
     
    865883        self._add_history("set_unit", varlist)
    866884
    867     @print_log_dec
     885    @asaplog_post_dec
    868886    def set_instrument(self, instr):
    869887        """\
     
    878896        self._setInstrument(instr)
    879897        self._add_history("set_instument", vars())
    880         print_log()
    881 
    882     @print_log_dec
     898
     899    @asaplog_post_dec
    883900    def set_feedtype(self, feedtype):
    884901        """\
     
    892909        self._setfeedtype(feedtype)
    893910        self._add_history("set_feedtype", vars())
    894         print_log()
    895 
    896     @print_log_dec
     911
     912    @asaplog_post_dec
    897913    def set_doppler(self, doppler='RADIO'):
    898914        """\
     
    909925        self._setcoordinfo(inf)
    910926        self._add_history("set_doppler", vars())
    911         print_log()
    912 
    913     @print_log_dec
     927
     928    @asaplog_post_dec
    914929    def set_freqframe(self, frame=None):
    915930        """\
     
    942957        else:
    943958            msg  = "Please specify a valid freq type. Valid types are:\n", valid
    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 
     959            raise TypeError(msg)
     960
     961    @asaplog_post_dec
    952962    def set_dirframe(self, frame=""):
    953963        """\
     
    965975        """
    966976        varlist = vars()
    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
     977        Scantable.set_dirframe(self, frame)
    977978        self._add_history("set_dirframe", varlist)
    978979
     
    991992        return unit
    992993
     994    @asaplog_post_dec
    993995    def get_abcissa(self, rowno=0):
    994996        """\
     
    10081010        abc = self._getabcissa(rowno)
    10091011        lbl = self._getabcissalabel(rowno)
    1010         print_log()
    10111012        return abc, lbl
    10121013
     1014    @asaplog_post_dec
    10131015    def flag(self, mask=None, unflag=False):
    10141016        """\
     
    10191021            mask:   an optional channel mask, created with create_mask. Default
    10201022                    (no mask) is all channels.
     1023
    10211024            unflag:    if True, unflag the data
    10221025
     
    10241027        varlist = vars()
    10251028        mask = mask or []
    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
     1029        self._flag(mask, unflag)
    10361030        self._add_history("flag", varlist)
    10371031
     1032    @asaplog_post_dec
    10381033    def flag_row(self, rows=[], unflag=False):
    10391034        """\
     
    10441039            rows:   list of row numbers to be flagged. Default is no row
    10451040                    (must be explicitly specified to execute row-based flagging).
     1041
    10461042            unflag: if True, unflag the data.
    10471043
    10481044        """
    10491045        varlist = vars()
    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
     1046        self._flag_row(rows, unflag)
    10591047        self._add_history("flag_row", varlist)
    10601048
     1049    @asaplog_post_dec
    10611050    def clip(self, uthres=None, dthres=None, clipoutside=True, unflag=False):
    10621051        """\
     
    10661055
    10671056            uthres:      upper threshold.
     1057
    10681058            dthres:      lower threshold
    10691059
    10701060            clipoutside: True for flagging data outside the range [dthres:uthres].
    1071                          False for glagging data inside the range.
     1061                         False for flagging data inside the range.
     1062
    10721063            unflag:      if True, unflag the data.
    10731064
    10741065        """
    10751066        varlist = vars()
    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
     1067        self._clip(uthres, dthres, clipoutside, unflag)
    10851068        self._add_history("clip", varlist)
    10861069
    1087     @print_log_dec
     1070    @asaplog_post_dec
    10881071    def lag_flag(self, start, end, unit="MHz", insitu=None):
    10891072        """\
     
    10961079            start:    the start frequency (really a period within the
    10971080                      bandwidth)  or period to remove
     1081
    10981082            end:      the end frequency or period to remove
     1083
    10991084            unit:     the frequency unit (default "MHz") or "" for
    11001085                      explicit lag channels
     
    11121097        if not (unit == "" or base.has_key(unit)):
    11131098            raise ValueError("%s is not a valid unit." % unit)
    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
     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"))
    11281104        s._add_history("lag_flag", varlist)
    1129         print_log()
    11301105        if insitu:
    11311106            self._assign(s)
     
    11331108            return s
    11341109
    1135     @print_log_dec
     1110    @asaplog_post_dec
    11361111    def create_mask(self, *args, **kwargs):
    11371112        """\
     
    11451120                Pairs of start/end points (inclusive)specifying the regions
    11461121                to be masked
     1122
    11471123            invert:     optional argument. If specified as True,
    11481124                        return an inverted mask, i.e. the regions
    11491125                        specified are EXCLUDED
     1126
    11501127            row:        create the mask using the specified row for
    11511128                        unit conversions, default is row=0
     
    11731150        data = self._getabcissa(row)
    11741151        u = self._getcoordinfo()[0]
    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)
     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)
    11821159        n = self.nchan()
    11831160        msk = _n_bools(n, False)
     
    12011178            if kwargs.get('invert'):
    12021179                msk = mask_not(msk)
    1203         print_log()
    12041180        return msk
    12051181
    1206     def get_masklist(self, mask=None, row=0):
     1182    def get_masklist(self, mask=None, row=0, silent=False):
    12071183        """\
    12081184        Compute and return a list of mask windows, [min, max].
     
    12111187
    12121188            mask:       channel mask, created with create_mask.
     1189
    12131190            row:        calcutate the masklist using the specified row
    12141191                        for unit conversions, default is row=0
     
    12311208        data = self._getabcissa(row)
    12321209        u = self._getcoordinfo()[0]
    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))
     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:
    12391217            asaplog.push(msg)
    12401218        masklist=[]
     
    12511229        """\
    12521230        Compute and Return lists of mask start indices and mask end indices.
    1253          Parameters:
     1231
     1232        Parameters:
     1233
    12541234            mask:       channel mask, created with create_mask.
    12551235
     
    13261306        """\
    13271307        Set or replace the restfrequency specified and
    1328         If the 'freqs' argument holds a scalar,
     1308        if the 'freqs' argument holds a scalar,
    13291309        then that rest frequency will be applied to all the selected
    13301310        data.  If the 'freqs' argument holds
     
    13421322
    13431323            freqs:   list of rest frequency values or string idenitfiers
     1324
    13441325            unit:    unit for rest frequency (default 'Hz')
    13451326
     
    14521433        Scantable.shift_refpix(self, delta)
    14531434
     1435    @asaplog_post_dec
    14541436    def history(self, filename=None):
    14551437        """\
     
    14581440        Parameters:
    14591441
    1460             filename:    The name  of the file to save the history to.
     1442            filename:    The name of the file to save the history to.
    14611443
    14621444        """
     
    14651447        for h in hist:
    14661448            if h.startswith("---"):
    1467                 out += "\n"+h
     1449                out = "\n".join([out, h])
    14681450            else:
    14691451                items = h.split("##")
     
    14741456                out += "Function: %s\n  Parameters:" % (func)
    14751457                for i in items:
     1458                    if i == '':
     1459                        continue
    14761460                    s = i.split("=")
    14771461                    out += "\n   %s = %s" % (s[0], s[1])
    1478                 out += "\n"+"-"*80
     1462                out = "\n".join([out, "-"*80])
    14791463        if filename is not None:
    14801464            if filename is "":
     
    14881472            else:
    14891473                msg = "Illegal file name '%s'." % (filename)
    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
     1474                raise IOError(msg)
     1475        return page(out)
    15051476    #
    15061477    # Maths business
    15071478    #
    1508     @print_log_dec
     1479    @asaplog_post_dec
    15091480    def average_time(self, mask=None, scanav=False, weight='tint', align=False):
    15101481        """\
     
    15191490            mask:     an optional mask (only used for 'var' and 'tsys'
    15201491                      weighting)
     1492
    15211493            scanav:   True averages each scan separately
    15221494                      False (default) averages all scans together,
     1495
    15231496            weight:   Weighting scheme.
    15241497                      'none'     (mean no weight)
     
    15291502                      'median'   ( median averaging)
    15301503                      The default is 'tint'
     1504
    15311505            align:    align the spectra in velocity before averaging. It takes
    15321506                      the time of the first spectrum as reference time.
     
    15431517        scanav = (scanav and 'SCAN') or 'NONE'
    15441518        scan = (self, )
    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
     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))
    15631529        s._add_history("average_time", varlist)
    1564         print_log()
    15651530        return s
    15661531
    1567     @print_log_dec
     1532    @asaplog_post_dec
    15681533    def convert_flux(self, jyperk=None, eta=None, d=None, insitu=None):
    15691534        """\
     
    15781543
    15791544            jyperk:      the Jy / K conversion factor
     1545
    15801546            eta:         the aperture efficiency
    1581             d:           the geomtric diameter (metres)
     1547
     1548            d:           the geometric diameter (metres)
     1549
    15821550            insitu:      if False a new scantable is returned.
    15831551                         Otherwise, the scaling is done in-situ
     
    15931561        s = scantable(self._math._convertflux(self, d, eta, jyperk))
    15941562        s._add_history("convert_flux", varlist)
    1595         print_log()
    15961563        if insitu: self._assign(s)
    15971564        else: return s
    15981565
    1599     @print_log_dec
     1566    @asaplog_post_dec
    16001567    def gain_el(self, poly=None, filename="", method="linear", insitu=None):
    16011568        """\
     
    16141581                         gain-elevation correction as a function of
    16151582                         elevation (in degrees).
     1583
    16161584            filename:    The name of an ascii file holding correction factors.
    16171585                         The first row of the ascii file must give the column
     
    16321600                         0.5 80 0.8
    16331601                         0.6 90 0.75
     1602
    16341603            method:      Interpolation method when correcting from a table.
    16351604                         Values are  "nearest", "linear" (default), "cubic"
    16361605                         and "spline"
     1606
    16371607            insitu:      if False a new scantable is returned.
    16381608                         Otherwise, the scaling is done in-situ
     
    16491619        s = scantable(self._math._gainel(self, poly, filename, method))
    16501620        s._add_history("gain_el", varlist)
    1651         print_log()
    16521621        if insitu:
    16531622            self._assign(s)
     
    16551624            return s
    16561625
    1657     @print_log_dec
     1626    @asaplog_post_dec
    16581627    def freq_align(self, reftime=None, method='cubic', insitu=None):
    16591628        """\
     
    16631632
    16641633        Parameters:
     1634
    16651635            reftime:     reference time to align at. By default, the time of
    16661636                         the first row of data is used.
     1637
    16671638            method:      Interpolation method for regridding the spectra.
    16681639                         Choose from "nearest", "linear", "cubic" (default)
    16691640                         and "spline"
     1641
    16701642            insitu:      if False a new scantable is returned.
    16711643                         Otherwise, the scaling is done in-situ
     
    16791651        s = scantable(self._math._freq_align(self, reftime, method))
    16801652        s._add_history("freq_align", varlist)
    1681         print_log()
    16821653        if insitu: self._assign(s)
    16831654        else: return s
    16841655
    1685     @print_log_dec
     1656    @asaplog_post_dec
    16861657    def opacity(self, tau=None, insitu=None):
    16871658        """\
     
    16901661
    16911662        Parameters:
     1663
    16921664            tau:         (list of) opacity from which the correction factor is
    16931665                         exp(tau*ZD)
     
    16981670                         if tau is `None` the opacities are determined from a
    16991671                         model.
     1672
    17001673            insitu:      if False a new scantable is returned.
    17011674                         Otherwise, the scaling is done in-situ
     
    17101683        s = scantable(self._math._opacity(self, tau))
    17111684        s._add_history("opacity", varlist)
    1712         print_log()
    17131685        if insitu: self._assign(s)
    17141686        else: return s
    17151687
    1716     @print_log_dec
     1688    @asaplog_post_dec
    17171689    def bin(self, width=5, insitu=None):
    17181690        """\
     
    17221694
    17231695            width:       The bin width (default=5) in pixels
     1696
    17241697            insitu:      if False a new scantable is returned.
    17251698                         Otherwise, the scaling is done in-situ
     
    17321705        s = scantable(self._math._bin(self, width))
    17331706        s._add_history("bin", varlist)
    1734         print_log()
    17351707        if insitu:
    17361708            self._assign(s)
     
    17381710            return s
    17391711
    1740     @print_log_dec
     1712    @asaplog_post_dec
    17411713    def resample(self, width=5, method='cubic', insitu=None):
    17421714        """\
     
    17461718
    17471719            width:       The bin width (default=5) in pixels
     1720
    17481721            method:      Interpolation method when correcting from a table.
    17491722                         Values are  "nearest", "linear", "cubic" (default)
    17501723                         and "spline"
     1724
    17511725            insitu:      if False a new scantable is returned.
    17521726                         Otherwise, the scaling is done in-situ
     
    17591733        s = scantable(self._math._resample(self, method, width))
    17601734        s._add_history("resample", varlist)
    1761         print_log()
    17621735        if insitu: self._assign(s)
    17631736        else: return s
    17641737
    1765     @print_log_dec
     1738    @asaplog_post_dec
    17661739    def average_pol(self, mask=None, weight='none'):
    17671740        """\
     
    17731746                         averaging will be applied. The output will have all
    17741747                         specified points masked.
     1748
    17751749            weight:      Weighting scheme. 'none' (default), 'var' (1/var(spec)
    17761750                         weighted), or 'tsys' (1/Tsys**2 weighted)
     
    17811755        s = scantable(self._math._averagepol(self, mask, weight.upper()))
    17821756        s._add_history("average_pol", varlist)
    1783         print_log()
    17841757        return s
    17851758
    1786     @print_log_dec
     1759    @asaplog_post_dec
    17871760    def average_beam(self, mask=None, weight='none'):
    17881761        """\
     
    17931766                         averaging will be applied. The output will have all
    17941767                         specified points masked.
     1768
    17951769            weight:      Weighting scheme. 'none' (default), 'var' (1/var(spec)
    17961770                         weighted), or 'tsys' (1/Tsys**2 weighted)
     
    18011775        s = scantable(self._math._averagebeams(self, mask, weight.upper()))
    18021776        s._add_history("average_beam", varlist)
    1803         print_log()
    18041777        return s
    18051778
     
    18101783
    18111784        Parameters:
     1785
    18121786            pflag:  Bool indicating whether to turn this on (True) or
    18131787                    off (False)
     
    18181792        self._add_history("parallactify", varlist)
    18191793
    1820     @print_log_dec
     1794    @asaplog_post_dec
    18211795    def convert_pol(self, poltype=None):
    18221796        """\
     
    18251799
    18261800        Parameters:
     1801
    18271802            poltype:    The new polarisation type. Valid types are:
    18281803                        "linear", "circular", "stokes" and "linpol"
     
    18301805        """
    18311806        varlist = vars()
    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
     1807        s = scantable(self._math._convertpol(self, poltype))
    18431808        s._add_history("convert_pol", varlist)
    1844         print_log()
    18451809        return s
    18461810
    1847     @print_log_dec
     1811    @asaplog_post_dec
    18481812    def smooth(self, kernel="hanning", width=5.0, order=2, plot=False, insitu=None):
    18491813        """\
     
    18551819                        'hanning' (default), 'gaussian', 'boxcar', 'rmedian'
    18561820                        or 'poly'
     1821
    18571822            width:      The width of the kernel in pixels. For hanning this is
    18581823                        ignored otherwise it defauls to 5 pixels.
     
    18601825                        Maximum. For 'boxcar' it is the full width.
    18611826                        For 'rmedian' and 'poly' it is the half width.
     1827
    18621828            order:      Optional parameter for 'poly' kernel (default is 2), to
    18631829                        specify the order of the polnomial. Ignored by all other
    18641830                        kernels.
     1831
    18651832            plot:       plot the original and the smoothed spectra.
    18661833                        In this each indivual fit has to be approved, by
    18671834                        typing 'y' or 'n'
     1835
    18681836            insitu:     if False a new scantable is returned.
    18691837                        Otherwise, the scaling is done in-situ
     
    19161884            del orgscan
    19171885
    1918         print_log()
    19191886        if insitu: self._assign(s)
    19201887        else: return s
    19211888
    1922     @print_log_dec
    1923     def poly_baseline(self, mask=None, order=0, plot=False, uselin=False,
    1924                       insitu=None):
     1889    @asaplog_post_dec
     1890    def old_poly_baseline(self, mask=None, order=0, plot=False, uselin=False, insitu=None, rows=None):
    19251891        """\
    19261892        Return a scan which has been baselined (all rows) by a polynomial.
    1927 
     1893       
    19281894        Parameters:
    19291895
    19301896            mask:       an optional mask
     1897
    19311898            order:      the order of the polynomial (default is 0)
     1899
    19321900            plot:       plot the fit and the residual. In this each
    19331901                        indivual fit has to be approved, by typing 'y'
    19341902                        or 'n'
     1903
    19351904            uselin:     use linear polynomial fit
     1905
    19361906            insitu:     if False a new scantable is returned.
    19371907                        Otherwise, the scaling is done in-situ
    19381908                        The default is taken from .asaprc (False)
    19391909
    1940         Example::
    1941 
     1910            rows:       row numbers of spectra to be processed.
     1911                        (default is None: for all rows)
     1912       
     1913        Example:
    19421914            # return a scan baselined by a third order polynomial,
    19431915            # not using a mask
     
    19521924        varlist = vars()
    19531925        if mask is None:
    1954             mask = [True for i in xrange(self.nchan(-1))]
    1955 
    1956         from asap.asapfitter import fitter
     1926            mask = [True for i in xrange(self.nchan())]
     1927
    19571928        try:
    19581929            f = fitter()
     
    19621933                f.set_function(poly=order)
    19631934
    1964             rows = range(workscan.nrow())
     1935            if rows == None:
     1936                rows = xrange(workscan.nrow())
     1937            elif isinstance(rows, int):
     1938                rows = [ rows ]
     1939           
    19651940            if len(rows) > 0:
    19661941                self.blpars = []
    1967 
     1942                self.masklists = []
     1943                self.actualmask = []
     1944           
    19681945            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)
    19811946                f.x = workscan._getabcissa(r)
    19821947                f.y = workscan._getspectrum(r)
     1948                f.mask = mask_and(mask, workscan._getmask(r))    # (CAS-1434)
    19831949                f.data = None
    19841950                f.fit()
     
    19881954                    if x.upper() == 'N':
    19891955                        self.blpars.append(None)
     1956                        self.masklists.append(None)
     1957                        self.actualmask.append(None)
    19901958                        continue
    19911959                workscan._setspectrum(f.fitter.getresidual(), r)
    19921960                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)
    19931963
    19941964            if plot:
     
    19961966                f._p = None
    19971967            workscan._add_history("poly_baseline", varlist)
    1998             print_log()
    1999             if insitu: self._assign(workscan)
    2000             else: return workscan
     1968            if insitu:
     1969                self._assign(workscan)
     1970            else:
     1971                return workscan
    20011972        except RuntimeError:
    20021973            msg = "The fit failed, possibly because it didn't converge."
    2003             if rcParams['verbose']:
    2004                 #print msg
    2005                 print_log()
    2006                 asaplog.push( str(msg) )
    2007                 print_log( 'ERROR' )
     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))
    20082078                return
    20092079            else:
    2010                 raise RuntimeError(msg)
    2011 
    2012 
    2013     def auto_poly_baseline(self, mask=[], edge=(0, 0), order=0,
     2080                raise RuntimeError(str(e)+'\n'+msg)
     2081
     2082
     2083    def auto_poly_baseline(self, mask=None, edge=(0, 0), order=0,
    20142084                           threshold=3, chan_avg_limit=1, plot=False,
    2015                            insitu=None):
     2085                           insitu=None, rows=None):
    20162086        """\
    20172087        Return a scan which has been baselined (all rows) by a polynomial.
     
    20542124                        Otherwise, the scaling is done in-situ
    20552125                        The default is taken from .asaprc (False)
     2126            rows:       row numbers of spectra to be processed.
     2127                        (default is None: for all rows)
    20562128
    20572129
     
    20632135        if insitu is None: insitu = rcParams['insitu']
    20642136        varlist = vars()
    2065         from asap.asapfitter import fitter
    20662137        from asap.asaplinefind import linefinder
    20672138        from asap import _is_sequence_or_number as _is_valid
     
    20872158            curedge = edge;
    20882159
     2160        if not insitu:
     2161            workscan = self.copy()
     2162        else:
     2163            workscan = self
     2164
    20892165        # setup fitter
    20902166        f = fitter()
    2091         f.set_function(poly=order)
     2167        f.set_function(lpoly=order)
    20922168
    20932169        # setup line finder
     
    20952171        fl.set_options(threshold=threshold,avg_limit=chan_avg_limit)
    20962172
    2097         if not insitu:
    2098             workscan = self.copy()
    2099         else:
    2100             workscan = self
    2101 
    21022173        fl.set_scan(workscan)
    21032174
    2104         rows = range(workscan.nrow())
     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       
    21052183        # Save parameters of baseline fits & masklists as a class attribute.
    21062184        # NOTICE: It does not reflect changes in scantable!
     
    21082186            self.blpars=[]
    21092187            self.masklists=[]
     2188            self.actualmask=[]
    21102189        asaplog.push("Processing:")
    21112190        for r in rows:
     
    21222201                    curedge = edge[workscan.getif(r)]
    21232202
    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]
     2203            actualmask = mask_and(mask, workscan._getmask(r))    # (CAS-1434)
    21352204
    21362205            # setup line finder
    21372206            fl.find_lines(r, actualmask, curedge)
    2138             outmask=fl.get_mask()
    2139             f.set_scan(workscan, fl.get_mask())
     2207           
    21402208            f.x = workscan._getabcissa(r)
    21412209            f.y = workscan._getspectrum(r)
     2210            f.mask = fl.get_mask()
    21422211            f.data = None
    21432212            f.fit()
    21442213
    21452214            # Show mask list
    2146             masklist=workscan.get_masklist(fl.get_mask(),row=r)
     2215            masklist=workscan.get_masklist(f.mask, row=r, silent=True)
    21472216            msg = "mask range: "+str(masklist)
    21482217            asaplog.push(msg, False)
     
    21542223                    self.blpars.append(None)
    21552224                    self.masklists.append(None)
     2225                    self.actualmask.append(None)
    21562226                    continue
    21572227
     
    21592229            self.blpars.append(f.get_parameters())
    21602230            self.masklists.append(masklist)
     2231            self.actualmask.append(f.mask)
    21612232        if plot:
    21622233            f._p.unmap()
     
    21682239            return workscan
    21692240
    2170     @print_log_dec
     2241    @asaplog_post_dec
    21712242    def rotate_linpolphase(self, angle):
    21722243        """\
     
    21872258        self._math._rotate_linpolphase(self, angle)
    21882259        self._add_history("rotate_linpolphase", varlist)
    2189         print_log()
    21902260        return
    21912261
    2192     @print_log_dec
     2262    @asaplog_post_dec
    21932263    def rotate_xyphase(self, angle):
    21942264        """\
     
    22092279        self._math._rotate_xyphase(self, angle)
    22102280        self._add_history("rotate_xyphase", varlist)
    2211         print_log()
    22122281        return
    22132282
    2214     @print_log_dec
     2283    @asaplog_post_dec
    22152284    def swap_linears(self):
    22162285        """\
     
    22212290        self._math._swap_linears(self)
    22222291        self._add_history("swap_linears", varlist)
    2223         print_log()
    22242292        return
    22252293
    2226     @print_log_dec
     2294    @asaplog_post_dec
    22272295    def invert_phase(self):
    22282296        """\
     
    22342302        return
    22352303
    2236     @print_log_dec
     2304    @asaplog_post_dec
    22372305    def add(self, offset, insitu=None):
    22382306        """\
     
    22422310
    22432311            offset:      the offset
     2312
    22442313            insitu:      if False a new scantable is returned.
    22452314                         Otherwise, the scaling is done in-situ
     
    22572326            return s
    22582327
    2259     @print_log_dec
     2328    @asaplog_post_dec
    22602329    def scale(self, factor, tsys=True, insitu=None):
    22612330        """\
    22622331
    2263         Return a scan where all spectra are scaled by the give 'factor'
     2332        Return a scan where all spectra are scaled by the given 'factor'
    22642333
    22652334        Parameters:
    22662335
    22672336            factor:      the scaling factor (float or 1D float list)
     2337
    22682338            insitu:      if False a new scantable is returned.
    22692339                         Otherwise, the scaling is done in-situ
    22702340                         The default is taken from .asaprc (False)
     2341
    22712342            tsys:        if True (default) then apply the operation to Tsys
    22722343                         as well as the data
     
    22872358            s = scantable(self._math._unaryop(self.copy(), factor, "MUL", tsys))
    22882359        s._add_history("scale", varlist)
    2289         print_log()
    22902360        if insitu:
    22912361            self._assign(s)
     
    23022372
    23032373            match:          a Unix style pattern, regular expression or selector
     2374
    23042375            matchtype:      'pattern' (default) UNIX style pattern or
    23052376                            'regex' regular expression
     2377
    23062378            sourcetype:     the type of the source to use (source/reference)
    23072379
     
    23322404        self._add_history("set_sourcetype", varlist)
    23332405
    2334     @print_log_dec
     2406    @asaplog_post_dec
     2407    @preserve_selection
    23352408    def auto_quotient(self, preserve=True, mode='paired', verify=False):
    23362409        """\
     
    23432416            preserve:       you can preserve (default) the continuum or
    23442417                            remove it.  The equations used are
     2418
    23452419                            preserve: Output = Toff * (on/off) - Toff
     2420
    23462421                            remove:   Output = Toff * (on/off) - Ton
     2422
    23472423            mode:           the on/off detection mode
    23482424                            'paired' (default)
     
    23542430                            finds the closest off in time
    23552431
    2356         """
     2432        .. todo:: verify argument is not implemented
     2433
     2434        """
     2435        varlist = vars()
    23572436        modes = ["time", "paired"]
    23582437        if not mode in modes:
    23592438            msg = "please provide valid mode. Valid modes are %s" % (modes)
    23602439            raise ValueError(msg)
    2361         varlist = vars()
    23622440        s = None
    23632441        if mode.lower() == "paired":
    2364             basesel = self.get_selection()
    2365             sel = selector()+basesel
    2366             sel.set_query("SRCTYPE==1")
     2442            sel = self.get_selection()
     2443            sel.set_query("SRCTYPE==psoff")
    23672444            self.set_selection(sel)
    23682445            offs = self.copy()
    2369             sel.set_query("SRCTYPE==0")
     2446            sel.set_query("SRCTYPE==pson")
    23702447            self.set_selection(sel)
    23712448            ons = self.copy()
    23722449            s = scantable(self._math._quotient(ons, offs, preserve))
    2373             self.set_selection(basesel)
    23742450        elif mode.lower() == "time":
    23752451            s = scantable(self._math._auto_quotient(self, mode, preserve))
    23762452        s._add_history("auto_quotient", varlist)
    2377         print_log()
    23782453        return s
    23792454
    2380     @print_log_dec
     2455    @asaplog_post_dec
    23812456    def mx_quotient(self, mask = None, weight='median', preserve=True):
    23822457        """\
     
    23862461
    23872462            mask:           an optional mask to be used when weight == 'stddev'
     2463
    23882464            weight:         How to average the off beams.  Default is 'median'.
     2465
    23892466            preserve:       you can preserve (default) the continuum or
    2390                             remove it.  The equations used are
    2391                             preserve: Output = Toff * (on/off) - Toff
    2392                             remove:   Output = Toff * (on/off) - Ton
     2467                            remove it.  The equations used are:
     2468
     2469                                preserve: Output = Toff * (on/off) - Toff
     2470
     2471                                remove:   Output = Toff * (on/off) - Ton
    23932472
    23942473        """
     
    24012480        q = quotient(on, off, preserve)
    24022481        q._add_history("mx_quotient", varlist)
    2403         print_log()
    24042482        return q
    24052483
    2406     @print_log_dec
     2484    @asaplog_post_dec
    24072485    def freq_switch(self, insitu=None):
    24082486        """\
     
    24212499        s = scantable(self._math._freqswitch(self))
    24222500        s._add_history("freq_switch", varlist)
    2423         print_log()
    2424         if insitu: self._assign(s)
    2425         else: return s
    2426 
    2427     @print_log_dec
     2501        if insitu:
     2502            self._assign(s)
     2503        else:
     2504            return s
     2505
     2506    @asaplog_post_dec
    24282507    def recalc_azel(self):
    24292508        """Recalculate the azimuth and elevation for each position."""
     
    24312510        self._recalcazel()
    24322511        self._add_history("recalc_azel", varlist)
    2433         print_log()
    24342512        return
    24352513
    2436     @print_log_dec
     2514    @asaplog_post_dec
    24372515    def __add__(self, other):
    24382516        varlist = vars()
     
    24472525        return s
    24482526
    2449     @print_log_dec
     2527    @asaplog_post_dec
    24502528    def __sub__(self, other):
    24512529        """
     
    24632541        return s
    24642542
    2465     @print_log_dec
     2543    @asaplog_post_dec
    24662544    def __mul__(self, other):
    24672545        """
     
    24802558
    24812559
    2482     @print_log_dec
     2560    @asaplog_post_dec
    24832561    def __div__(self, other):
    24842562        """
     
    24982576        return s
    24992577
     2578    @asaplog_post_dec
    25002579    def get_fit(self, row=0):
    25012580        """\
     
    25112590        from asap.asapfit import asapfit
    25122591        fit = asapfit(self._getfit(row))
    2513         if rcParams['verbose']:
    2514             #print fit
    2515             asaplog.push( '%s' %(fit) )
    2516             print_log()
    2517             return
    2518         else:
    2519             return fit.as_dict()
     2592        asaplog.push( '%s' %(fit) )
     2593        return fit.as_dict()
    25202594
    25212595    def flag_nans(self):
     
    26112685        return (sum(nchans)/len(nchans) == nchans[0])
    26122686
    2613     def _fill(self, names, unit, average, getpt, antenna):
     2687    @asaplog_post_dec
     2688    #def _fill(self, names, unit, average, getpt, antenna):
     2689    def _fill(self, names, unit, average, opts={}):
    26142690        first = True
    26152691        fullnames = []
     
    26192695            if not os.path.exists(name):
    26202696                msg = "File '%s' does not exists" % (name)
    2621                 if rcParams['verbose']:
    2622                     asaplog.push(msg)
    2623                     print_log( 'ERROR' )
    2624                     return
    26252697                raise IOError(msg)
    26262698            fullnames.append(name)
     
    26352707            msg = "Importing %s..." % (name)
    26362708            asaplog.push(msg, False)
    2637             print_log()
    2638             r.open(name)# antenna, -1, -1, getpt)
     2709            #opts = {'ms': {'antenna' : antenna, 'getpt': getpt} }
     2710            r.open(name, opts)# antenna, -1, -1, getpt)
    26392711            r.fill()
    26402712            if average:
     
    26462718            del r, tbl
    26472719            first = False
     2720            #flush log
     2721        asaplog.post()
    26482722        if unit is not None:
    26492723            self.set_fluxunit(unit)
Note: See TracChangeset for help on using the changeset viewer.