Ignore:
Location:
trunk/python
Files:
1 added
14 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/__init__.py

    r1848 r1949  
    1616from asap.utils import _n_bools, _is_sequence_or_number, _to_list
    1717
    18 
    1918if is_ipython():
    2019    from ipysupport import *
    2120
    22 # use rc parameter to enable/disable logging
    23 asaplog.enable(rcParams['verbose'])
     21# Only use rcParams['verbose'] in standard asap cli mode
     22# not in scripts or casapy
     23if not is_asap_cli():
     24    rcParams['verbose'] = False
    2425
    2526setup_env()
     
    3839        plotter = asapplotter(gui)
    3940    except ImportError:
    40         asaplog.post( "Matplotlib not installed. No plotting available")
    41         print_log('WARN')
     41        asaplog.push( "Matplotlib not installed. No plotting available")
     42        asaplog.post('WARN')
    4243
    4344from selector import selector
     
    5152from opacity import skydip
    5253from opacity import model as opacity_model
     54from _asap import srctype
    5355
    5456__date__ = '$Date$'.split()[1]
  • trunk/python/asapfitter.py

    r1848 r1949  
    11import _asap
    22from asap.parameters import rcParams
    3 from asap.logging import asaplog, print_log, print_log_dec
     3from asap.logging import asaplog, asaplog_post_dec
    44from asap.utils import _n_bools, mask_and
    55
     
    99    The fitting class for ASAP.
    1010    """
    11 
    1211    def __init__(self):
    1312        """
     
    4948        return
    5049
     50    @asaplog_post_dec
    5151    def set_scan(self, thescan=None, mask=None):
    5252        """
     
    5858        if not thescan:
    5959            msg = "Please give a correct scan"
    60             if rcParams['verbose']:
    61                 #print msg
    62                 asaplog.push(msg)
    63                 print_log('ERROR')
    64                 return
    65             else:
    66                 raise TypeError(msg)
     60            raise TypeError(msg)
    6761        self.fitted = False
    6862        self.data = thescan
     
    7468        return
    7569
     70    @asaplog_post_dec
    7671    def set_function(self, **kwargs):
    7772        """
     
    9287        if kwargs.has_key('poly'):
    9388            self.fitfunc = 'poly'
     89            self.fitfuncs = ['poly']
    9490            n = kwargs.get('poly')
    95             self.components = [n]
     91            self.components = [n+1]
    9692            self.uselinear = False
    9793        elif kwargs.has_key('lpoly'):
    9894            self.fitfunc = 'poly'
     95            self.fitfuncs = ['lpoly']
    9996            n = kwargs.get('lpoly')
    100             self.components = [n]
     97            self.components = [n+1]
    10198            self.uselinear = True
    10299        elif kwargs.has_key('gauss'):
     
    114111        else:
    115112            msg = "Invalid function type."
    116             if rcParams['verbose']:
    117                 #print msg
    118                 asaplog.push(msg)
    119                 print_log('ERROR')
    120                 return
    121             else:
    122                 raise TypeError(msg)
     113            raise TypeError(msg)
    123114
    124115        self.fitter.setexpression(self.fitfunc,n)
     
    126117        return
    127118
    128     @print_log_dec
     119    @asaplog_post_dec
    129120    def fit(self, row=0, estimate=False):
    130121        """
     
    146137               or self.fitfunc is None:
    147138            msg = "Fitter not yet initialised. Please set data & fit function"
    148             if rcParams['verbose']:
    149                 #print msg
    150                 asaplog.push(msg)
    151                 print_log('ERROR')
    152                 return
    153             else:
    154                 raise RuntimeError(msg)
     139            raise RuntimeError(msg)
    155140
    156141        else:
     
    172157            if len(ps) == 0 or estimate:
    173158                self.fitter.estimate()
    174         try:
    175             fxdpar = list(self.fitter.getfixedparameters())
    176             if len(fxdpar) and fxdpar.count(0) == 0:
    177                  raise RuntimeError,"No point fitting, if all parameters are fixed."
    178             if self.uselinear:
    179                 converged = self.fitter.lfit()
    180             else:
    181                 converged = self.fitter.fit()
    182             if not converged:
    183                 raise RuntimeError,"Fit didn't converge."
    184         except RuntimeError, msg:
    185             if rcParams['verbose']:
    186                 #print msg
    187                 print_log()
    188                 asaplog.push(str(msg))
    189                 print_log('ERROR')
    190             else:
    191                 raise
     159        fxdpar = list(self.fitter.getfixedparameters())
     160        if len(fxdpar) and fxdpar.count(0) == 0:
     161             raise RuntimeError,"No point fitting, if all parameters are fixed."
     162        if self.uselinear:
     163            converged = self.fitter.lfit()
     164        else:
     165            converged = self.fitter.fit()
     166        if not converged:
     167            raise RuntimeError,"Fit didn't converge."
    192168        self._fittedrow = row
    193169        self.fitted = True
    194         print_log()
    195170        return
    196171
     
    221196                self.data._addfit(fit,self._fittedrow)
    222197
    223     @print_log_dec
     198    @asaplog_post_dec
    224199    def set_parameters(self,*args,**kwargs):
    225200        """
     
    229204              fixed:     a vector of which parameters are to be held fixed
    230205                         (default is none)
    231               component: in case of multiple gaussians, the index of the
    232                          component
     206              component: in case of multiple gaussians/lorentzians,
     207                         the index of the component
    233208        """
    234209        component = None
     
    244219        if self.fitfunc is None:
    245220            msg = "Please specify a fitting function first."
    246             if rcParams['verbose']:
    247                 #print msg
    248                 asaplog.push(msg)
    249                 print_log('ERROR')
    250                 return
    251             else:
    252                 raise RuntimeError(msg)
     221            raise RuntimeError(msg)
    253222        if (self.fitfunc == "gauss" or self.fitfunc == 'lorentz') and component is not None:
    254223            if not self.fitted and sum(self.fitter.getparameters()) == 0:
     
    266235        if fixed is not None:
    267236            self.fitter.setfixedparameters(fixed)
    268         print_log()
    269237        return
    270238
     239    @asaplog_post_dec
    271240    def set_gauss_parameters(self, peak, centre, fwhm,
    272241                             peakfixed=0, centrefixed=0,
     
    288257        if self.fitfunc != "gauss":
    289258            msg = "Function only operates on Gaussian components."
    290             if rcParams['verbose']:
    291                 #print msg
    292                 asaplog.push(msg)
    293                 print_log('ERROR')
    294                 return
    295             else:
    296                 raise ValueError(msg)
     259            raise ValueError(msg)
    297260        if 0 <= component < len(self.components):
    298261            d = {'params':[peak, centre, fwhm],
     
    301264        else:
    302265            msg = "Please select a valid  component."
    303             if rcParams['verbose']:
    304                 #print msg
    305                 asaplog.push(msg)
    306                 print_log('ERROR')
    307                 return
    308             else:
    309                 raise ValueError(msg)
    310 
     266            raise ValueError(msg)
     267
     268    @asaplog_post_dec
    311269    def set_lorentz_parameters(self, peak, centre, fwhm,
    312270                             peakfixed=0, centrefixed=0,
     
    316274        Set the Parameters of a 'Lorentzian' component, set with set_function.
    317275        Parameters:
    318             peak, centre, fwhm:  The gaussian parameters
     276            peak, centre, fwhm:  The lorentzian parameters
    319277            peakfixed,
    320278            centrefixed,
     
    328286        if self.fitfunc != "lorentz":
    329287            msg = "Function only operates on Lorentzian components."
    330             if rcParams['verbose']:
    331                 #print msg
    332                 asaplog.push(msg)
    333                 print_log('ERROR')
    334                 return
    335             else:
    336                 raise ValueError(msg)
     288            raise ValueError(msg)
    337289        if 0 <= component < len(self.components):
    338290            d = {'params':[peak, centre, fwhm],
     
    341293        else:
    342294            msg = "Please select a valid  component."
    343             if rcParams['verbose']:
    344                 #print msg
    345                 asaplog.push(msg)
    346                 print_log('ERROR')
    347                 return
    348             else:
    349                 raise ValueError(msg)
     295            raise ValueError(msg)
    350296
    351297    def get_area(self, component=None):
     
    378324            return sum(areas)
    379325
     326    @asaplog_post_dec
    380327    def get_errors(self, component=None):
    381328        """
     
    387334        if not self.fitted:
    388335            msg = "Not yet fitted."
    389             if rcParams['verbose']:
    390                 #print msg
    391                 asaplog.push(msg)
    392                 print_log('ERROR')
    393                 return
    394             else:
    395                 raise RuntimeError(msg)
     336            raise RuntimeError(msg)
    396337        errs = list(self.fitter.geterrors())
    397338        cerrs = errs
     
    403344        return cerrs
    404345
     346
     347    @asaplog_post_dec
    405348    def get_parameters(self, component=None, errors=False):
    406349        """
     
    412355        if not self.fitted:
    413356            msg = "Not yet fitted."
    414             if rcParams['verbose']:
    415                 #print msg
    416                 asaplog.push(msg)
    417                 print_log('ERROR')
    418                 return
    419             else:
    420                 raise RuntimeError(msg)
     357            raise RuntimeError(msg)
    421358        pars = list(self.fitter.getparameters())
    422359        fixed = list(self.fitter.getfixedparameters())
     
    444381                  area += [a for i in range(3)]
    445382        fpars = self._format_pars(cpars, cfixed, errors and cerrs, area)
    446         if rcParams['verbose']:
    447             #print fpars
    448             asaplog.push(fpars)
    449             print_log()
     383        asaplog.push(fpars)
    450384        return {'params':cpars, 'fixed':cfixed, 'formatted': fpars,
    451385                'errors':cerrs}
     
    481415        return out
    482416
     417
     418    @asaplog_post_dec
    483419    def get_estimate(self):
    484420        """
     
    487423        pars = self.fitter.getestimate()
    488424        fixed = self.fitter.getfixedparameters()
    489         if rcParams['verbose']:
    490             #print self._format_pars(pars,fixed,None)
    491             asaplog.push(self._format_pars(pars,fixed,None))
    492             print_log()
     425        asaplog.push(self._format_pars(pars,fixed,None,None))
    493426        return pars
    494427
     428    @asaplog_post_dec
    495429    def get_residual(self):
    496430        """
     
    499433        if not self.fitted:
    500434            msg = "Not yet fitted."
    501             if rcParams['verbose']:
    502                 #print msg
    503                 asaplog.push(msg)
    504                 print_log('ERROR')
    505                 return
    506             else:
    507                 raise RuntimeError(msg)
     435            raise RuntimeError(msg)
    508436        return self.fitter.getresidual()
    509437
     438    @asaplog_post_dec
    510439    def get_chi2(self):
    511440        """
     
    514443        if not self.fitted:
    515444            msg = "Not yet fitted."
    516             if rcParams['verbose']:
    517                 #print msg
    518                 asaplog.push(msg)
    519                 print_log('ERROR')
    520                 return
    521             else:
    522                 raise RuntimeError(msg)
     445            raise RuntimeError(msg)
    523446        ch2 = self.fitter.getchi2()
    524         if rcParams['verbose']:
    525             #print 'Chi^2 = %3.3f' % (ch2)
    526             asaplog.push( 'Chi^2 = %3.3f' % (ch2) )
    527             print_log()
     447        asaplog.push( 'Chi^2 = %3.3f' % (ch2) )
    528448        return ch2
    529449
     450    @asaplog_post_dec
    530451    def get_fit(self):
    531452        """
     
    534455        if not self.fitted:
    535456            msg = "Not yet fitted."
    536             if rcParams['verbose']:
    537                 #print msg
    538                 asaplog.push(msg)
    539                 print_log('ERROR')
    540                 return
    541             else:
    542                 raise RuntimeError(msg)
     457            raise RuntimeError(msg)
    543458        return self.fitter.getfit()
    544459
    545     @print_log_dec
     460    @asaplog_post_dec
    546461    def commit(self):
    547462        """
     
    550465        if not self.fitted:
    551466            msg = "Not yet fitted."
    552             if rcParams['verbose']:
    553                 #print msg
    554                 asaplog.push(msg)
    555                 print_log('ERROR')
    556                 return
    557             else:
    558                 raise RuntimeError(msg)
     467            raise RuntimeError(msg)
    559468        from asap import scantable
    560469        if not isinstance(self.data, scantable):
    561470            msg = "Not a scantable"
    562             if rcParams['verbose']:
    563                 #print msg
    564                 asaplog.push(msg)
    565                 print_log('ERROR')
    566                 return
    567             else:
    568                 raise TypeError(msg)
     471            raise TypeError(msg)
    569472        scan = self.data.copy()
    570473        scan._setspectrum(self.fitter.getresidual())
    571         print_log()
    572474        return scan
    573475
    574     @print_log_dec
     476    @asaplog_post_dec
    575477    def plot(self, residual=False, components=None, plotparms=False,
    576478             filename=None):
     
    671573        if (not rcParams['plotter.gui']):
    672574            self._p.save(filename)
    673         print_log()
    674 
    675     @print_log_dec
     575
     576    @asaplog_post_dec
    676577    def auto_fit(self, insitu=None, plot=False):
    677578        """
     
    683584        if not isinstance(self.data, scantable) :
    684585            msg = "Data is not a scantable"
    685             if rcParams['verbose']:
    686                 #print msg
    687                 asaplog.push(msg)
    688                 print_log('ERROR')
    689                 return
    690             else:
    691                 raise TypeError(msg)
     586            raise TypeError(msg)
    692587        if insitu is None: insitu = rcParams['insitu']
    693588        if not insitu:
     
    725620            self._p.unmap()
    726621            self._p = None
    727         print_log()
    728622        return scan
  • trunk/python/asaplotbase.py

    r1848 r1949  
    1414
    1515from asap.parameters import rcParams as asaprcParams
    16 from asap.logging import asaplog, print_log
     16from asap.logging import asaplog
    1717
    1818# API change in mpl >= 0.98
     
    2525    #print "Warning: matplotlib version < 0.87. This might cause errors. Please upgrade."
    2626    asaplog.push( "matplotlib version < 0.99. This might cause errors. Please upgrade." )
    27     print_log( 'WARN' )
     27    asaplog.post( 'WARN' )
    2828
    2929class asaplotbase:
     
    417417            fname = 'asap'+dstr+'.png'
    418418
    419         d = ['png','.ps','eps']
     419        d = ['png','.ps','eps', 'svg']
    420420
    421421        from os.path import expandvars
     
    456456            except IOError, msg:
    457457                #print 'Failed to save %s: Error msg was\n\n%s' % (fname, err)
    458                 print_log()
     458                asaplog.post()
    459459                asaplog.push('Failed to save %s: Error msg was\n\n%s' % (fname, str(msg)))
    460                 print_log( 'ERROR' )
     460                asaplog.post( 'ERROR' )
    461461                return
    462462        else:
     
    464464            #print "'ps', 'eps', 'png'"
    465465            asaplog.push( "Invalid image type. Valid types are:" )
    466             asaplog.push( "'ps', 'eps', 'png'" )
    467             print_log('WARN')
     466            asaplog.push( "'ps', 'eps', 'png', 'svg'" )
     467            asaplog.post('WARN')
    468468
    469469
     
    669669                            for tick in self.subplots[i]['axes'].xaxis.majorTicks:
    670670                                tick.label1On = False
    671                             self.subplots[i]['axes'].xaxis.label.set_visible(False)
     671                            #self.subplots[i]['axes'].xaxis.label.set_visible(False)
    672672                    if i%cols:
    673673                        # Suppress y-labels for frames not in the left column.
    674674                        for tick in self.subplots[i]['axes'].yaxis.majorTicks:
    675675                            tick.label1On = False
    676                         self.subplots[i]['axes'].yaxis.label.set_visible(False)
     676                        #self.subplots[i]['axes'].yaxis.label.set_visible(False)
    677677                    # disable the first tick of [1:ncol-1] of the last row
    678678                    #if i+1 < nplots:
    679679                    #    self.subplots[i]['axes'].xaxis.majorTicks[0].label1On = False
    680                 self.rows = rows
    681                 self.cols = cols
     680                # set axes label state for interior subplots.
     681                if i%cols:
     682                    self.subplots[i]['axes'].yaxis.label.set_visible(False)
     683                if (i <= (rows-1)*cols - 1) and (i+cols < nplots):
     684                    self.subplots[i]['axes'].xaxis.label.set_visible(False)
     685            self.rows = rows
     686            self.cols = cols
    682687            self.subplot(0)
    683688        del rows,cols,n,nplots,layout,ganged,i
     689
    684690
    685691    def tidy(self):
     
    694700                if i != 0:
    695701                    ax.yaxis.majorTicks[-1].label1On = False
    696 
     702            ## set axes label state for interior subplots.
     703            #innerax=False
     704            #if i%self.cols:
     705            #    ax.yaxis.label.set_visible(innerax)
     706            #if (i <= (self.rows-1)*self.cols - 1) and (i+self.cols < nplots):
     707            #    ax.xaxis.label.set_visible(innerax)
     708           
    697709
    698710    def set_title(self, title=None):
     
    733745                        sp['axes'].legend(tuple(lines), tuple(labels),
    734746                                          self.loc, prop=fp)
    735                     else:
    736                         sp['axes'].legend((' '))
     747                    #else:
     748                    #    sp['axes'].legend((' '))
    737749
    738750            from matplotlib.artist import setp
  • trunk/python/asapmath.py

    r1848 r1949  
    11from asap.scantable import scantable
    22from asap.parameters import rcParams
    3 from asap.logging import asaplog, print_log, print_log_dec
     3from asap.logging import asaplog, asaplog_post_dec
    44from asap.selector import selector
    55from asap import asaplotgui
    66
    7 @print_log_dec
     7@asaplog_post_dec
    88def average_time(*args, **kwargs):
    99    """
     
    6767        if not isinstance(s,scantable):
    6868            msg = "Please give a list of scantables"
    69             if rcParams['verbose']:
    70                 #print msg
    71                 asaplog.push(msg)
    72                 print_log('ERROR')
    73                 return
    74             else:
    75                 raise TypeError(msg)
     69            raise TypeError(msg)
    7670    if scanav: scanav = "SCAN"
    7771    else: scanav = "NONE"
     
    9690        s = scantable(stm._new_average(alignedlst, compel, mask, weight.upper(), scanav))
    9791    s._add_history("average_time",varlist)
    98     print_log()
     92
    9993    return s
    10094
     95@asaplog_post_dec
    10196def quotient(source, reference, preserve=True):
    10297    """
     
    119114    s = scantable(stm._quotient(source, reference, preserve))
    120115    s._add_history("quotient",varlist)
    121     print_log()
    122116    return s
    123117
    124 @print_log_dec
     118@asaplog_post_dec
    125119def dototalpower(calon, caloff, tcalval=0.0):
    126120    """
     
    138132    s = scantable(stm._dototalpower(calon, caloff, tcalval))
    139133    s._add_history("dototalpower",varlist)
    140     print_log()
    141134    return s
    142135
    143 @print_log_dec
     136@asaplog_post_dec
    144137def dosigref(sig, ref, smooth, tsysval=0.0, tauval=0.0):
    145138    """
     
    159152    s = scantable(stm._dosigref(sig, ref, smooth, tsysval, tauval))
    160153    s._add_history("dosigref",varlist)
    161     print_log()
    162154    return s
    163155
    164 @print_log_dec
     156@asaplog_post_dec
    165157def calps(scantab, scannos, smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    166158    """
    167159    Calibrate GBT position switched data
    168160    Adopted from GBTIDL getps
    169     Currently calps identify the scans as position switched data if they
    170     contain '_ps' in the source name. The data must contains 'CAL' signal
    171     on/off in each integration. To identify 'CAL' on state, the word, 'calon'
    172     need to be present in the source name field.
     161    Currently calps identify the scans as position switched data if source
     162    type enum is pson or psoff. The data must contains 'CAL' signal
     163    on/off in each integration. To identify 'CAL' on state, the source type
     164    enum of poncal and poffcal need to be present in the source name field.
    173165    (GBT MS data reading process to scantable automatically append these
    174166    id names to the source names)
     
    184176        tcalval:       optional user specified Tcal (default is 0.0,
    185177                       use Tcal value in the data)
     178        verify:        Verify calibration if true
    186179    """
    187180    varlist = vars()
     
    190183##     if s is None:
    191184##         msg = "The input data appear to contain no position-switch mode data."
    192 ##         if rcParams['verbose']:
    193 ##             #print msg
    194 ##             asaplog.push(msg)
    195 ##             print_log('ERROR')
    196 ##             return
    197 ##         else:
    198 ##             raise TypeError(msg)
     185##         raise TypeError(msg)
    199186    s = scantab.copy()
    200187    from asap._asap import srctype
     
    205192    except Exception, e:
    206193        msg = "The input data appear to contain no position-switch mode data."
    207         if rcParams['verbose']:
    208             #print msg
    209             asaplog.push(msg)
    210             print_log('ERROR')
    211             return
    212         else:
    213             raise TypeError(msg)
     194        raise TypeError(msg)
    214195    s.set_selection()
    215196    sel.reset()
     
    217198    if ssub is None:
    218199        msg = "No data was found with given scan numbers!"
    219         if rcParams['verbose']:
    220             #print msg
    221             asaplog.push(msg)
    222             print_log('ERROR')
    223             return
    224         else:
    225             raise TypeError(msg)
     200        raise TypeError(msg)
    226201    #ssubon = ssub.get_scan('*calon')
    227202    #ssuboff = ssub.get_scan('*[^calon]')
     
    238213    if ssubon.nrow() != ssuboff.nrow():
    239214        msg = "mismatch in numbers of CAL on/off scans. Cannot calibrate. Check the scan numbers."
    240         if rcParams['verbose']:
    241             #print msg
    242             asaplog.push(msg)
    243             print_log('ERROR')
    244             return
    245         else:
    246             raise TypeError(msg)
     215        raise TypeError(msg)
    247216    cals = dototalpower(ssubon, ssuboff, tcalval)
    248217    #sig = cals.get_scan('*ps')
     
    260229    if sig.nscan() != ref.nscan():
    261230        msg = "mismatch in numbers of on/off scans. Cannot calibrate. Check the scan numbers."
    262         if rcParams['verbose']:
    263             #print msg
    264             asaplog.push(msg)
    265             print_log('ERROR')
    266             return
    267         else:
    268             raise TypeError(msg)
     231        raise TypeError(msg)
    269232
    270233    #for user supplied Tsys
     
    272235        if tauval<=0.0:
    273236            msg = "Need to supply a valid tau to use the supplied Tsys"
    274             if rcParams['verbose']:
    275                 #print msg
    276                 asaplog.push(msg)
    277                 print_log('ERROR')
    278                 return
    279             else:
    280                 raise TypeError(msg)
     237            raise TypeError(msg)
    281238        else:
    282239            sig.recalc_azel()
    283240            ref.recalc_azel()
    284241            #msg = "Use of user specified Tsys is not fully implemented yet."
    285             #if rcParams['verbose']:
    286             #    print msg
    287             #    return
    288             #else:
    289             #    raise TypeError(msg)
     242            #raise TypeError(msg)
    290243            # use get_elevation to get elevation and
    291244            # calculate a scaling factor using the formula
     
    355308        del sel
    356309        # plot
    357         print_log()
     310        asaplog.post()
    358311        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
    359         print_log('WARN')
     312        asaplog.post('WARN')
    360313        p=asaplotgui.asaplotgui()
    361314        #nr=min(6,len(ifnos)*len(polnos))
     
    384337                btics.append(b)
    385338        else:
    386             print_log()
     339            asaplog.post()
    387340            asaplog.push('Only first 6 [if,pol] pairs are plotted.')
    388             print_log('WARN')
     341            asaplog.post('WARN')
    389342            nr=6
    390343            for i in range(2*nr):
     
    442395    ###
    443396    ress._add_history("calps", varlist)
    444     print_log()
    445397    return ress
    446398
    447 @print_log_dec
     399@asaplog_post_dec
    448400def calnod(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    449401    """
     
    458410        tauval:      optional user specified tau value (not implemented yet)
    459411        tcalval:     optional user specified Tcal value
     412        verify:       Verify calibration if true
    460413    """
    461414    varlist = vars()
     
    469422##     if s is None:
    470423##         msg = "The input data appear to contain no Nod observing mode data."
    471 ##         if rcParams['verbose']:
    472 ##             #print msg
    473 ##             asaplog.push(msg)
    474 ##             print_log('ERROR')
    475 ##             return
    476 ##         else:
    477 ##             raise TypeError(msg)
     424##         raise TypeError(msg)
    478425    s = scantab.copy()
    479426    sel = selector()
     
    483430    except Exception, e:
    484431        msg = "The input data appear to contain no Nod observing mode data."
    485         if rcParams['verbose']:
    486             #print msg
    487             asaplog.push(msg)
    488             print_log('ERROR')
    489             return
    490         else:
    491             raise TypeError(msg)
     432        raise TypeError(msg)
    492433    sel.reset()
    493434    del sel
     
    511452        #if len(scannos)>2:
    512453        #    msg = "calnod can only process a pair of nod scans at time."
    513         #    if rcParams['verbose']:
    514         #        print msg
    515         #        return
    516         #    else:
    517         #        raise TypeError(msg)
     454        #    raise TypeError(msg)
    518455        #
    519456        #if len(scannos)==2:
     
    525462        if tauval<=0.0:
    526463            msg = "Need to supply a valid tau to use the supplied Tsys"
    527             if rcParams['verbose']:
    528                 #print msg
    529                 asaplog.push(msg)
    530                 print_log('ERROR')
    531                 return
    532             else:
    533                 raise TypeError(msg)
     464            raise TypeError(msg)
    534465        else:
    535466            scantab.recalc_azel()
     
    596527        del sel
    597528        # plot
    598         print_log()
     529        asaplog.post()
    599530        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
    600         print_log('WARN')
     531        asaplog.post('WARN')
    601532        p=asaplotgui.asaplotgui()
    602533        #nr=min(6,len(ifnos)*len(polnos))
     
    625556                btics.append(b)
    626557        else:
    627             print_log()
     558            asaplog.post()
    628559            asaplog.push('Only first 6 [if,pol] pairs are plotted.')
    629             print_log('WARN')
     560            asaplog.post('WARN')
    630561            nr=6
    631562            for i in range(2*nr):
     
    683614    ###
    684615    resspec._add_history("calnod",varlist)
    685     print_log()
    686616    return resspec
    687617
    688 @print_log_dec
     618@asaplog_post_dec
    689619def calfs(scantab, scannos=[], smooth=1, tsysval=0.0, tauval=0.0, tcalval=0.0, verify=False):
    690620    """
    691621    Calibrate GBT frequency switched data.
    692622    Adopted from GBTIDL getfs.
    693     Currently calfs identify the scans as frequency switched data if they
    694     contain '_fs' in the source name. The data must contains 'CAL' signal
    695     on/off in each integration. To identify 'CAL' on state, the word, 'calon'
    696     need to be present in the source name field.
     623    Currently calfs identify the scans as frequency switched data if source
     624    type enum is fson and fsoff. The data must contains 'CAL' signal
     625    on/off in each integration. To identify 'CAL' on state, the source type
     626    enum of foncal and foffcal need to be present in the source name field.
    697627    (GBT MS data reading via scantable automatically append these
    698628    id names to the source names)
     
    706636                       use Tsys in the data)
    707637        tauval:        optional user specified Tau
     638        verify:        Verify calibration if true
    708639    """
    709640    varlist = vars()
     
    716647#    if check is None:
    717648#        msg = "The input data appear to contain no Nod observing mode data."
    718 #        if rcParams['verbose']:
    719 #            print msg
    720 #            return
    721 #        else:
    722 #            raise TypeError(msg)
     649#        raise TypeError(msg)
    723650    s = scantab.get_scan(scannos)
    724651    del scantab
     
    812739        del sel
    813740        # plot
    814         print_log()
     741        asaplog.post()
    815742        asaplog.push('Plot only first spectrum for each [if,pol] pairs to verify calibration.')
    816         print_log('WARN')
     743        asaplog.post('WARN')
    817744        p=asaplotgui.asaplotgui()
    818745        #nr=min(6,len(ifnos)*len(polnos))
     
    821748        btics=[]
    822749        if nr>3:
    823             print_log()
     750            asaplog.post()
    824751            asaplog.push('Only first 3 [if,pol] pairs are plotted.')
    825             print_log('WARN')
     752            asaplog.post('WARN')
    826753            nr=3
    827754        p.set_panels(rows=nr,cols=3,nplots=3*nr,ganged=False)
     
    891818    ###
    892819    resspec._add_history("calfs",varlist)
    893     print_log()
    894820    return resspec
    895821
    896 @print_log_dec
     822@asaplog_post_dec
    897823def merge(*args):
    898824    """
     
    921847        if not isinstance(s,scantable):
    922848            msg = "Please give a list of scantables"
    923             if rcParams['verbose']:
    924                 #print msg
    925                 asaplog.push(msg)
    926                 print_log('ERROR')
    927                 return
    928             else:
    929                 raise TypeError(msg)
     849            raise TypeError(msg)
    930850    s = scantable(stm._merge(lst))
    931851    s._add_history("merge", varlist)
    932     print_log()
    933852    return s
    934853
     854@asaplog_post_dec
    935855def calibrate( scantab, scannos=[], calmode='none', verify=None ):
    936856    """
     
    946866    if ( calmode == 'nod' ):
    947867        asaplog.push( 'Calibrating nod data.' )
    948         print_log()
    949868        scal = calnod( scantab, scannos=scannos, verify=verify )
    950869    elif ( calmode == 'quotient' ):
    951870        asaplog.push( 'Calibrating using quotient.' )
    952         print_log()
    953871        scal = scantab.auto_quotient( verify=verify )
    954872    elif ( calmode == 'ps' ):
    955873        asaplog.push( 'Calibrating %s position-switched data.' % antname )
    956         print_log()
    957874        if ( antname.find( 'APEX' ) != -1 ):
    958875            scal = apexcal( scantab, scannos, calmode, verify )
     
    963880    elif ( calmode == 'fs' or calmode == 'fsotf' ):
    964881        asaplog.push( 'Calibrating %s frequency-switched data.' % antname )
    965         print_log()
    966882        if ( antname.find( 'APEX' ) != -1 ):
    967883            scal = apexcal( scantab, scannos, calmode, verify )
     
    972888    elif ( calmode == 'otf' ):
    973889        asaplog.push( 'Calibrating %s On-The-Fly data.' % antname )
    974         print_log()
    975890        scal = almacal( scantab, scannos, calmode, verify )
    976891    else:
     
    1015930    return scal
    1016931
     932@asaplog_post_dec
    1017933def splitant(filename, outprefix='',overwrite=False):
    1018934    """
     
    1032948    """
    1033949    # Import the table toolkit from CASA
    1034     try:
    1035        import casac
    1036     except ImportError:
    1037        if rcParams['verbose']:
    1038            #print "failed to load casa"
    1039            print_log()
    1040            asaplog.push("failed to load casa")
    1041            print_log('ERROR')
    1042        else: raise
    1043        return False
    1044     try:
    1045        tbtool = casac.homefinder.find_home_by_name('tableHome')
    1046        tb = tbtool.create()
    1047        tb2 = tbtool.create()
    1048     except:
    1049        if rcParams['verbose']:
    1050            #print "failed to load a table tool:\n", e
    1051            print_log()
    1052            asaplog.push("failed to load table tool")
    1053            print_log('ERROR')
    1054        else: raise
    1055        return False
     950    import casac
     951    from asap.scantable import is_ms
     952    tbtool = casac.homefinder.find_home_by_name('tableHome')
     953    tb = tbtool.create()
    1056954    # Check the input filename
    1057955    if isinstance(filename, str):
     
    1061959        if not os.path.exists(filename):
    1062960            s = "File '%s' not found." % (filename)
    1063             if rcParams['verbose']:
    1064                 print_log()
    1065                 asaplog.push(s)
    1066                 print_log('ERROR')
    1067                 return
    1068961            raise IOError(s)
    1069962        # check if input file is MS
    1070         if not os.path.isdir(filename) \
    1071                or not os.path.exists(filename+'/ANTENNA') \
    1072                or not os.path.exists(filename+'/table.f1'):
     963        #if not os.path.isdir(filename) \
     964        #       or not os.path.exists(filename+'/ANTENNA') \
     965        #       or not os.path.exists(filename+'/table.f1'):
     966        if not is_ms(filename):
    1073967            s = "File '%s' is not a Measurement set." % (filename)
    1074             if rcParams['verbose']:
    1075                 print_log()
    1076                 asaplog.push(s)
    1077                 print_log('ERROR')
    1078                 return
    1079968            raise IOError(s)
    1080969    else:
    1081970        s = "The filename should be string. "
    1082         if rcParams['verbose']:
    1083             print_log()
    1084             asaplog.push(s)
    1085             print_log('ERROR')
    1086             return
    1087971        raise TypeError(s)
    1088972    # Check out put file name
     
    1096980    nant=tb.nrows()
    1097981    antnames=tb.getcol('NAME',0,nant,1)
    1098     antpos=tb.getcol('POSITION',0,nant,1).transpose()
    1099982    tb.close()
    1100983    tb.open(tablename=filename,nomodify=True)
    1101984    ant1=tb.getcol('ANTENNA1',0,-1,1)
    1102985    tb.close()
     986    tmpname='asapmath.splitant.tmp'
    1103987    for antid in set(ant1):
    1104         scan=scantable(filename,average=False,getpt=True,antenna=int(antid))
     988        tb.open(tablename=filename,nomodify=True)
     989        tbsel=tb.query('ANTENNA1 == %s && ANTENNA2 == %s'%(antid,antid),tmpname)
     990        scan=scantable(tmpname,average=False,getpt=True,antenna=int(antid))
    1105991        outname=prefix+antnames[antid]+'.asap'
    1106992        scan.save(outname,format='ASAP',overwrite=overwrite)
     993        tbsel.close()
     994        tb.close()
     995        del tbsel
    1107996        del scan
    1108997        outfiles.append(outname)
    1109     del tb, tb2
     998        os.system('rm -rf '+tmpname)
     999    del tb
    11101000    return outfiles
    11111001
     1002@asaplog_post_dec
    11121003def _array2dOp( scan, value, mode="ADD", tsys=False ):
    11131004    """
     
    11281019        del stm
    11291020    elif len( value ) != nrow:
    1130         asaplog.push( 'len(value) must be 1 or conform to scan.nrow()' )
    1131         print_log( 'ERROR' )
     1021        raise ValueError( 'len(value) must be 1 or conform to scan.nrow()' )
    11321022    else:
    11331023        from asap._asap import stmath
  • trunk/python/asapplotter.py

    r1848 r1949  
    22from asap.selector import selector
    33from asap.scantable import scantable
    4 from asap.logging import asaplog, print_log, print_log_dec
     4from asap.logging import asaplog, asaplog_post_dec
    55import matplotlib.axes
    66from matplotlib.font_manager import FontProperties
     
    1414    By default the plotter is set up to plot polarisations
    1515    'colour stacked' and scantables across panels.
    16     Note:
     16
     17    .. note::
     18
    1719        Currenly it only plots 'spectra' not Tsys or
    1820        other variables.
     21
    1922    """
    2023    def __init__(self, visible=None , **kwargs):
     
    4851        self._fp = FontProperties()
    4952        self._panellayout = self.set_panellayout(refresh=False)
     53        self._offset = None
     54        self._rowcount = 0
     55        self._panelcnt = 0
    5056
    5157    def _translate(self, instr):
    52         keys = "s b i p t".split()
     58        keys = "s b i p t r".split()
    5359        if isinstance(instr, str):
    5460            for key in keys:
     
    7884        else: return None
    7985
    80     @print_log_dec
     86    @asaplog_post_dec
    8187    def plot(self, scan=None):
    8288        """
     
    9096            are consistent e.g. all 'channel' or all 'velocity' etc.
    9197        """
     98        self._rowcount = self._panelcnt = 0
    9299        if self._plotter.is_dead:
    93100            if hasattr(self._plotter.figmgr,'casabar'):
     
    96103            self._plotter.figmgr.casabar=self._newcasabar()
    97104        self._plotter.hold()
    98         self._plotter.clear()
     105        #self._plotter.clear()
    99106        if not self._data and not scan:
    100107            msg = "Input is not a scantable"
    101             if rcParams['verbose']:
    102                 #print msg
    103                 asaplog.push( msg )
    104                 print_log( 'ERROR' )
    105                 return
    106108            raise TypeError(msg)
    107         if scan: self.set_data(scan,refresh=False)
     109        if scan:
     110            self.set_data(scan, refresh=False)
    108111        self._plot(self._data)
    109112        if self._minmaxy is not None:
     
    113116        self._plotter.tidy()
    114117        self._plotter.show(hardrefresh=False)
    115         print_log()
    116118        return
    117119
     
    125127    def create_mask(self, nwin=1, panel=0, color=None):
    126128        """
    127         Interactively define a mask.It retruns a mask that is equivalent to
     129        Interactively define a mask. It retruns a mask that is equivalent to
    128130        the one created manually with scantable.create_mask.
    129131        Parameters:
     
    275277    # end matplotlib.axes fowarding functions
    276278
     279    @asaplog_post_dec
    277280    def set_data(self, scan, refresh=True):
    278281        """
     
    295298                    # reset
    296299                    self._reset()
    297                     msg = "A new scantable is set to the plotter. The masks and data selections are reset."
     300                    msg = "A new scantable is set to the plotter. "\
     301                          "The masks and data selections are reset."
    298302                    asaplog.push( msg )
    299                     print_log( 'INFO' )
    300303            else:
    301304                self._data = scan
     
    303306        else:
    304307            msg = "Input is not a scantable"
    305             if rcParams['verbose']:
    306                 #print msg
    307                 asaplog.push( msg )
    308                 print_log( 'ERROR' )
    309                 return
    310308            raise TypeError(msg)
    311309
     
    318316        if refresh: self.plot()
    319317
    320 
     318    @asaplog_post_dec
    321319    def set_mode(self, stacking=None, panelling=None, refresh=True):
    322320        """
     
    341339        if not self.set_panelling(panelling) or \
    342340               not self.set_stacking(stacking):
    343             if rcParams['verbose']:
    344                 #print msg
    345                 asaplog.push( msg )
    346                 print_log( 'ERROR' )
    347                 return
    348             else:
    349                 raise TypeError(msg)
     341            raise TypeError(msg)
     342        if self._panelling == 'r':
     343            self._stacking = '_r'
     344        elif self._stacking == 'r':
     345            self._panelling = '_r'
    350346        if refresh and self._data: self.plot(self._data)
    351347        return
    352348
    353349    def set_panelling(self, what=None):
     350        """Set the 'panelling' mode i.e. which type of spectra should be
     351        spread across different panels.
     352        """
     353
    354354        mode = what
    355355        if mode is None:
     
    359359            self._panelling = md
    360360            self._title = None
     361            if md == 'r':
     362                self._stacking = '_r'
    361363            return True
    362364        return False
     
    382384
    383385    def set_stacking(self, what=None):
     386        """Set the 'stacking' mode i.e. which type of spectra should be
     387        overlayed.
     388        """
    384389        mode = what
    385390        if mode is None:
     
    389394            self._stacking = md
    390395            self._lmap = None
     396            if md == 'r':
     397                self._panelling = '_r'
    391398            return True
    392399        return False
    393400
    394     def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True):
     401    def set_range(self,xstart=None,xend=None,ystart=None,yend=None,refresh=True, offset=None):
    395402        """
    396403        Set the range of interest on the abcissa of the plot
     
    400407                      replotted based on the new parameter setting(s).
    401408                      Otherwise,the parameter(s) are set without replotting.
     409            offset:   shift the abcissa by the given amount. The abcissa label will
     410                      have '(relative)' appended to it.
    402411        Note:
    403412            These become non-sensical when the unit changes.
     
    405414
    406415        """
     416        self._offset = offset
    407417        if xstart is None and xend is None:
    408418            self._minmaxx = None
     
    650660            deltachan:    the number of channels to include each side of the
    651661                          line to determine a local maximum/minimum
    652             rotate:       the rotation (in degrees) )for the text label (default 90.0)
     662            rotate:       the rotation (in degrees) for the text label (default 90.0)
    653663            location:     the location of the line annotation from the 'top',
    654664                          'bottom' or alternate (None - the default)
     
    720730    def save(self, filename=None, orientation=None, dpi=None):
    721731        """
    722         Save the plot to a file. The know formats are 'png', 'ps', 'eps'.
     732        Save the plot to a file. The known formats are 'png', 'ps', 'eps'.
    723733        Parameters:
    724734             filename:    The name of the output file. This is optional
     
    736746        return
    737747
    738 
     748    @asaplog_post_dec
    739749    def set_mask(self, mask=None, selection=None, refresh=True):
    740750        """
     
    754764        if not self._data:
    755765            msg = "Can only set mask after a first call to plot()"
    756             if rcParams['verbose']:
    757                 #print msg
    758                 asaplog.push( msg )
    759                 print_log( 'ERROR' )
    760                 return
    761             else:
    762                 raise RuntimeError(msg)
     766            raise RuntimeError(msg)
    763767        if len(mask):
    764768            if isinstance(mask, list) or isinstance(mask, tuple):
     
    817821        self._usermask = []
    818822        self._usermaskspectra = None
     823        self._offset = None
    819824        self.set_selection(None, False)
    820825
     
    822827        savesel = scan.get_selection()
    823828        sel = savesel +  self._selection
    824         d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
    825               'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' }
    826         order = [d0[self._panelling],d0[self._stacking]]
    827         sel.set_order(order)
     829        order = self._get_sortstring([self._panelling,self._stacking])
     830        if order:
     831            sel.set_order(order)
    828832        scan.set_selection(sel)
    829833        d = {'b': scan.getbeam, 's': scan.getscan,
    830              'i': scan.getif, 'p': scan.getpol, 't': scan._gettime }
     834             #'i': scan.getif, 'p': scan.getpol, 't': scan._gettime,
     835             'i': scan.getif, 'p': scan.getpol, 't': scan.get_time,
     836             'r': int, '_r': int}
    831837
    832838        polmodes = dict(zip(self._selection.get_pols(),
     
    839845        if isinstance(nstack0, int): nstack = nstack0
    840846        else: nstack = len(nstack0)
     847        nptot = n
    841848        maxpanel, maxstack = 16,16
    842         if n > maxpanel or nstack > maxstack:
    843             maxn = 0
    844             if nstack > maxstack: maxn = maxstack
    845             if n > maxpanel: maxn = maxpanel
    846             msg ="Scan to be plotted contains more than %d selections.\n" \
    847                   "Selecting first %d selections..." % (maxn, maxn)
     849        if nstack > maxstack:
     850            msg ="Scan to be overlayed contains more than %d selections.\n" \
     851                  "Selecting first %d selections..." % (maxstack, maxstack)
    848852            asaplog.push(msg)
    849             print_log('WARN')
    850             n = min(n,maxpanel)
     853            asaplog.post('WARN')
    851854            nstack = min(nstack,maxstack)
     855        n = min(n,maxpanel)
     856           
    852857        if n > 1:
    853858            ganged = rcParams['plotter.ganged']
     
    865870#            self._plotter.set_panels()
    866871            self._plotter.set_panels(layout=self._panellayout)
    867         r=0
     872        #r = 0
     873        r = self._rowcount
    868874        nr = scan.nrow()
    869875        a0,b0 = -1,-1
     
    882888                xlab = self._abcissa and self._abcissa[panelcount] \
    883889                       or scan._getabcissalabel()
     890                if self._offset and not self._abcissa:
     891                    xlab += " (relative)"
    884892                ylab = self._ordinate and self._ordinate[panelcount] \
    885893                       or scan._get_ordinate_label()
     
    887895                self._plotter.set_axes('ylabel', ylab)
    888896                lbl = self._get_label(scan, r, self._panelling, self._title)
     897                #if self._panelling == 'r': lbl = ''
    889898                if isinstance(lbl, list) or isinstance(lbl, tuple):
    890899                    if 0 <= panelcount < len(lbl):
     
    895904                self._plotter.set_axes('title',lbl)
    896905                newpanel = True
    897                 stackcount =0
     906                stackcount = 0
    898907                panelcount += 1
    899             if (b > b0 or newpanel) and stackcount < nstack:
     908            #if (b > b0 or newpanel) and stackcount < nstack:
     909            if stackcount < nstack and (newpanel or (a == a0 and b > b0)):
    900910                y = []
    901911                if len(polmodes):
     
    908918                    if d[self._stacking](r) in self._maskselection[self._stacking]:
    909919                        m = logical_and(m, self._usermask)
    910                 x = scan._getabcissa(r)
    911920                from numpy import ma, array
     921                x = array(scan._getabcissa(r))
     922                if self._offset:
     923                    x += self._offset
    912924                y = ma.masked_array(y,mask=logical_not(array(m,copy=False)))
    913925                if self._minmaxx is not None:
     
    960972                break
    961973            r+=1 # next row
     974        ###-S
     975        self._rowcount = r+1
     976        self._panelcnt += panelcount
     977        if self._plotter.figmgr.casabar:
     978            if self._panelcnt >= nptot-1:
     979                self._plotter.figmgr.casabar.disable_next()
     980            else:
     981                self._plotter.figmgr.casabar.enable_next()
     982            #if self._panelcnt - panelcount > 0:
     983            #    self._plotter.figmgr.casabar.enable_prev()
     984            #else:
     985            #    self._plotter.figmgr.casabar.disable_prev()
     986        ###-E
    962987        #reset the selector to the scantable's original
    963988        scan.set_selection(savesel)
     
    968993            for o in self._plotter.figure.findobj(Text):
    969994                o.set_fontproperties(self._fp)
     995
     996    def _get_sortstring(self, lorders):
     997        d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
     998              'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME', 'r':None, '_r':None }
     999        if not (type(lorders) == list) and not (type(lorders) == tuple):
     1000            return None
     1001        if len(lorders) > 0:
     1002            lsorts = []
     1003            for order in lorders:
     1004                ssort = d0[order]
     1005                if ssort:
     1006                    lsorts.append(ssort)
     1007            return lsorts
     1008        return None
    9701009
    9711010    def set_selection(self, selection=None, refresh=True, **kw):
     
    9921031            raise TypeError("'selection' is not of type selector")
    9931032
    994         d0 = {'s': 'SCANNO', 'b': 'BEAMNO', 'i':'IFNO',
    995               'p': 'POLNO', 'c': 'CYCLENO', 't' : 'TIME' }
    996         order = [d0[self._panelling],d0[self._stacking]]
    997         self._selection.set_order(order)
     1033        order = self._get_sortstring([self._panelling,self._stacking])
     1034        if order:
     1035            self._selection.set_order(order)
    9981036        if refresh and self._data: self.plot(self._data)
    9991037
    10001038    def _get_selected_n(self, scan):
    10011039        d1 = {'b': scan.getbeamnos, 's': scan.getscannos,
    1002              'i': scan.getifnos, 'p': scan.getpolnos, 't': scan.ncycle }
     1040             'i': scan.getifnos, 'p': scan.getpolnos, 't': scan.ncycle,
     1041             'r': scan.nrow, '_r': False}
    10031042        d2 = { 'b': self._selection.get_beams(),
    10041043               's': self._selection.get_scans(),
    10051044               'i': self._selection.get_ifs(),
    10061045               'p': self._selection.get_pols(),
    1007                't': self._selection.get_cycles() }
     1046               't': self._selection.get_cycles(),
     1047               'r': False, '_r': 1}
    10081048        n =  d2[self._panelling] or d1[self._panelling]()
    10091049        nstack = d2[self._stacking] or d1[self._stacking]()
     
    10241064             'i': "IF"+str(scan.getif(row)),
    10251065             'p': poleval,
    1026              't': str(scan.get_time(row)) }
     1066             't': str(scan.get_time(row)),
     1067             'r': "row "+str(row),
     1068             #'_r': str(scan.get_time(row))+",\nIF"+str(scan.getif(row))+", "+poleval+", Beam"+str(scan.getbeam(row)) }
     1069             '_r': "" }
    10271070        return userlabel or d[mode]
    10281071
    10291072    def plotazel(self, scan=None, outfile=None):
    1030     #def plotazel(self):
    10311073        """
    10321074        plot azimuth and elevation versus time of a scantable
    10331075        """
     1076        visible = rcParams['plotter.gui']
    10341077        from matplotlib import pylab as PL
    10351078        from matplotlib.dates import DateFormatter, timezone
     
    10371080        from matplotlib.ticker import MultipleLocator
    10381081        from numpy import array, pi
     1082        if not visible or not self._visible:
     1083            PL.ioff()
     1084            from matplotlib.backends.backend_agg import FigureCanvasAgg
     1085            PL.gcf().canvas.switch_backends(FigureCanvasAgg)
    10391086        self._data = scan
    10401087        self._outfile = outfile
     
    10461093        PL.clf()
    10471094        # Adjust subplot layouts
    1048         if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
     1095        if len(self._panellayout) != 6:
     1096            self.set_panellayout(refresh=False)
    10491097        lef, bot, rig, top, wsp, hsp = self._panellayout
    10501098        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     
    11261174
    11271175    def plotpointing(self, scan=None, outfile=None):
    1128     #def plotpointing(self):
    11291176        """
    11301177        plot telescope pointings
    11311178        """
     1179        visible = rcParams['plotter.gui']
    11321180        from matplotlib import pylab as PL
    11331181        from numpy import array, pi
     1182        if not visible or not self._visible:
     1183            PL.ioff()
     1184            from matplotlib.backends.backend_agg import FigureCanvasAgg
     1185            PL.gcf().canvas.switch_backends(FigureCanvasAgg)
    11341186        self._data = scan
    11351187        self._outfile = outfile
     
    11411193        PL.clf()
    11421194        # Adjust subplot layouts
    1143         if len(self._panellayout) !=6: self.set_panellayout(refresh=False)
     1195        if len(self._panellayout) != 6:
     1196            self.set_panellayout(refresh=False)
    11441197        lef, bot, rig, top, wsp, hsp = self._panellayout
    11451198        PL.gcf().subplots_adjust(left=lef,bottom=bot,right=rig,top=top,
     
    11621215    # plot total power data
    11631216    # plotting in time is not yet implemented..
     1217    @asaplog_post_dec
    11641218    def plottp(self, scan=None, outfile=None):
    11651219        if self._plotter.is_dead:
     
    11731227        if not self._data and not scan:
    11741228            msg = "Input is not a scantable"
    1175             if rcParams['verbose']:
    1176                 #print msg
    1177                 asaplog.push( msg )
    1178                 print_log( 'ERROR' )
    1179                 return
    11801229            raise TypeError(msg)
    11811230        if isinstance(scan, scantable):
     
    12071256        self._plotter.tidy()
    12081257        self._plotter.show(hardrefresh=False)
    1209         print_log()
    12101258        return
    12111259
     
    12681316
    12691317    # printing header information
     1318    @asaplog_post_dec
    12701319    def print_header(self, plot=True, fontsize=9, logger=False, selstr='', extrastr=''):
    12711320        """
     
    12741323            plot:      whether or not print header info on the plot.
    12751324            fontsize:  header font size (valid only plot=True)
    1276             autoscale: whether or not autoscale the plot (valid only plot=True)
    12771325            logger:    whether or not print header info on the logger.
    12781326            selstr:    additional selection string (not verified)
    12791327            extrastr:  additional string to print (not verified)
    12801328        """
    1281         if not plot and not logger: return
    1282         if not self._data: raise RuntimeError("No scantable has been set yet.")
     1329        if not plot and not logger:
     1330            return
     1331        if not self._data:
     1332            raise RuntimeError("No scantable has been set yet.")
    12831333        # Now header will be printed on plot and/or logger.
    12841334        # Get header information and format it.
     
    13131363            asaplog.push(extrastr)
    13141364            asaplog.push(ssum[ssum.find('Beams:'):])
    1315             print_log()
    13161365        del ssum
  • trunk/python/casatoolbar.py

    r1848 r1949  
    11import os
    22import matplotlib
     3
    34######################################
    45##    Add CASA custom toolbar       ##
     
    144145        mymask.select_mask(once=True,showmask=False)
    145146
     147    def _mod_note(self,event):
     148        # Do not fire event when in zooming/panning mode
     149        if not self.figmgr.toolbar.mode == '':
     150            return
     151        if event.button ==1:
     152            self.notewin.load_textwindow(event)
     153        elif event.button == 3 and self._note_picked(event):
     154            self.notewin.load_modmenu(event)
     155        return
     156
     157    def _note_picked(self,event):
     158        # just briefly check if any texts are picked
     159        for textobj in self.canvas.figure.texts:
     160            if textobj.contains(event)[0]:
     161                return True
     162        for ax in self.canvas.figure.axes:
     163            for textobj in ax.texts:
     164                if textobj.contains(event)[0]:
     165                    return True
     166        #print "No text picked"
     167        return False
     168
     169    def _new_page(self,next=True):
     170        self.plotter._plotter.hold()
     171        #self.plotter._plotter.clear()
     172        self.plotter._plot(self.plotter._data)
     173        self.plotter._plotter.release()
     174        self.plotter._plotter.tidy()
     175        self.plotter._plotter.show(hardrefresh=False)
     176        pass
     177
    146178#####################################
    147179##    Backend dependent Classes    ##
     
    150182if matplotlib.get_backend() == 'TkAgg':
    151183    import Tkinter as Tk
     184    from notationwindow import NotationWindowTkAgg
    152185
    153186class CustomToolbarTkAgg(CustomToolbarCommon, Tk.Frame):
     
    164197        self.button=True
    165198        self._add_custom_toolbar()
     199        self.notewin=NotationWindowTkAgg(master=self.canvas)
    166200        CustomToolbarCommon.__init__(self,parent)
    167201
     
    174208                                   text='statistics',
    175209                                   command=self.stat_cal)
     210        self.bNote=self._NewButton(master=self,
     211                                   text='notation',
     212                                   command=self.modify_note)
     213        #self.bPrev=self._NewButton(master=self,
     214        #                           text='- page',
     215        #                           command=self.prev_page)
     216        self.bNext=self._NewButton(master=self,
     217                                   text='+ page',
     218                                   command=self.next_page)
     219        if os.uname()[0] != 'Darwin':
     220            #self.bPrev.config(padx=5)
     221            self.bNext.config(padx=5)
    176222        self.bQuit=self._NewButton(master=self,
    177223                                   text='Quit',
     
    198244        self.bStat.config(relief='raised')
    199245        self.bSpec.config(relief='sunken')
     246        self.bNote.config(relief='raised')
    200247        self.mode='spec'
     248        self.notewin.close_widgets()
    201249        self.__disconnect_event()
    202250        #self.canvas.mpl_connect('button_press_event',self._select_spectrum)
     
    209257        self.bSpec.config(relief='raised')
    210258        self.bStat.config(relief='sunken')
     259        self.bNote.config(relief='raised')
    211260        self.mode='stat'
     261        self.notewin.close_widgets()
    212262        self.__disconnect_event()
    213263        self._p.register('button_press',self._single_mask)
     264
     265    def modify_note(self):
     266        if not self.figmgr.toolbar.mode == '': return
     267        self.figmgr.toolbar.set_message('text: select a position/text')
     268        if self.mode == 'note': return
     269        self.bSpec.config(relief='raised')
     270        self.bStat.config(relief='raised')
     271        self.bNote.config(relief='sunken')
     272        self.mode='note'
     273        self.__disconnect_event()
     274        self._p.register('button_press',self._mod_note)
     275
     276    def prev_page(self):
     277        self.figmgr.toolbar.set_message('plotting the previous page')
     278        self._new_page(next=False)
     279
     280    def next_page(self):
     281        self.figmgr.toolbar.set_message('plotting the next page')
     282        self._new_page(next=True)
    214283
    215284    def quit(self):
     
    230299        self.bStat.config(relief='raised', state=Tk.DISABLED)
    231300        self.bSpec.config(relief='raised', state=Tk.DISABLED)
     301        #self.bPrev.config(state=Tk.DISABLED)
     302        #self.bNext.config(state=Tk.DISABLED)
    232303        self.button=False
    233304        self.mode=''
    234305        self.__disconnect_event()
     306
     307    def enable_next(self):
     308        self.bNext.config(state=Tk.NORMAL)
     309
     310    def disable_next(self):
     311        self.bNext.config(state=Tk.DISABLED)
     312
     313    def enable_prev(self):
     314        #self.bPrev.config(state=Tk.NORMAL)
     315        pass
     316
     317    def disable_prev(self):
     318        #self.bPrev.config(state=Tk.DISABLED)
     319        pass
    235320
    236321    def delete_bar(self):
  • trunk/python/env.py

    r1848 r1949  
    1 __all__ = ["is_casapy", "is_ipython", "setup_env", "get_revision"]
     1"""This module has various functions for environment specific setings.
     2"""
     3__all__ = ["is_casapy", "is_ipython", "setup_env", "get_revision",
     4           "is_asap_cli"]
    25
    36import sys
     
    710
    811def is_casapy():
     12    """Are we running inside casapy?"""
    913    try:
    1014        from taskinit import casalog
     
    1418
    1519def is_ipython():
     20    """Are we running inside IPython?"""
    1621    return 'IPython' in sys.modules.keys()
    1722
     23def is_asap_cli():
     24    """Are we running inside asap ipython (but not casapy)"""
     25    return is_ipython() and not is_casapy()
     26
    1827def setup_env():
     28    """Set-up environment variables for casa and initialise ~/.asap on first
     29    use.
     30    """
    1931    # Set up CASAPATH and first time use of asap i.e. ~/.asap/*
    2032    plf = None
     
    5971
    6072def get_revision():
     73    """Get the revision of the software. Only useful within casapy."""
    6174    if not is_casapy:
    6275        return ' unknown '
  • trunk/python/linecatalog.py

    r1848 r1949  
    1 """
     1"""\
    22A representation of a spectral line catalog.
    3 
    4 Author: Malte Marquarding
    5 
    63"""
    74__revision__ = "$Revision$"
    85from asap._asap import linecatalog as lcbase
    9 from asap.parameters import rcParams
    106from asap.logging import asaplog
    117import os
    128
    139class linecatalog(lcbase):
    14     """
     10    """\
    1511    This class is a warpper for line catalogs. These can be either ASCII tables
    1612    or the tables saved from this class.
     13
    1714    ASCII tables have the following restrictions:
    18     Comments can be present through lines starting with '#'.
    19     The first column contains the name of the Molecule. This can't contain spaces,
    20     if it does it has to be wrapped in ""
    21     The second column contains the frequency of the transition.
    22     The third column contains the error in frequency.
    23     The fourth column contains a value describing the intensity
     15
     16        * Comments can be present through lines starting with '#'.
     17
     18        * The first column contains the name of the Molecule. This can't contain
     19          spaces, if it does it has to be wrapped in double-quotes.
     20
     21        * The second column contains the frequency of the transition.
     22
     23        * The third column contains the error in frequency.
     24
     25        * The fourth column contains a value describing the intensity.
     26
    2427    """
    2528
     
    3033        else:
    3134            msg = "File '%s' not found" % fpath
    32             if rcParams['verbose']:
    33                 #print msg
    34                 asaplog.push( msg )
    35                 print_log( 'ERROR' )
    36                 return
    37             else:
    38                 raise IOError(msg)
     35            raise IOError(msg)
    3936
    4037    def __repr__(self):
     
    5249
    5350    def set_name(self, name, mode="pattern"):
    54         """
     51        """\
    5552        Set a name restriction on the table. This can be a standard unix-style
    5653        pattern or a regular expression.
     54
    5755        Parameters:
     56
    5857            name:       the name patterrn/regex
     58
    5959            mode:       the matching mode, i.e. "pattern" (default) or "regex"
     60
    6061        """
    6162        validmodes = "pattern regex".split()
     
    6566
    6667    def set_frequency_limits(self, fmin=1.0, fmax=120.0, unit="GHz"):
    67         """
     68        """\
    6869        Set frequency limits on the table.
     70
    6971        Parameters:
     72
    7073            fmin:       the lower bound
     74
    7175            fmax:       the upper bound
     76
    7277            unit:       the frequency unit (default "GHz")
    7378
    74         Note:
    75             The underlying table conatins frequency values in MHz
     79        .. note:: The underlying table contains frequency values in MHz
    7680        """
    7781        base = { "GHz": 1000.0, "MHz": 1.0 }
     
    8286
    8387    def set_strength_limits(self, smin, smax):
    84         """
     88        """\
    8589        Set line strength limits on the table (arbitrary units)
     90
    8691        Parameters:
     92
    8793            smin:       the lower bound
     94
    8895            smax:       the upper bound
     96
    8997        """
    9098        lcbase.set_strength_limits(self, smin, smax)
    9199
    92100    def save(self, name, overwrite=False):
    93         """
     101        """\
    94102        Save the subset of the table to disk. This uses an internal data format
    95103        and can be read in again.
     
    99107            if not overwrite:
    100108                msg = "File %s exists." % name
    101                 if rcParams['verbose']:
    102                     #print msg
    103                     asaplog.push( msg )
    104                     print_log( 'ERROR' )
    105                     return
    106                 else:
    107                     raise IOError(msg)
     109                raise IOError(msg)
    108110        lcbase.save(self, name)
    109111
    110112    def reset(self):
    111         """
    112         Reset the table to its initial state, i.e. undo all calls to set_
     113        """\
     114        Reset the table to its initial state, i.e. undo all calls to ``set_``.
    113115        """
    114116        lcbase.reset(self)
    115117
    116118    def get_row(self, row=0):
     119        """\
     120        Get the values in a specified row of the table.
     121
     122        Parameters:
     123
     124              row:        the row to retrieve
     125
    117126        """
    118         Get the values in a specified row of the table.
    119         Parameters:
    120               row:        the row to retrieve
    121         """
     127        if row < 0 or row > len(self)-1:
     128            raise IndexError("Row index out of bounds.")
    122129        freq = lcbase.get_frequency(self, row)
    123130        name = lcbase.get_name(self, row)
     
    128135
    129136    def __getitem__(self, k):
    130         if k < 0: k = self.nrow()-k
     137        if k < 0:
     138            k = self.nrow()-k
    131139        return self.get_row(k)
  • trunk/python/logging.py

    r1848 r1949  
    1 __all__ = ["asaplog", "print_log", "print_log_dec"]
     1"""This module presents a logging abstraction layer on top of casa.
     2"""
     3__all__ = ["asaplog", "asaplog_post_dec", "AsapLogger"]
    24
     5import inspect
    36from asap.env import is_casapy
    47from asap.parameters import rcParams
     
    1013
    1114
    12 class _asaplog(object):
    13     """Wrapper object to allow for both casapy and asap logging"""
     15class AsapLogger(object):
     16    """Wrapper object to allow for both casapy and asap logging.
     17
     18    Inside casapy this will connect to `taskinit.casalog`. Otherwise it will
     19    create its own casa log sink.
     20
     21    .. note:: Do instantiate a new one - use the :obj:`asaplog` instead.
     22
     23    """
    1424    def __init__(self):
    15         self._enabled = False
     25        self._enabled = True
    1626        self._log = ""
    1727        if is_casapy():
     
    2232            set_global_sink(self.logger)
    2333
    24     def post(self, level):
     34    def post(self, level='INFO', origin=""):
    2535        """Post the messages to the logger. This will clear the buffered
    2636        logs.
     37
     38        Parameters:
     39
     40            level:  The log level (severity). One of INFO, WARN, ERROR.
     41
    2742        """
    2843        if not self._enabled:
    2944            return
    30         if not rcParams['verbose']:
    31             return
    3245
     46        if not origin:
     47            origin = inspect.getframeinfo(inspect.currentframe().f_back)[2]
    3348        logs = self._log.strip()
    3449        if len(logs) > 0:
    35            self.logger.post(logs, priority=level)
     50            if isinstance(self.logger, LogSink):
     51                #can't handle unicode in boost signature
     52                logs = str(logs)
     53            self.logger.post(logs, priority=level, origin=origin)
    3654        if isinstance(self.logger, LogSink):
    3755            logs = self.logger.pop().strip()
     
    4159
    4260    def push(self, msg, newline=True):
    43         """Push logs into the buffer. post needs to be called to send them."""
    44         from asap import rcParams
     61        """Push logs into the buffer. post needs to be called to send them.
     62
     63        Parameters:
     64
     65            msg:        the log message (string)
     66
     67            newline:    should we terminate with a newline (default yes)
     68
     69        """
    4570        if self._enabled:
    46             if rcParams["verbose"]:
    47                 sep = ""
    48                 self._log = sep.join([self._log, msg])
    49                 if newline:
    50                     self._log += "\n"
     71            sep = ""
     72            self._log = sep.join([self._log, msg])
     73            if newline:
     74                self._log += "\n"
    5175
    5276    def enable(self, flag=True):
     
    5882        self._enabled = flag
    5983
    60 asaplog = _asaplog()
     84    def is_enabled(self):
     85        return self._enabled
    6186
    62 def print_log_dec(f, level='INFO'):
     87asaplog = AsapLogger()
     88"""Default asap logger"""
     89
     90def asaplog_post_dec(f):
     91    """Decorator which posts log at completion of the wrapped method.
     92
     93    Example::
     94
     95        @asaplog_post_dec
     96        def test(self):
     97            do_stuff()
     98            asaplog.push('testing...', False)
     99            do_more_stuff()
     100            asaplog.push('finished')
     101    """
    63102    @wraps_dec(f)
    64103    def wrap_it(*args, **kw):
    65         val = f(*args, **kw)
    66         print_log(level)
    67         return val
     104        level = "INFO"
     105        try:
     106            val = f(*args, **kw)
     107            return val
     108        except Exception, ex:
     109            level = "ERROR"
     110            asaplog.push(str(ex))
     111            if rcParams['verbose']:
     112                pass
     113            else:
     114                raise
     115        finally:
     116            asaplog.post(level, f.func_name)
     117            #asaplog.post(level, ".".join([f.__module__,f.func_name]))
    68118    return wrap_it
    69119
    70 def print_log(level='INFO'):
    71     """Alias for asaplog.post."""
    72     asaplog.post(level)
  • trunk/python/opacity.py

    r1848 r1949  
    66from asap.asapfitter import fitter
    77from asap.selector import selector
    8 from asap.parameters import rcParams
    98from asap._asap import atmosphere
    109
     
    5150
    5251    def get_opacities(self, freq, elevation=None):
    53         """Get the opacity value(s) for the fiven frequency(ies).
     52        """Get the opacity value(s) for the given frequency(ies).
    5453        If no elevation is given the opacities for the zenith are returned.
    5554        If an elevation is specified refraction is also taken into account.
     
    148147                    is corrupted (Mopra). If set to 'False', an opacity value
    149148                    per polarisation is returned.
    150         tksy:       The sky temperature (default 300.0K). This might
     149        tsky:       The sky temperature (default 300.0K). This might
    151150                    be read from the data in the future.
    152151        plot:       Plot each fit (airmass vs. Tsys). Default is 'False'
    153152    """
    154     rcsave = rcParams['verbose']
    155     rcParams['verbose'] = False
    156153    if plot:
    157154        from matplotlib import pylab
     
    222219
    223220    scan.set_selection(basesel)
    224     rcParams['verbose'] = rcsave
    225221    if plot:
    226222        pylab.close()
  • trunk/python/parameters.py

    r1848 r1949  
     1"""This module provides functions to set up resource parameters (rc).
     2These can be set in a file .asaprc or using functions.
     3"""
    14__all__ = ["rc", "list_rcparameters", "rcParams", "rcParamsDefault"]
    25
     
    8285    print """
    8386# general
    84 # print verbose output
     87# only valid in asap standard mode not in scripts or casapy
     88# It will disable exceptions and just print the messages
    8589verbose                    : True
    8690
     
    173177            print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
    174178            #asaplog.push('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
    175             #print_log('WARN')
     179            #asaplog.post('WARN')
    176180            continue
    177181
     
    181185            print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
    182186            #asaplog.push('Bad key "%s" on line %d in %s' % (key, cnt, fname))
    183             #print_log('WARN')
     187            #asaplog.post('WARN')
    184188            continue
    185189
     
    193197            print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
    194198            #asaplog.push('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, str(msg)))
    195             #print_log('WARN')
     199            #asaplog.post('WARN')
    196200            continue
    197201        else:
  • trunk/python/scantable.py

    r1848 r1949  
    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)
  • trunk/python/selector.py

    r1848 r1949  
    1 from asap._asap import selector as _selector
     1import re
     2from asap._asap import selector as _selector, srctype
    23from asap.utils import unique, _to_list
    34
     
    78    scantables to specific rows.
    89    """
    9     fields = ["pols", "ifs", "beams", "scans", "cycles", "name", "query"]
     10    fields = ["pols", "ifs", "beams", "scans", "cycles", "name", "query", "types", "rows"]
    1011
    1112    def __init__(self, *args, **kw):
     
    148149        Example:
    149150            # select all off scans with integration times over 60 seconds.
    150             selection.set_query("SRCTYPE == 1 AND INTERVAL > 60.0")
    151         """
     151            selection.set_query("SRCTYPE == PSOFF AND INTERVAL > 60.0")
     152        """
     153        rx = re.compile("((SRCTYPE *[!=][=] *)([a-zA-Z.]+))", re.I)
     154        for r in rx.findall(query):
     155            sval = None
     156            stype = r[-1].lower()
     157            if stype.find('srctype.') == -1:
     158                stype = ".".join(["srctype", stype])
     159            try:
     160                sval = eval(stype)
     161                sval = "%s%d" % (r[1], sval)
     162            except:
     163                continue
     164            query = query.replace(r[0], sval)
    152165        taql = "SELECT FROM $1 WHERE " + query
    153166        self._settaql(taql)
     
    203216    def get_types(self):
    204217        return list(self._gettypes())
     218    def get_rows(self):
     219        return list(self._getrows())
    205220    def get_query(self):
    206221        prefix = "SELECT FROM $1 WHERE "
     
    220235             "POLNO": self.get_pols(),
    221236             "QUERY": self.get_query(),
     237             "SRCTYPE": self.get_types(),
     238             "ROWS": self.get_rows(),
    222239             "Sort Order": self.get_order()
    223240             }
  • trunk/python/utils.py

    r1848 r1949  
    6161    if not os.path.isdir(path):
    6262        return None
    63     valid = "rpf rpf.1 rpf.2 sdf sdfits mbf asap".split()
     63    valid = "ms rpf rpf.1 rpf.2 sdf sdfits mbf asap".split()
    6464    if not suffix in valid:
    6565        return None
    6666    files = [os.path.expanduser(os.path.expandvars(path+"/"+f)) for f in os.listdir(path)]
    6767    return filter(lambda x: x.endswith(suffix),files)
     68
     69def page(message):
     70    """Run the input message through a pager. This is only done if
     71    ``rcParams["verbose"]`` is set.
     72    """
     73    verbose = False
     74    try:
     75        from asap.parameters import rcParams
     76        verbose = rcParams['verbose']
     77    except:
     78        pass
     79    if verbose:
     80        try:
     81            from IPython.genutils import page as pager
     82        except ImportError:
     83            from pydoc import pager
     84        pager(message)
     85        return None
     86    else:
     87        return message
Note: See TracChangeset for help on using the changeset viewer.