casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
sdstat_pg.py
Go to the documentation of this file.
00001 #
00002 # This file was generated using xslt from its XML file
00003 #
00004 # Copyright 2008, Associated Universities Inc., Washington DC
00005 #
00006 import sys
00007 import os
00008 from casac import *
00009 import string
00010 import time
00011 import inspect
00012 import gc
00013 import numpy
00014 from odict import odict
00015 from task_sdstat import sdstat
00016 from task_sdstat import casalog
00017 
00018 class sdstat_pg_:
00019     __name__ = "sdstat"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (sdstat_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, infile=None, antenna=None, fluxunit=None, telescopeparm=None, specunit=None, restfreq=None, frame=None, doppler=None, scanlist=None, field=None, iflist=None, pollist=None, masklist=None, invertmask=None, interactive=None, outfile=None, format=None, overwrite=None, async=None):
00027 
00028         """ASAP SD task: list statistics of spectral region
00029         Keyword arguments:
00030         infile -- name of input SD dataset
00031                 default: none - must input file name
00032                 example: 'mysd.asap'
00033                          See sdcal for allowed formats.
00034         antenna -- antenna name or id (only effective for MS input). 
00035         fluxunit -- units for line flux
00036                 options: (str) 'K','Jy',''
00037                 default: '' (keep current fluxunit)
00038                 WARNING: For GBT data, see description below.
00039             >>> fluxunit expandable parameter
00040                  telescopeparm -- the telescope characteristics
00041                         options: (str) name or (list) list of gain info
00042                         default: '' (none set)
00043                         example: if telescopeparm='', it tries to get the telescope
00044                                  name from the data.
00045                                  Full antenna parameters (diameter,ap.eff.) known
00046                                  to ASAP are
00047                                  'ATPKSMB', 'ATPKSHOH', 'ATMOPRA', 'DSS-43',
00048                                  'CEDUNA','HOBART'. For GBT, it fixes default fluxunit
00049                                  to 'K' first then convert to a new fluxunit.
00050                                  telescopeparm=[104.9,0.43] diameter(m), ap.eff.
00051                                  telescopeparm=[0.743] gain in Jy/K
00052                                  telescopeparm='FIX' to change default fluxunit
00053                                  see description below
00054 
00055         specunit -- units for spectral axis
00056                 options: (str) 'channel','km/s','GHz','MHz','kHz','Hz',''
00057                 default: '' (=current)
00058             >>> specunit expandable parameter
00059                  restfreq -- rest frequency
00060                          default: '' (use current setting)
00061                          example: 4.6e10 (float value in Hz),
00062                                   '46GHz' (string with unit),
00063                                   ['345.8GHz', 347.0e9, 356.7e9] (for each IF)
00064                                   [{'name':'CO','value':345e9}] (a value with name)
00065         frame -- frequency frame for spectral axis
00066                 options: (str) 'LSRK','REST','TOPO','LSRD','BARY',
00067                          'GEO','GALACTO','LGROUP','CMB'
00068                 default: currently set frame in scantable
00069                 WARNING: frame='REST' not yet implemented
00070         doppler -- doppler mode
00071                 options: (str) 'RADIO','OPTICAL','Z','BETA','GAMMA'
00072                 default: currently set doppler in scantable
00073         scanlist -- list of scan numbers to process
00074                 default: [] (use all scans)
00075                 example: [21,22,23,24]
00076                 this selection is in addition to field, iflist, and pollist
00077         field -- selection string for selecting scans by name
00078                 default: '' (no name selection)
00079                 example: 'FLS3a*'
00080                 this selection is in addition to scanlist, iflist, and pollist
00081         iflist -- list of IF id numbers to select
00082                 default: [] (use all IFs)
00083                 example: [15]
00084                 this selection is in addition to field, scanlist, and pollist
00085         pollist -- list of polarization id numbers to select
00086                 default: [] (use all pols)
00087                 example: [1]
00088                 this selection is in addition to field, scanlist, and iflist
00089         masklist -- list of mask regions to INCLUDE in stats
00090                 default: [] (whole spectrum)
00091                 example: [4000,4500] for one region
00092                          [[1000,3000],[5000,7000]]
00093                          these must be pairs of [lo,hi] boundaries
00094         invertmask -- invert mask (EXCLUDE masklist instead)
00095                 options: (bool) True,False
00096                 default: false
00097         interactive -- determines interactive masking
00098                 options: (bool) True,False
00099                 default: False
00100                 example: interactive=True allows adding and deleting mask 
00101                          regions by drawing rectangles on the plot with mouse. 
00102                          Draw a rectangle with LEFT-mouse to ADD the region to 
00103                          the mask and with RIGHT-mouse to DELETE the region. 
00104         outfile -- name of output file for line statistics
00105                 default: '' (no output statistics file)
00106                 example: 'stat.txt'
00107         format -- format string to print statistic values
00108                 default: '3.3f'
00109         overwrite -- overwrite the statistics file if already exists 
00110                 options: (bool) True,False
00111                 default: False
00112 
00113         -------------------------------------------------------------------
00114                 Returns: a Python dictionary of line statistics
00115                    keys: 'rms','stddev','max','min','max_abscissa',
00116                          'min_abscissa','sum','median','mean','totint','eqw'
00117                 example: xstat=sdstat(); print "rms = ",xstat['rms']
00118                          these can be used for testing in scripts or
00119                          for regression
00120 
00121                          'max_abscissa' and 'min_abscissa' refer to the abscissa
00122                          (channel/frequency/velocity) of max and min intensity.
00123                          'totint' is the integrated intensity (sum*dx)
00124                          where dx is the abscissa interval in 'specunit'.
00125                          'eqw' is equivalent width (totint/mag) where mag
00126                          is either max or min depending on which has
00127                          greater magnitude. 
00128                          Note that 'max_abscissa', 'min_abscissa', 'totint' 
00129                          and 'eqw' are quantities (python dictionaries with
00130                          keys, 'unit' and 'value').
00131 
00132 
00133        DESCRIPTION:
00134 
00135         Task sdstat computes basic statistics (rms,mean,median,sum)
00136         for single-dish spectra.  It assumes that the spectra have
00137         been calibrated.  Furthermore, it assumes that any
00138         time and channel averaging/smoothing has also already been done as
00139         there are no controls for these. 
00140 
00141         Note that multiple scans and IFs can in principle be handled, but
00142         we recommend that you use scanlist, field, iflist, and pollist to give 
00143         a single selection for each run.
00144 
00145         WARNING: If you do have multiple scantable rows, then the returning 
00146         values will be lists.
00147 
00148         ASAP recognizes the data of the "AT" telescopes, but currently
00149         does not know about the GBT or any other telescope. This task
00150         does know about GBT. Telescope name is obtained from the data.
00151         If you wish to change the fluxunit (see below), and telescopeparm='',
00152         for the AT telescopes it will use internal telescope parameters for
00153         flux conversion. For GBT, it will use an approximate aperture
00154         efficiency conversion.  If you give telescopeparm a list, then
00155         if the list has a single float it is assumed to be the gain in Jy/K,
00156         if two or more elements they are assumed to be telescope diameter (m)
00157         and aperture efficiency respectively.
00158 
00159         WARNING for the GBT raw SDFITS format data as input:
00160         SDtasks are able to handle GBT raw SDFITS format data since the 
00161         data filler is available. However, the functionality is not well 
00162         tested yet, so that there may be unknown bugs.  
00163 
00164   
00165         """
00166         a=inspect.stack()
00167         stacklevel=0
00168         for k in range(len(a)):
00169           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00170                 stacklevel=k
00171                 break
00172         myf=sys._getframe(stacklevel).f_globals
00173         myf['__last_task'] = 'sdstat'
00174         myf['taskname'] = 'sdstat'
00175         ###
00176         myf['update_params'](func=myf['taskname'],printtext=False)
00177         ###
00178         ###
00179         #Handle globals or user over-ride of arguments
00180         #
00181         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00182         useLocalDefaults = False
00183 
00184         for item in function_signature_defaults.iteritems():
00185                 key,val = item
00186                 keyVal = eval(key)
00187                 if (keyVal == None):
00188                         #user hasn't set it - use global/default
00189                         pass
00190                 else:
00191                         #user has set it - use over-ride
00192                         if (key != 'self') :
00193                            useLocalDefaults = True
00194                         #myf[key]=keyVal
00195 
00196         myparams = {}
00197         if useLocalDefaults :
00198            for item in function_signature_defaults.iteritems():
00199                key,val = item
00200                keyVal = eval(key)
00201                exec('myparams[key] = keyVal')
00202                if (keyVal == None):
00203                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00204                    keyVal = eval(key)
00205                    if(type(keyVal) == dict) :
00206                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00207 
00208         else :
00209             uselessvariable = None 
00210             myparams['infile'] = infile = myf['infile']
00211             myparams['antenna'] = antenna = myf['antenna']
00212             myparams['fluxunit'] = fluxunit = myf['fluxunit']
00213             myparams['telescopeparm'] = telescopeparm = myf['telescopeparm']
00214             myparams['specunit'] = specunit = myf['specunit']
00215             myparams['restfreq'] = restfreq = myf['restfreq']
00216             myparams['frame'] = frame = myf['frame']
00217             myparams['doppler'] = doppler = myf['doppler']
00218             myparams['scanlist'] = scanlist = myf['scanlist']
00219             myparams['field'] = field = myf['field']
00220             myparams['iflist'] = iflist = myf['iflist']
00221             myparams['pollist'] = pollist = myf['pollist']
00222             myparams['masklist'] = masklist = myf['masklist']
00223             myparams['invertmask'] = invertmask = myf['invertmask']
00224             myparams['interactive'] = interactive = myf['interactive']
00225             myparams['outfile'] = outfile = myf['outfile']
00226             myparams['format'] = format = myf['format']
00227             myparams['overwrite'] = overwrite = myf['overwrite']
00228 
00229         if type(scanlist)==int: scanlist=[scanlist]
00230         if type(iflist)==int: iflist=[iflist]
00231         if type(pollist)==int: pollist=[pollist]
00232         if type(masklist)==int: masklist=[masklist]
00233 
00234         result = None
00235 
00236 #
00237 #    The following is work around to avoid a bug with current python translation
00238 #
00239         mytmp = {}
00240 
00241         mytmp['infile'] = infile
00242         mytmp['antenna'] = antenna
00243         mytmp['fluxunit'] = fluxunit
00244         mytmp['telescopeparm'] = telescopeparm
00245         mytmp['specunit'] = specunit
00246         mytmp['restfreq'] = restfreq
00247         mytmp['frame'] = frame
00248         mytmp['doppler'] = doppler
00249         mytmp['scanlist'] = scanlist
00250         mytmp['field'] = field
00251         mytmp['iflist'] = iflist
00252         mytmp['pollist'] = pollist
00253         mytmp['masklist'] = masklist
00254         mytmp['invertmask'] = invertmask
00255         mytmp['interactive'] = interactive
00256         mytmp['outfile'] = outfile
00257         mytmp['format'] = format
00258         mytmp['overwrite'] = overwrite
00259         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00260         trec = casac.utils().torecord(pathname+'sdstat.xml')
00261 
00262         casalog.origin('sdstat')
00263         if not trec.has_key('sdstat') or not casac.utils().verify(mytmp, trec['sdstat']) :
00264             return False
00265 
00266 
00267         try :
00268           casalog.post('')
00269           casalog.post('##########################################')
00270           casalog.post('##### Begin Task: sdstat           #####')
00271           casalog.post('')
00272           result = sdstat(infile, antenna, fluxunit, telescopeparm, specunit, restfreq, frame, doppler, scanlist, field, iflist, pollist, masklist, invertmask, interactive, outfile, format, overwrite)
00273           casalog.post('')
00274           casalog.post('##### End Task: sdstat           #####')
00275           casalog.post('##########################################')
00276 
00277 
00278 # saveinputs for individule engine has no use
00279 # saveinputs should alos be removed from casa_in_py.py
00280 #
00281 #
00282 #          saveinputs = myf['saveinputs']
00283 #          saveinputs('sdstat', 'sdstat.last', myparams)
00284 #
00285 #
00286         except Exception, instance:
00287           #print '**** Error **** ',instance
00288           pass
00289 
00290         gc.collect()
00291         return result
00292 #
00293 #
00294 ##
00295 #    def paramgui(self, useGlobals=True):
00296 #        """
00297 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00298 #        """
00299 #        import paramgui
00300 #
00301 #        a=inspect.stack()
00302 #        stacklevel=0
00303 #        for k in range(len(a)):
00304 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00305 #            stacklevel=k
00306 #            break
00307 #        myf = sys._getframe(stacklevel).f_globals
00308 #
00309 #        if useGlobals:
00310 #            paramgui.setGlobals(myf)
00311 #        else:
00312 #            paramgui.setGlobals({})
00313 #
00314 #        paramgui.runTask('sdstat', myf['_ip'])
00315 #        paramgui.setGlobals({})
00316 #
00317 #
00318 #
00319 #
00320     def defaults(self, param=None):
00321         a=inspect.stack()
00322         stacklevel=0
00323         for k in range(len(a)):
00324           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00325                 stacklevel=k
00326                 break
00327         myf=sys._getframe(stacklevel).f_globals
00328         a = odict()
00329         a['infile']  = ''
00330         a['antenna']  = 0
00331         a['fluxunit']  = ''
00332         a['specunit']  = ''
00333         a['frame']  = ''
00334         a['doppler']  = ''
00335         a['scanlist']  = []
00336         a['field']  = ''
00337         a['iflist']  = []
00338         a['pollist']  = []
00339         a['masklist']  = []
00340         a['invertmask']  = False
00341         a['interactive']  = False
00342         a['outfile']  = ''
00343         a['format']  = '3.3f'
00344         a['overwrite']  = False
00345 
00346         a['async']=False
00347         a['fluxunit'] = {
00348                     0:{'value':''}, 
00349                     1:odict([{'value':'K'}, {'telescopeparm':''}]), 
00350                     2:odict([{'value':'k'}, {'telescopeparm':''}]), 
00351                     3:odict([{'value':'Jy'}, {'telescopeparm':''}]), 
00352                     4:odict([{'value':'jy'}, {'telescopeparm':''}])}
00353         a['specunit'] = {
00354                     0:{'value':''}, 
00355                     1:{'value':'channel'}, 
00356                     2:odict([{'value':'km/s'}, {'restfreq':''}]), 
00357                     3:{'value':'GHz'}, 
00358                     4:{'value':'MHz'}, 
00359                     5:{'value':'kHz'}, 
00360                     6:{'value':'Hz'}}
00361 
00362 ### This function sets the default values but also will return the list of
00363 ### parameters or the default value of a given parameter
00364         if(param == None):
00365                 myf['__set_default_parameters'](a)
00366         elif(param == 'paramkeys'):
00367                 return a.keys()
00368         else:
00369                 if(a.has_key(param)):
00370                    #if(type(a[param]) == dict) :
00371                    #   return a[param][len(a[param])-1]['value']
00372                    #else :
00373                       return a[param]
00374 
00375 
00376 #
00377 #
00378     def check_params(self, param=None, value=None):
00379       a=inspect.stack() 
00380       stacklevel=0
00381       for k in range(len(a)):
00382         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00383             stacklevel=k
00384             break
00385       myf=sys._getframe(stacklevel).f_globals
00386 
00387 #      print 'param:', param, 'value:', value
00388       try :
00389          if str(type(value)) != "<type 'instance'>" :
00390             value0 = value
00391             value = myf['cu'].expandparam(param, value)
00392             matchtype = False
00393             if(type(value) == numpy.ndarray):
00394                if(type(value) == type(value0)):
00395                   myf[param] = value.tolist()
00396                else:
00397                   #print 'value:', value, 'value0:', value0
00398                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00399                   myf[param] = value0
00400                   if type(value0) != list :
00401                      matchtype = True
00402             else :
00403                myf[param] = value
00404             value = myf['cu'].verifyparam({param:value})
00405             if matchtype:
00406                value = False
00407       except Exception, instance:
00408          #ignore the exception and just return it unchecked
00409          myf[param] = value
00410       return value
00411 
00412 #
00413 #
00414     def description(self, key='sdstat', subkey=None):
00415         desc={'sdstat': 'ASAP SD task: list statistics of spectral region',
00416                'infile': 'name of input SD dataset',
00417                'antenna': 'antenna name or id (only effective for MS input)',
00418                'fluxunit': 'units for line flux (K,Jy) (''=current)',
00419                'telescopeparm': 'param of telescope for flux conversion',
00420                'specunit': 'units for spectral axis (channel,km/s,GHz)',
00421                'restfreq': 'rest frequency (default unit: Hz)',
00422                'frame': 'frequency reference frame, e.g. LSRK (''=current)',
00423                'doppler': 'doppler convention, e.g. RADIO (''=current)',
00424                'scanlist': 'list of scans to use (e.g. [1,2,3,4])',
00425                'field': 'string for selection by source name',
00426                'iflist': 'list of IF ids to select (e.g. [0,1])',
00427                'pollist': 'list of polarization ids to select (e.g. [0,1])',
00428                'masklist': 'list of mask regions to INCLUDE in stats',
00429                'invertmask': 'invert mask (EXCLUDE masklist instead)',
00430                'interactive': 'determines interactive masking',
00431                'outfile': 'name of output file for line statistics',
00432                'format': 'format string to print statistic values',
00433                'overwrite': 'overwrite the statistics file if already exists',
00434 
00435                'async': 'If true the taskname must be started using sdstat(...)'
00436               }
00437 
00438 #
00439 # Set subfields defaults if needed
00440 #
00441 
00442         if(desc.has_key(key)) :
00443            return desc[key]
00444 
00445     def itsdefault(self, paramname) :
00446         a = {}
00447         a['infile']  = ''
00448         a['antenna']  = 0
00449         a['fluxunit']  = ''
00450         a['telescopeparm']  = ''
00451         a['specunit']  = ''
00452         a['restfreq']  = ''
00453         a['frame']  = ''
00454         a['doppler']  = ''
00455         a['scanlist']  = []
00456         a['field']  = ''
00457         a['iflist']  = []
00458         a['pollist']  = []
00459         a['masklist']  = []
00460         a['invertmask']  = False
00461         a['interactive']  = False
00462         a['outfile']  = ''
00463         a['format']  = '3.3f'
00464         a['overwrite']  = False
00465 
00466         if a.has_key(paramname) :
00467               return a[paramname]
00468 sdstat_pg = sdstat_pg_()