Changeset 1859


Ignore:
Timestamp:
08/05/10 14:40:38 (14 years ago)
Author:
Malte Marquarding
Message:

Ticket #193: the rcParamsverbose? flag is only used in standard asap cli mode. Otherwise log messages are always send to the logger and one needs to call asaplog.disable()/asaplog.enable() to controls this. I have also added the function name as the log origin.

Location:
trunk
Files:
13 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/__init__.py

    r1835 r1859  
    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()
  • trunk/python/asapfitter.py

    r1826 r1859  
    4949        return
    5050
     51    @print_log_dec
    5152    def set_scan(self, thescan=None, mask=None):
    5253        """
     
    5859        if not thescan:
    5960            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)
     61            raise TypeError(msg)
    6762        self.fitted = False
    6863        self.data = thescan
     
    7469        return
    7570
     71    @print_log_dec
    7672    def set_function(self, **kwargs):
    7773        """
     
    114110        else:
    115111            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)
     112            raise TypeError(msg)
    123113
    124114        self.fitter.setexpression(self.fitfunc,n)
     
    146136               or self.fitfunc is None:
    147137            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)
     138            raise RuntimeError(msg)
    155139
    156140        else:
     
    172156            if len(ps) == 0 or estimate:
    173157                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
     158        fxdpar = list(self.fitter.getfixedparameters())
     159        if len(fxdpar) and fxdpar.count(0) == 0:
     160             raise RuntimeError,"No point fitting, if all parameters are fixed."
     161        if self.uselinear:
     162            converged = self.fitter.lfit()
     163        else:
     164            converged = self.fitter.fit()
     165        if not converged:
     166            raise RuntimeError,"Fit didn't converge."
    192167        self._fittedrow = row
    193168        self.fitted = True
    194         print_log()
    195169        return
    196170
     
    244218        if self.fitfunc is None:
    245219            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)
     220            raise RuntimeError(msg)
    253221        if (self.fitfunc == "gauss" or self.fitfunc == 'lorentz') and component is not None:
    254222            if not self.fitted and sum(self.fitter.getparameters()) == 0:
     
    266234        if fixed is not None:
    267235            self.fitter.setfixedparameters(fixed)
    268         print_log()
    269236        return
    270237
     238    @print_log_dec
    271239    def set_gauss_parameters(self, peak, centre, fwhm,
    272240                             peakfixed=0, centrefixed=0,
     
    288256        if self.fitfunc != "gauss":
    289257            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)
     258            raise ValueError(msg)
    297259        if 0 <= component < len(self.components):
    298260            d = {'params':[peak, centre, fwhm],
     
    301263        else:
    302264            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 
     265            raise ValueError(msg)
     266
     267    @print_log_dec
    311268    def set_lorentz_parameters(self, peak, centre, fwhm,
    312269                             peakfixed=0, centrefixed=0,
     
    328285        if self.fitfunc != "lorentz":
    329286            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)
     287            raise ValueError(msg)
    337288        if 0 <= component < len(self.components):
    338289            d = {'params':[peak, centre, fwhm],
     
    341292        else:
    342293            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)
     294            raise ValueError(msg)
    350295
    351296    def get_area(self, component=None):
     
    378323            return sum(areas)
    379324
     325    @print_log_dec
    380326    def get_errors(self, component=None):
    381327        """
     
    387333        if not self.fitted:
    388334            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)
     335            raise RuntimeError(msg)
    396336        errs = list(self.fitter.geterrors())
    397337        cerrs = errs
     
    403343        return cerrs
    404344
     345
     346    @print_log_dec
    405347    def get_parameters(self, component=None, errors=False):
    406348        """
     
    412354        if not self.fitted:
    413355            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)
     356            raise RuntimeError(msg)
    421357        pars = list(self.fitter.getparameters())
    422358        fixed = list(self.fitter.getfixedparameters())
     
    444380                  area += [a for i in range(3)]
    445381        fpars = self._format_pars(cpars, cfixed, errors and cerrs, area)
    446         if rcParams['verbose']:
    447             #print fpars
    448             asaplog.push(fpars)
    449             print_log()
     382        asaplog.push(fpars)
    450383        return {'params':cpars, 'fixed':cfixed, 'formatted': fpars,
    451384                'errors':cerrs}
     
    481414        return out
    482415
     416
     417    @print_log_dec
    483418    def get_estimate(self):
    484419        """
     
    487422        pars = self.fitter.getestimate()
    488423        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()
     424        asaplog.push(self._format_pars(pars,fixed,None))
    493425        return pars
    494426
     427    @print_log_dec
    495428    def get_residual(self):
    496429        """
     
    499432        if not self.fitted:
    500433            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)
     434            raise RuntimeError(msg)
    508435        return self.fitter.getresidual()
    509436
     437    @print_log_dec
    510438    def get_chi2(self):
    511439        """
     
    514442        if not self.fitted:
    515443            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)
     444            raise RuntimeError(msg)
    523445        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()
     446        asaplog.push( 'Chi^2 = %3.3f' % (ch2) )
    528447        return ch2
    529448
     449    @print_log_dec
    530450    def get_fit(self):
    531451        """
     
    534454        if not self.fitted:
    535455            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)
     456            raise RuntimeError(msg)
    543457        return self.fitter.getfit()
    544458
     
    550464        if not self.fitted:
    551465            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)
     466            raise RuntimeError(msg)
    559467        from asap import scantable
    560468        if not isinstance(self.data, scantable):
    561469            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)
     470            raise TypeError(msg)
    569471        scan = self.data.copy()
    570472        scan._setspectrum(self.fitter.getresidual())
    571         print_log()
    572473        return scan
    573474
     
    671572        if (not rcParams['plotter.gui']):
    672573            self._p.save(filename)
    673         print_log()
    674574
    675575    @print_log_dec
     
    683583        if not isinstance(self.data, scantable) :
    684584            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)
     585            raise TypeError(msg)
    692586        if insitu is None: insitu = rcParams['insitu']
    693587        if not insitu:
     
    725619            self._p.unmap()
    726620            self._p = None
    727         print_log()
    728621        return scan
  • trunk/python/asapmath.py

    r1827 r1859  
    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@print_log_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
     
    138132    s = scantable(stm._dototalpower(calon, caloff, tcalval))
    139133    s._add_history("dototalpower",varlist)
    140     print_log()
    141134    return s
    142135
     
    159152    s = scantable(stm._dosigref(sig, ref, smooth, tsysval, tauval))
    160153    s._add_history("dosigref",varlist)
    161     print_log()
    162154    return s
    163155
     
    190182##     if s is None:
    191183##         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)
     184##         raise TypeError(msg)
    199185    s = scantab.copy()
    200186    from asap._asap import srctype
     
    205191    except Exception, e:
    206192        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)
     193        raise TypeError(msg)
    214194    s.set_selection()
    215195    sel.reset()
     
    217197    if ssub is None:
    218198        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)
     199        raise TypeError(msg)
    226200    #ssubon = ssub.get_scan('*calon')
    227201    #ssuboff = ssub.get_scan('*[^calon]')
     
    238212    if ssubon.nrow() != ssuboff.nrow():
    239213        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)
     214        raise TypeError(msg)
    247215    cals = dototalpower(ssubon, ssuboff, tcalval)
    248216    #sig = cals.get_scan('*ps')
     
    260228    if sig.nscan() != ref.nscan():
    261229        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)
     230        raise TypeError(msg)
    269231
    270232    #for user supplied Tsys
     
    272234        if tauval<=0.0:
    273235            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)
     236            raise TypeError(msg)
    281237        else:
    282238            sig.recalc_azel()
    283239            ref.recalc_azel()
    284240            #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)
     241            #raise TypeError(msg)
    290242            # use get_elevation to get elevation and
    291243            # calculate a scaling factor using the formula
     
    442394    ###
    443395    ress._add_history("calps", varlist)
    444     print_log()
    445396    return ress
    446397
     
    469420##     if s is None:
    470421##         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)
     422##         raise TypeError(msg)
    478423    s = scantab.copy()
    479424    sel = selector()
     
    483428    except Exception, e:
    484429        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)
     430        raise TypeError(msg)
    492431    sel.reset()
    493432    del sel
     
    511450        #if len(scannos)>2:
    512451        #    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)
     452        #    raise TypeError(msg)
    518453        #
    519454        #if len(scannos)==2:
     
    525460        if tauval<=0.0:
    526461            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)
     462            raise TypeError(msg)
    534463        else:
    535464            scantab.recalc_azel()
     
    683612    ###
    684613    resspec._add_history("calnod",varlist)
    685     print_log()
    686614    return resspec
    687615
     
    716644#    if check is None:
    717645#        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)
     646#        raise TypeError(msg)
    723647    s = scantab.get_scan(scannos)
    724648    del scantab
     
    891815    ###
    892816    resspec._add_history("calfs",varlist)
    893     print_log()
    894817    return resspec
    895818
     
    921844        if not isinstance(s,scantable):
    922845            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)
     846            raise TypeError(msg)
    930847    s = scantable(stm._merge(lst))
    931848    s._add_history("merge", varlist)
    932     print_log()
    933849    return s
    934850
     851@print_log_dec
    935852def calibrate( scantab, scannos=[], calmode='none', verify=None ):
    936853    """
     
    946863    if ( calmode == 'nod' ):
    947864        asaplog.push( 'Calibrating nod data.' )
    948         print_log()
    949865        scal = calnod( scantab, scannos=scannos, verify=verify )
    950866    elif ( calmode == 'quotient' ):
    951867        asaplog.push( 'Calibrating using quotient.' )
    952         print_log()
    953868        scal = scantab.auto_quotient( verify=verify )
    954869    elif ( calmode == 'ps' ):
    955870        asaplog.push( 'Calibrating %s position-switched data.' % antname )
    956         print_log()
    957871        if ( antname.find( 'APEX' ) != -1 ):
    958872            scal = apexcal( scantab, scannos, calmode, verify )
     
    963877    elif ( calmode == 'fs' or calmode == 'fsotf' ):
    964878        asaplog.push( 'Calibrating %s frequency-switched data.' % antname )
    965         print_log()
    966879        if ( antname.find( 'APEX' ) != -1 ):
    967880            scal = apexcal( scantab, scannos, calmode, verify )
     
    972885    elif ( calmode == 'otf' ):
    973886        asaplog.push( 'Calibrating %s On-The-Fly data.' % antname )
    974         print_log()
    975887        scal = almacal( scantab, scannos, calmode, verify )
    976888    else:
     
    1015927    return scal
    1016928
     929@print_log_dec
    1017930def splitant(filename, outprefix='',overwrite=False):
    1018931    """
     
    1032945    """
    1033946    # 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
     947
     948    import casac
     949    tbtool = casac.homefinder.find_home_by_name('tableHome')
     950    tb = tbtool.create()
     951    tb2 = tbtool.create()
    1056952    # Check the input filename
    1057953    if isinstance(filename, str):
     
    1061957        if not os.path.exists(filename):
    1062958            s = "File '%s' not found." % (filename)
    1063             if rcParams['verbose']:
    1064                 print_log()
    1065                 asaplog.push(s)
    1066                 print_log('ERROR')
    1067                 return
    1068959            raise IOError(s)
    1069960        # check if input file is MS
     
    1072963               or not os.path.exists(filename+'/table.f1'):
    1073964            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
    1079965            raise IOError(s)
    1080966    else:
    1081967        s = "The filename should be string. "
    1082         if rcParams['verbose']:
    1083             print_log()
    1084             asaplog.push(s)
    1085             print_log('ERROR')
    1086             return
    1087968        raise TypeError(s)
    1088969    # Check out put file name
     
    1110991    return outfiles
    1111992
     993@print_log_dec
    1112994def _array2dOp( scan, value, mode="ADD", tsys=False ):
    1113995    """
     
    11281010        del stm
    11291011    elif len( value ) != nrow:
    1130         asaplog.push( 'len(value) must be 1 or conform to scan.nrow()' )
    1131         print_log( 'ERROR' )
     1012        raise ValueError( 'len(value) must be 1 or conform to scan.nrow()' )
    11321013    else:
    11331014        from asap._asap import stmath
  • trunk/python/asapplotter.py

    r1858 r1859  
    102102        if not self._data and not scan:
    103103            msg = "Input is not a scantable"
    104             if rcParams['verbose']:
    105                 #print msg
    106                 asaplog.push( msg )
    107                 print_log( 'ERROR' )
    108                 return
    109104            raise TypeError(msg)
    110105        if scan: self.set_data(scan,refresh=False)
     
    277272    # end matplotlib.axes fowarding functions
    278273
     274    @print_log_dec
    279275    def set_data(self, scan, refresh=True):
    280276        """
     
    299295                    msg = "A new scantable is set to the plotter. The masks and data selections are reset."
    300296                    asaplog.push( msg )
    301                     print_log( 'INFO' )
    302297            else:
    303298                self._data = scan
     
    305300        else:
    306301            msg = "Input is not a scantable"
    307             if rcParams['verbose']:
    308                 #print msg
    309                 asaplog.push( msg )
    310                 print_log( 'ERROR' )
    311                 return
    312302            raise TypeError(msg)
    313303
     
    320310        if refresh: self.plot()
    321311
    322 
     312    @print_log_dec
    323313    def set_mode(self, stacking=None, panelling=None, refresh=True):
    324314        """
     
    343333        if not self.set_panelling(panelling) or \
    344334               not self.set_stacking(stacking):
    345             if rcParams['verbose']:
    346                 #print msg
    347                 asaplog.push( msg )
    348                 print_log( 'ERROR' )
    349                 return
    350             else:
    351                 raise TypeError(msg)
     335            raise TypeError(msg)
    352336        if refresh and self._data: self.plot(self._data)
    353337        return
     
    745729        return
    746730
    747 
     731    @print_log_dec
    748732    def set_mask(self, mask=None, selection=None, refresh=True):
    749733        """
     
    763747        if not self._data:
    764748            msg = "Can only set mask after a first call to plot()"
    765             if rcParams['verbose']:
    766                 #print msg
    767                 asaplog.push( msg )
    768                 print_log( 'ERROR' )
    769                 return
    770             else:
    771                 raise RuntimeError(msg)
     749            raise RuntimeError(msg)
    772750        if len(mask):
    773751            if isinstance(mask, list) or isinstance(mask, tuple):
     
    11711149    # plot total power data
    11721150    # plotting in time is not yet implemented..
     1151    @print_log_dec
    11731152    def plottp(self, scan=None, outfile=None):
    11741153        if self._plotter.is_dead:
     
    11821161        if not self._data and not scan:
    11831162            msg = "Input is not a scantable"
    1184             if rcParams['verbose']:
    1185                 #print msg
    1186                 asaplog.push( msg )
    1187                 print_log( 'ERROR' )
    1188                 return
    11891163            raise TypeError(msg)
    11901164        if isinstance(scan, scantable):
     
    12161190        self._plotter.tidy()
    12171191        self._plotter.show(hardrefresh=False)
    1218         print_log()
    12191192        return
    12201193
     
    12771250
    12781251    # printing header information
     1252    @print_log_dec
    12791253    def print_header(self, plot=True, fontsize=9, logger=False, selstr='', extrastr=''):
    12801254        """
     
    12881262            extrastr:  additional string to print (not verified)
    12891263        """
    1290         if not plot and not logger: return
    1291         if not self._data: raise RuntimeError("No scantable has been set yet.")
     1264        if not plot and not logger:
     1265            return
     1266        if not self._data:
     1267            raise RuntimeError("No scantable has been set yet.")
    12921268        # Now header will be printed on plot and/or logger.
    12931269        # Get header information and format it.
     
    13221298            asaplog.push(extrastr)
    13231299            asaplog.push(ssum[ssum.find('Beams:'):])
    1324             print_log()
    13251300        del ssum
  • trunk/python/env.py

    r1858 r1859  
    11"""This module has various functions for environment specific setings.
    22"""
    3 __all__ = ["is_casapy", "is_ipython", "setup_env", "get_revision"]
     3__all__ = ["is_casapy", "is_ipython", "setup_env", "get_revision",
     4           "is_asap_cli"]
    45
    56import sys
     
    1920    """Are we running inside IPython?"""
    2021    return 'IPython' in sys.modules.keys()
     22
     23def is_asap_cli():
     24    """Are we running inside asap ipython (but not casapy)"""
     25    return is_ipython() and not is_casapy()
    2126
    2227def setup_env():
  • trunk/python/linecatalog.py

    r1826 r1859  
    77__revision__ = "$Revision$"
    88from asap._asap import linecatalog as lcbase
    9 from asap.parameters import rcParams
    109from asap.logging import asaplog
    1110import os
     
    3029        else:
    3130            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)
     31            raise IOError(msg)
    3932
    4033    def __repr__(self):
     
    9992            if not overwrite:
    10093                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)
     94                raise IOError(msg)
    10895        lcbase.save(self, name)
    10996
  • trunk/python/logging.py

    r1858 r1859  
    1919
    2020    .. note:: Do instantiate a new one - use the :obj:`asaplog` instead.
    21    
     21
    2222    """
    2323    def __init__(self):
    24         self._enabled = False
     24        self._enabled = True
    2525        self._log = ""
    2626        if is_casapy():
     
    3131            set_global_sink(self.logger)
    3232
    33     def post(self, level):
     33    def post(self, level, origin=""):
    3434        """Post the messages to the logger. This will clear the buffered
    3535        logs.
     
    4242        if not self._enabled:
    4343            return
    44         if not rcParams['verbose']:
    45             return
    4644
    4745        logs = self._log.strip()
    4846        if len(logs) > 0:
    49            self.logger.post(logs, priority=level)
     47            self.logger.post(logs, priority=level, origin=origin)
    5048        if isinstance(self.logger, LogSink):
    5149            logs = self.logger.pop().strip()
     
    6462
    6563        """
    66         from asap import rcParams
    6764        if self._enabled:
    68             if rcParams["verbose"]:
    69                 sep = ""
    70                 self._log = sep.join([self._log, msg])
    71                 if newline:
    72                     self._log += "\n"
     65            sep = ""
     66            self._log = sep.join([self._log, msg])
     67            if newline:
     68                self._log += "\n"
    7369
    7470    def enable(self, flag=True):
     
    8076        self._enabled = flag
    8177
     78    def is_enabled(self):
     79        return self._enabled
     80
    8281asaplog = AsapLogger()
    8382"""Default asap logger"""
    8483
    85 def print_log_dec(f, level='INFO'):
     84def print_log_dec(f):
    8685    """Decorator which posts log at completion of the wrapped method.
     86
    8787    Example::
    8888
     
    9696    @wraps_dec(f)
    9797    def wrap_it(*args, **kw):
    98         val = f(*args, **kw)
    99         print_log(level)
    100         return val
     98        level = "INFO"
     99        try:
     100            val = f(*args, **kw)
     101            return val
     102        except Exception, ex:
     103            level = "ERROR"
     104            asaplog.push(str(ex))
     105            if rcParams['verbose']:
     106                pass
     107            else:
     108                raise
     109        finally:
     110            print_log(level, f.func_name)
    101111    return wrap_it
    102112
    103 def print_log(level='INFO'):
     113def print_log(level='INFO', origin=""):
    104114    """Alias for asaplog.post(level)"""
    105     asaplog.post(level)
     115    asaplog.post(level, origin)
  • trunk/python/opacity.py

    r1826 r1859  
    66from asap.asapfitter import fitter
    77from asap.selector import selector
    8 from asap.parameters import rcParams
    98from asap._asap import atmosphere
    109
     
    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/scantable.py

    r1857 r1859  
    1515from asap.linecatalog import linecatalog
    1616from asap.coordinate import coordinate
    17 from asap.utils import _n_bools, mask_not, mask_and, mask_or
     17from asap.utils import _n_bools, mask_not, mask_and, mask_or, page
    1818
    1919
     
    101101                    tmpstr=tmpstr+antenna[i]+','
    102102                else:
    103                     asaplog.push('Bad antenna selection.')
    104                     print_log('ERROR')
    105                     return
     103                    raise TypeError('Bad antenna selection.')
    106104            antenna = tmpstr.rstrip(',')
    107105        parallactify = parallactify or rcParams['scantable.parallactify']
     
    117115                if not os.path.exists(filename):
    118116                    s = "File '%s' not found." % (filename)
    119                     if rcParams['verbose']:
    120                         asaplog.push(s)
    121                         print_log('ERROR')
    122                         return
    123117                    raise IOError(s)
    124118                if is_scantable(filename):
     
    133127                    msg = "The given file '%s'is not a valid " \
    134128                          "asap table." % (filename)
    135                     if rcParams['verbose']:
    136                         #print msg
    137                         asaplog.push( msg )
    138                         print_log( 'ERROR' )
    139                         return
    140                     else:
    141                         raise IOError(msg)
     129                    raise IOError(msg)
    142130                else:
    143131                    self._fill([filename], unit, average, getpt, antenna)
     
    191179            if not overwrite:
    192180                msg = "File %s exists." % name
    193                 if rcParams['verbose']:
    194                     #print msg
    195                     asaplog.push( msg )
    196                     print_log( 'ERROR' )
    197                     return
    198                 else:
    199                     raise IOError(msg)
     181                raise IOError(msg)
    200182        format2 = format.upper()
    201183        if format2 == 'ASAP':
     
    236218        from asap import unique
    237219        if not _is_valid(scanid):
    238             if rcParams['verbose']:
    239                 asaplog.push( 'Please specify a scanno to drop from the scantable' )
    240                 print_log( 'ERROR' )
    241                 return
    242             else:
    243                 raise RuntimeError("No scan given")
    244         try:
    245             scanid = _to_list(scanid)
    246             allscans = unique([ self.getscan(i) for i in range(self.nrow())])
    247             for sid in scanid: allscans.remove(sid)
    248             if len(allscans) == 0:
    249                 raise ValueError("Can't remove all scans")
    250         except ValueError:
    251             if rcParams['verbose']:
    252                 print_log()
    253                 asaplog.push( "Couldn't find any match." )
    254                 print_log( 'ERROR' )
    255                 return
    256             else: raise
    257         try:
    258             sel = selector(scans=allscans)
    259             return self._select_copy(sel)
    260         except RuntimeError:
    261             if rcParams['verbose']:
    262                 print_log()
    263                 asaplog.push( "Couldn't find any match." )
    264                 print_log( 'ERROR' )
    265             else:
    266                 raise
     220            raise RuntimeError( 'Please specify a scanno to drop from the scantable' )
     221        scanid = _to_list(scanid)
     222        allscans = unique([ self.getscan(i) for i in range(self.nrow())])
     223        for sid in scanid: allscans.remove(sid)
     224        if len(allscans) == 0:
     225            raise ValueError("Can't remove all scans")
     226        sel = selector(scans=allscans)
     227        return self._select_copy(sel)
    267228
    268229    def _select_copy(self, selection):
     
    299260        """
    300261        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 
     262            raise RuntimeError( 'Please specify a scan no or name to '
     263                                'retrieve from the scantable' )
    311264        try:
    312265            bsel = self.get_selection()
     
    323276            else:
    324277                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)
     278                raise TypeError(msg)
    331279        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
     280            raise
    338281
    339282    def __str__(self):
     
    362305            else:
    363306                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
     307                raise IOError(msg)
     308        return page(info)
    378309
    379310    def get_spectrum(self, rowno):
     
    518449            return workscan
    519450
    520     #def stats(self, stat='stddev', mask=None):
     451    @print_log_dec
    521452    def stats(self, stat='stddev', mask=None, form='3.3f'):
    522453        """\
     
    591522            out +=  sep+"\n"
    592523
    593         if rcParams['verbose']:
    594             import os
    595             if os.environ.has_key( 'USER' ):
    596                 usr=os.environ['USER']
    597             else:
    598                 import commands
    599                 usr=commands.getoutput( 'whoami' )
    600             tmpfile='/tmp/tmp_'+usr+'_casapy_asap_scantable_stats'
    601             f=open(tmpfile,'w')
    602             print >> f, sep
    603             print >> f, ' %s %s' % (label, statunit)
    604             print >> f, sep
    605             print >> f, out
    606             f.close()
    607             f=open(tmpfile,'r')
    608             x=f.readlines()
    609             f.close()
    610             blanc=''
    611             asaplog.push(blanc.join(x), False)
    612             #for xx in x:
    613             #    asaplog.push( xx, False )
    614             print_log()
     524
     525        import os
     526        if os.environ.has_key( 'USER' ):
     527            usr = os.environ['USER']
     528        else:
     529            import commands
     530            usr = commands.getoutput( 'whoami' )
     531        tmpfile = '/tmp/tmp_'+usr+'_casapy_asap_scantable_stats'
     532        f = open(tmpfile,'w')
     533        print >> f, sep
     534        print >> f, ' %s %s' % (label, statunit)
     535        print >> f, sep
     536        print >> f, out
     537        f.close()
     538        f = open(tmpfile,'r')
     539        x = f.readlines()
     540        f.close()
     541        asaplog.push(''.join(x), False)
     542
    615543        return statvals
    616544
     
    727655            out += '= %3.3f\n' % (outvec[i])
    728656            out +=  sep+'\n'
    729         if rcParams['verbose']:
    730             asaplog.push(sep)
    731             asaplog.push(" %s" % (label))
    732             asaplog.push(sep)
    733             asaplog.push(out)
    734             print_log()
     657
     658        asaplog.push(sep)
     659        asaplog.push(" %s" % (label))
     660        asaplog.push(sep)
     661        asaplog.push(out)
     662        print_log()
    735663        return outvec
    736664
     
    945873        else:
    946874            msg  = "Please specify a valid freq type. Valid types are:\n", valid
    947             if rcParams['verbose']:
    948                 #print msg
    949                 asaplog.push( msg )
    950                 print_log( 'ERROR' )
    951             else:
    952                 raise TypeError(msg)
    953 
     875            raise TypeError(msg)
     876
     877    @print_log_dec
    954878    def set_dirframe(self, frame=""):
    955879        """\
     
    967891        """
    968892        varlist = vars()
    969         try:
    970             Scantable.set_dirframe(self, frame)
    971         except RuntimeError, msg:
    972             if rcParams['verbose']:
    973                 #print msg
    974                 print_log()
    975                 asaplog.push( str(msg) )
    976                 print_log( 'ERROR' )
    977             else:
    978                 raise
     893        Scantable.set_dirframe(self, frame)
    979894        self._add_history("set_dirframe", varlist)
    980895
     
    1013928        return abc, lbl
    1014929
     930    @print_log_dec
    1015931    def flag(self, mask=None, unflag=False):
    1016932        """\
     
    1027943        varlist = vars()
    1028944        mask = mask or []
    1029         try:
    1030             self._flag(mask, unflag)
    1031         except RuntimeError, msg:
    1032             if rcParams['verbose']:
    1033                 #print msg
    1034                 print_log()
    1035                 asaplog.push( str(msg) )
    1036                 print_log( 'ERROR' )
    1037                 return
    1038             else: raise
     945        self._flag(mask, unflag)
    1039946        self._add_history("flag", varlist)
    1040947
     948    @print_log_dec
    1041949    def flag_row(self, rows=[], unflag=False):
    1042950        """\
     
    1052960        """
    1053961        varlist = vars()
    1054         try:
    1055             self._flag_row(rows, unflag)
    1056         except RuntimeError, msg:
    1057             if rcParams['verbose']:
    1058                 print_log()
    1059                 asaplog.push( str(msg) )
    1060                 print_log('ERROR')
    1061                 return
    1062             else: raise
     962        self._flag_row(rows, unflag)
    1063963        self._add_history("flag_row", varlist)
    1064964
     965    @print_log_dec
    1065966    def clip(self, uthres=None, dthres=None, clipoutside=True, unflag=False):
    1066967        """\
     
    1080981        """
    1081982        varlist = vars()
    1082         try:
    1083             self._clip(uthres, dthres, clipoutside, unflag)
    1084         except RuntimeError, msg:
    1085             if rcParams['verbose']:
    1086                 print_log()
    1087                 asaplog.push(str(msg))
    1088                 print_log('ERROR')
    1089                 return
    1090             else: raise
     983        self._clip(uthres, dthres, clipoutside, unflag)
    1091984        self._add_history("clip", varlist)
    1092985
     
    11201013        if not (unit == "" or base.has_key(unit)):
    11211014            raise ValueError("%s is not a valid unit." % unit)
    1122         try:
    1123             if unit == "":
    1124                 s = scantable(self._math._lag_flag(self, start, end, "lags"))
    1125             else:
    1126                 s = scantable(self._math._lag_flag(self, start*base[unit],
    1127                                                    end*base[unit], "frequency"))
    1128         except RuntimeError, msg:
    1129             if rcParams['verbose']:
    1130                 #print msg
    1131                 print_log()
    1132                 asaplog.push( str(msg) )
    1133                 print_log( 'ERROR' )
    1134                 return
    1135             else: raise
     1015        if unit == "":
     1016            s = scantable(self._math._lag_flag(self, start, end, "lags"))
     1017        else:
     1018            s = scantable(self._math._lag_flag(self, start*base[unit],
     1019                                               end*base[unit], "frequency"))
    11361020        s._add_history("lag_flag", varlist)
    11371021        if insitu:
     
    11821066        data = self._getabcissa(row)
    11831067        u = self._getcoordinfo()[0]
    1184         if rcParams['verbose']:
    1185             if u == "": u = "channel"
    1186             msg = "The current mask window unit is %s" % u
    1187             i = self._check_ifs()
    1188             if not i:
    1189                 msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
    1190             asaplog.push(msg)
     1068        if u == "":
     1069            u = "channel"
     1070        msg = "The current mask window unit is %s" % u
     1071        i = self._check_ifs()
     1072        if not i:
     1073            msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
     1074        asaplog.push(msg)
    11911075        n = self.nchan()
    11921076        msk = _n_bools(n, False)
     
    12401124        data = self._getabcissa(row)
    12411125        u = self._getcoordinfo()[0]
    1242         if rcParams['verbose']:
    1243             if u == "": u = "channel"
    1244             msg = "The current mask window unit is %s" % u
    1245             i = self._check_ifs()
    1246             if not i:
    1247                 msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
    1248             asaplog.push(msg)
     1126        if u == "":
     1127            u = "channel"
     1128        msg = "The current mask window unit is %s" % u
     1129        i = self._check_ifs()
     1130        if not i:
     1131            msg += "\nThis mask is only valid for IF=%d" % (self.getif(i))
     1132        asaplog.push(msg)
    12491133        masklist=[]
    12501134        ist, ien = None, None
     
    14641348        Scantable.shift_refpix(self, delta)
    14651349
     1350    @print_log_dec
    14661351    def history(self, filename=None):
    14671352        """\
     
    15001385            else:
    15011386                msg = "Illegal file name '%s'." % (filename)
    1502                 if rcParams['verbose']:
    1503                     #print msg
    1504                     asaplog.push( msg )
    1505                     print_log( 'ERROR' )
    1506                 else:
    1507                     raise IOError(msg)
    1508         if rcParams['verbose']:
    1509             try:
    1510                 from IPython.genutils import page as pager
    1511             except ImportError:
    1512                 from pydoc import pager
    1513             pager(out)
    1514         else:
    1515             return out
    1516         return
     1387                raise IOError(msg)
     1388        return page(out)
    15171389    #
    15181390    # Maths business
     
    15581430        scanav = (scanav and 'SCAN') or 'NONE'
    15591431        scan = (self, )
    1560         try:
    1561             if align:
    1562                 scan = (self.freq_align(insitu=False), )
    1563             s = None
    1564             if weight.upper() == 'MEDIAN':
    1565                 s = scantable(self._math._averagechannel(scan[0], 'MEDIAN',
    1566                                                          scanav))
    1567             else:
    1568                 s = scantable(self._math._average(scan, mask, weight.upper(),
    1569                               scanav))
    1570         except RuntimeError, msg:
    1571             if rcParams['verbose']:
    1572                 #print msg
    1573                 print_log()
    1574                 asaplog.push( str(msg) )
    1575                 print_log( 'ERROR' )
    1576                 return
    1577             else: raise
     1432
     1433        if align:
     1434            scan = (self.freq_align(insitu=False), )
     1435        s = None
     1436        if weight.upper() == 'MEDIAN':
     1437            s = scantable(self._math._averagechannel(scan[0], 'MEDIAN',
     1438                                                     scanav))
     1439        else:
     1440            s = scantable(self._math._average(scan, mask, weight.upper(),
     1441                          scanav))
    15781442        s._add_history("average_time", varlist)
    15791443        return s
     
    18541718        """
    18551719        varlist = vars()
    1856         try:
    1857             s = scantable(self._math._convertpol(self, poltype))
    1858         except RuntimeError, msg:
    1859             if rcParams['verbose']:
    1860                 #print msg
    1861                 print_log()
    1862                 asaplog.push( str(msg) )
    1863                 print_log( 'ERROR' )
    1864                 return
    1865             else:
    1866                 raise
     1720        s = scantable(self._math._convertpol(self, poltype))
    18671721        s._add_history("convert_pol", varlist)
    18681722        return s
     
    20321886        except RuntimeError:
    20331887            msg = "The fit failed, possibly because it didn't converge."
    2034             if rcParams['verbose']:
    2035                 #print msg
    2036                 print_log()
    2037                 asaplog.push( str(msg) )
    2038                 print_log( 'ERROR' )
    2039                 return
    2040             else:
    2041                 raise RuntimeError(msg)
     1888            raise RuntimeError(msg)
    20421889
    20431890
     
    25502397        from asap.asapfit import asapfit
    25512398        fit = asapfit(self._getfit(row))
    2552         if rcParams['verbose']:
    2553             #print fit
    2554             asaplog.push( '%s' %(fit) )
    2555             return
    2556         else:
    2557             return fit.as_dict()
     2399        asaplog.push( '%s' %(fit) )
     2400        return fit.as_dict()
    25582401
    25592402    def flag_nans(self):
     
    26492492        return (sum(nchans)/len(nchans) == nchans[0])
    26502493
     2494    @print_log_dec
    26512495    def _fill(self, names, unit, average, getpt, antenna):
    26522496        first = True
     
    26572501            if not os.path.exists(name):
    26582502                msg = "File '%s' does not exists" % (name)
    2659                 if rcParams['verbose']:
    2660                     asaplog.push(msg)
    2661                     print_log( 'ERROR' )
    2662                     return
    26632503                raise IOError(msg)
    26642504            fullnames.append(name)
     
    26732513            msg = "Importing %s..." % (name)
    26742514            asaplog.push(msg, False)
    2675             print_log()
    26762515            r.open(name)# antenna, -1, -1, getpt)
    26772516            r.fill()
  • trunk/python/utils.py

    r1824 r1859  
    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    verbose = False
     71    try:
     72        from asap.parameters import rcParams
     73        verbose = rcParams['verbose']
     74    except:
     75        pass
     76    if verbose:
     77        try:
     78            from IPython.genutils import page as pager
     79        except ImportError:
     80            from pydoc import pager
     81        pager(message)
     82        return None
     83    else:
     84        return message
  • trunk/src/AsapLogSink.cpp

    r1819 r1859  
    2121
    2222  void AsapLogSink::postMessage(const std::string& msg,
    23                                 const std::string& location,
    24                                 const std::string& priority)
     23                                const std::string& priority,
     24                                const std::string& origin)
    2525  {
    2626    LogMessage::Priority p;
     
    3232      p = LogMessage::SEVERE;
    3333    }
    34     LogMessage message(msg, LogOrigin(location), p);
     34    LogMessage message(msg, LogOrigin(origin), p);
    3535
    3636    MemoryLogSink::postLocally(message);
  • trunk/src/AsapLogSink.h

    r1819 r1859  
    3737
    3838  virtual void postMessage(const std::string& msg,
    39                            const std::string& location="",
    40                            const std::string& priority="INFO");
     39                           const std::string& priority="INFO",
     40                           const std::string& origin="");
    4141
    4242  std::string popMessages();
  • trunk/src/python_LogSink.cpp

    r1819 r1859  
    4141        .def( init <> () )
    4242        .def("post", &AsapLogSink::postMessage,
    43          (boost::python::arg("location")="",
    44          boost::python::arg("priority")="INFO"))
     43         (boost::python::arg("priority")="INFO",
     44         boost::python::arg("origin")=""))
    4545        .def("pop", &AsapLogSink::popMessages)
    4646      ;
Note: See TracChangeset for help on using the changeset viewer.