casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
sdmath_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_sdmath import sdmath
00016 from task_sdmath import casalog
00017 
00018 class sdmath_pg_:
00019     __name__ = "sdmath"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (sdmath_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, expr=None, varlist=None, antenna=None, fluxunit=None, telescopeparm=None, specunit=None, frame=None, doppler=None, scanlist=None, field=None, iflist=None, pollist=None, outfile=None, outform=None, overwrite=None, async=None):
00027 
00028         """ASAP SD task: do simple arithmatic (subtraction, addition, multiplication, and division) for spectra
00029   Keyword arguments:
00030         expr -- Mathematical expression using scantables 
00031         varlist -- Dictionary of variables in expr and their values.
00032                    Keys must be coincide with variables used in expr.
00033                    Values are substituted in each value in expr.
00034         antenna -- antenna name or id (only effective for MS input). 
00035         fluxunit -- units for line flux
00036                 options: '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                 example: this will be the units for masklist
00059         frame -- frequency frame for spectral axis
00060                 options: (str) 'LSRK','REST','TOPO','LSRD','BARY',
00061                          'GEO','GALACTO','LGROUP','CMB'
00062                 default: currently set frame in scantable
00063                 WARNING: frame='REST' not yet implemented
00064         doppler -- doppler mode
00065                 options: (str) 'RADIO','OPTICAL','Z','BETA','GAMMA'
00066                 default: currently set doppler in scantable
00067         scanlist -- list of scan numbers to process
00068                 default: [] (use all scans)
00069                 example: [21,22,23,24]
00070                 this selection is in addition to field, iflist, and pollist
00071         field -- selection string for selecting scans by name
00072                 default: '' (no name selection)
00073                 example: 'FLS3a*'
00074                 this selection is in addition to scanlist, iflist, and pollist
00075         iflist -- list of IF id numbers to select
00076                 default: [] (use all IFs)
00077                 example: [15]
00078                 this selection is in addition to scanlist, field, and pollist
00079         pollist -- list of polarization id numbers to select
00080                 default: [] (use all polarizations)
00081                 example: [1]
00082                 this selection is in addition to scanlist, field, and iflist
00083         outfile -- Name of output file
00084                 default: '' (<infile>_cal)
00085         outform -- format of output file
00086                 options: 'ASCII','SDFITS','MS','ASAP'
00087                 default: 'ASAP'
00088                 example: the ASAP format is easiest for further sd
00089                          processing; use MS for CASA imaging.
00090                          If ASCII, then will append some stuff to
00091                          the outfile name
00092         overwrite -- overwrite the output file if already exists
00093                 options: (bool) True,False
00094                 default: False
00095                 WARNING: if outform='ASCII', this parameter is ignored
00096 
00097 
00098         DESCRIPTION:
00099 
00100         Task sdmath execute a mathematical expression for single dish spectra.
00101         The spectral data file can be any of the formats supported by
00102         ASAP (scantable, MS, rpfits, and SDFITS). In the expression, 
00103         these file names should be put inside of sigle or double quotes.
00104 
00105         You can use variables in the expression. If you want to use, you 
00106         must define varlist dictionary. Name of variables should be simple, 
00107         e.g. V0, V1, etc., to avoid unexpected error. Keys of varlist must 
00108         be name of variables that you used in the expression, and their 
00109         values will be substituted for variables in the expression. Allowed 
00110         type for the value is numerical values, one- or two-dimensional lists 
00111         (Python list or numpy.ndarray), and filename strings that indicate 
00112         spectral data or ASCII text, which is space-separated list of 
00113         numerical values consisting of adequate number of rows and columns.  
00114 
00115         The fluxunit, specunit, and frame can be set, otherwise, the current
00116         settings of the first spectral data in the expression are used.  
00117         Other selections (e.g. scan No, . IF, Pol) also apply to all 
00118         the spectral data in the expression, so if any of the data does
00119         not contains selection, the task will produce no output. 
00120        
00121         WARNING for the GBT raw SDFITS format data as input:
00122         SDtasks are able to handle GBT raw SDFITS format data since the 
00123         data filler is available. However, the functionality is not well 
00124         tested yet, so that there may be unknown bugs.  
00125         
00126         Example:
00127         # do on-off/off calculation
00128         expr='("orion_on_data.asap"-"orion_off_data.asap")/"orion_off_data.asap"
00129         outfile='orion_cal.asap'
00130         sdmath()
00131 
00132         # do on-off/off calculation using varlist
00133         expr='V0/V1-V2'
00134         varlist['V0']="orion_on_data.asap"
00135         varlist['V1']="orion_off_data.asap"
00136         varlist['V2']=1.0
00137         outfile='orion_cal.asap'
00138         sdmath()
00139 
00140         # interpretation of ASCII file value for varlist
00141         If the contents of input ASCII file is shown as, 
00142 
00143            0.5 0.3 0.2
00144            1.0 0.2 0.9
00145 
00146         it is interpreted as a list [[0.5, 0.3, 0.2],[1.0, 0.2, 0.9]]. 
00147 
00148   
00149         """
00150         a=inspect.stack()
00151         stacklevel=0
00152         for k in range(len(a)):
00153           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00154                 stacklevel=k
00155                 break
00156         myf=sys._getframe(stacklevel).f_globals
00157         myf['__last_task'] = 'sdmath'
00158         myf['taskname'] = 'sdmath'
00159         ###
00160         myf['update_params'](func=myf['taskname'],printtext=False)
00161         ###
00162         ###
00163         #Handle globals or user over-ride of arguments
00164         #
00165         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00166         useLocalDefaults = False
00167 
00168         for item in function_signature_defaults.iteritems():
00169                 key,val = item
00170                 keyVal = eval(key)
00171                 if (keyVal == None):
00172                         #user hasn't set it - use global/default
00173                         pass
00174                 else:
00175                         #user has set it - use over-ride
00176                         if (key != 'self') :
00177                            useLocalDefaults = True
00178                         #myf[key]=keyVal
00179 
00180         myparams = {}
00181         if useLocalDefaults :
00182            for item in function_signature_defaults.iteritems():
00183                key,val = item
00184                keyVal = eval(key)
00185                exec('myparams[key] = keyVal')
00186                if (keyVal == None):
00187                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00188                    keyVal = eval(key)
00189                    if(type(keyVal) == dict) :
00190                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00191 
00192         else :
00193             uselessvariable = None 
00194             myparams['expr'] = expr = myf['expr']
00195             myparams['varlist'] = varlist = myf['varlist']
00196             myparams['antenna'] = antenna = myf['antenna']
00197             myparams['fluxunit'] = fluxunit = myf['fluxunit']
00198             myparams['telescopeparm'] = telescopeparm = myf['telescopeparm']
00199             myparams['specunit'] = specunit = myf['specunit']
00200             myparams['frame'] = frame = myf['frame']
00201             myparams['doppler'] = doppler = myf['doppler']
00202             myparams['scanlist'] = scanlist = myf['scanlist']
00203             myparams['field'] = field = myf['field']
00204             myparams['iflist'] = iflist = myf['iflist']
00205             myparams['pollist'] = pollist = myf['pollist']
00206             myparams['outfile'] = outfile = myf['outfile']
00207             myparams['outform'] = outform = myf['outform']
00208             myparams['overwrite'] = overwrite = myf['overwrite']
00209 
00210         if type(scanlist)==int: scanlist=[scanlist]
00211         if type(iflist)==int: iflist=[iflist]
00212         if type(pollist)==int: pollist=[pollist]
00213 
00214         result = None
00215 
00216 #
00217 #    The following is work around to avoid a bug with current python translation
00218 #
00219         mytmp = {}
00220 
00221         mytmp['expr'] = expr
00222         mytmp['varlist'] = varlist
00223         mytmp['antenna'] = antenna
00224         mytmp['fluxunit'] = fluxunit
00225         mytmp['telescopeparm'] = telescopeparm
00226         mytmp['specunit'] = specunit
00227         mytmp['frame'] = frame
00228         mytmp['doppler'] = doppler
00229         mytmp['scanlist'] = scanlist
00230         mytmp['field'] = field
00231         mytmp['iflist'] = iflist
00232         mytmp['pollist'] = pollist
00233         mytmp['outfile'] = outfile
00234         mytmp['outform'] = outform
00235         mytmp['overwrite'] = overwrite
00236         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00237         trec = casac.utils().torecord(pathname+'sdmath.xml')
00238 
00239         casalog.origin('sdmath')
00240         if not trec.has_key('sdmath') or not casac.utils().verify(mytmp, trec['sdmath']) :
00241             return False
00242 
00243 
00244         try :
00245           casalog.post('')
00246           casalog.post('##########################################')
00247           casalog.post('##### Begin Task: sdmath           #####')
00248           casalog.post('')
00249           result = sdmath(expr, varlist, antenna, fluxunit, telescopeparm, specunit, frame, doppler, scanlist, field, iflist, pollist, outfile, outform, overwrite)
00250           casalog.post('')
00251           casalog.post('##### End Task: sdmath           #####')
00252           casalog.post('##########################################')
00253 
00254 
00255 # saveinputs for individule engine has no use
00256 # saveinputs should alos be removed from casa_in_py.py
00257 #
00258 #
00259 #          saveinputs = myf['saveinputs']
00260 #          saveinputs('sdmath', 'sdmath.last', myparams)
00261 #
00262 #
00263         except Exception, instance:
00264           #print '**** Error **** ',instance
00265           pass
00266 
00267         gc.collect()
00268         return result
00269 #
00270 #
00271 ##
00272 #    def paramgui(self, useGlobals=True):
00273 #        """
00274 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00275 #        """
00276 #        import paramgui
00277 #
00278 #        a=inspect.stack()
00279 #        stacklevel=0
00280 #        for k in range(len(a)):
00281 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00282 #            stacklevel=k
00283 #            break
00284 #        myf = sys._getframe(stacklevel).f_globals
00285 #
00286 #        if useGlobals:
00287 #            paramgui.setGlobals(myf)
00288 #        else:
00289 #            paramgui.setGlobals({})
00290 #
00291 #        paramgui.runTask('sdmath', myf['_ip'])
00292 #        paramgui.setGlobals({})
00293 #
00294 #
00295 #
00296 #
00297     def defaults(self, param=None):
00298         a=inspect.stack()
00299         stacklevel=0
00300         for k in range(len(a)):
00301           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00302                 stacklevel=k
00303                 break
00304         myf=sys._getframe(stacklevel).f_globals
00305         a = odict()
00306         a['expr']  = ''
00307         a['varlist']  = {}
00308         a['antenna']  = 0
00309         a['fluxunit']  = ''
00310         a['specunit']  = ''
00311         a['frame']  = ''
00312         a['doppler']  = ''
00313         a['scanlist']  = []
00314         a['field']  = ''
00315         a['iflist']  = []
00316         a['pollist']  = []
00317         a['outfile']  = ''
00318         a['outform']  = 'ASAP'
00319         a['overwrite']  = False
00320 
00321         a['async']=False
00322         a['fluxunit'] = {
00323                     0:{'value':''}, 
00324                     1:odict([{'value':'K'}, {'telescopeparm':''}]), 
00325                     2:odict([{'value':'k'}, {'telescopeparm':''}]), 
00326                     3:odict([{'value':'Jy'}, {'telescopeparm':''}]), 
00327                     4:odict([{'value':'jy'}, {'telescopeparm':''}])}
00328 
00329 ### This function sets the default values but also will return the list of
00330 ### parameters or the default value of a given parameter
00331         if(param == None):
00332                 myf['__set_default_parameters'](a)
00333         elif(param == 'paramkeys'):
00334                 return a.keys()
00335         else:
00336                 if(a.has_key(param)):
00337                    #if(type(a[param]) == dict) :
00338                    #   return a[param][len(a[param])-1]['value']
00339                    #else :
00340                       return a[param]
00341 
00342 
00343 #
00344 #
00345     def check_params(self, param=None, value=None):
00346       a=inspect.stack() 
00347       stacklevel=0
00348       for k in range(len(a)):
00349         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00350             stacklevel=k
00351             break
00352       myf=sys._getframe(stacklevel).f_globals
00353 
00354 #      print 'param:', param, 'value:', value
00355       try :
00356          if str(type(value)) != "<type 'instance'>" :
00357             value0 = value
00358             value = myf['cu'].expandparam(param, value)
00359             matchtype = False
00360             if(type(value) == numpy.ndarray):
00361                if(type(value) == type(value0)):
00362                   myf[param] = value.tolist()
00363                else:
00364                   #print 'value:', value, 'value0:', value0
00365                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00366                   myf[param] = value0
00367                   if type(value0) != list :
00368                      matchtype = True
00369             else :
00370                myf[param] = value
00371             value = myf['cu'].verifyparam({param:value})
00372             if matchtype:
00373                value = False
00374       except Exception, instance:
00375          #ignore the exception and just return it unchecked
00376          myf[param] = value
00377       return value
00378 
00379 #
00380 #
00381     def description(self, key='sdmath', subkey=None):
00382         desc={'sdmath': 'ASAP SD task: do simple arithmatic (subtraction, addition, multiplication, and division) for spectra',
00383                'expr': 'Mathematical expression using spectra',
00384                'varlist': 'Dictionary of variables and their values used in expr.',
00385                'antenna': 'antenna name or id (only effective for MS input)',
00386                'fluxunit': 'units for line flux (K,Jy) (''=current)',
00387                'telescopeparm': 'param of telescope for flux conversion',
00388                'specunit': 'units for spectral axis (channel,km/s,GHz,''=current)',
00389                'frame': 'frequency reference frame, e.g. LSRK (''=current)',
00390                'doppler': 'doppler convention, e.g. RADIO (''=current)',
00391                'scanlist': 'list of scans to use (e.g. [1,2,3,4])',
00392                'field': 'string for selection by source name',
00393                'iflist': 'list of IF ids to select (e.g. [0,1])',
00394                'pollist': 'list of polarization ids to select (e.g. [0,1])',
00395                'outfile': 'output file name',
00396                'outform': 'output file format (ASCII,MS,SDFITS,ASAP)',
00397                'overwrite': 'overwrite the output file if already exists',
00398 
00399                'async': 'If true the taskname must be started using sdmath(...)'
00400               }
00401 
00402 #
00403 # Set subfields defaults if needed
00404 #
00405 
00406         if(desc.has_key(key)) :
00407            return desc[key]
00408 
00409     def itsdefault(self, paramname) :
00410         a = {}
00411         a['expr']  = ''
00412         a['varlist']  = {}
00413         a['antenna']  = 0
00414         a['fluxunit']  = ''
00415         a['telescopeparm']  = ''
00416         a['specunit']  = ''
00417         a['frame']  = ''
00418         a['doppler']  = ''
00419         a['scanlist']  = []
00420         a['field']  = ''
00421         a['iflist']  = []
00422         a['pollist']  = []
00423         a['outfile']  = ''
00424         a['outform']  = 'ASAP'
00425         a['overwrite']  = False
00426 
00427         if a.has_key(paramname) :
00428               return a[paramname]
00429 sdmath_pg = sdmath_pg_()