casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
msmoments_cli.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 casac
00010 import string
00011 import time
00012 import inspect
00013 import gc
00014 import numpy
00015 from odict import odict
00016 from taskmanager import tm
00017 from task_msmoments import msmoments
00018 class msmoments_cli_:
00019     __name__ = "msmoments"
00020     __async__ = {}
00021     rkey = None
00022     i_am_a_casapy_task = None
00023     # The existence of the i_am_a_casapy_task attribute allows help()
00024     # (and other) to treat casapy tasks as a special case.
00025 
00026     def __init__(self) :
00027        self.__bases__ = (msmoments_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'infile':None, 'moments':None, 'antenna':None, 'field':None, 'spw':None, 'includemask':None, 'excludemask':None, 'outfile':None, 'overwrite':None,  'async':None}
00031 
00032 
00033     def result(self, key=None):
00034             #### here we will scan the task-ids in __async__
00035             #### and add any that have completed...
00036             if key is not None and self.__async__.has_key(key) and self.__async__[key] is not None:
00037                ret = tm.retrieve(self.__async__[key])
00038                if ret['state'] == "done" :
00039                   self.__async__[key] = None
00040                elif ret['state'] == 'crashed' :
00041                   self.__async__[key] = None
00042                return ret
00043             return None
00044 
00045 
00046     def __call__(self, infile=None, moments=None, antenna=None, field=None, spw=None, includemask=None, excludemask=None, outfile=None, overwrite=None,  async=None):
00047 
00048         """Compute moments from an MS
00049         The spectral moment distributions at each row in input MS are
00050         determined. Input MS must have FLOAT_DATA column, i.e. 
00051         autocorrelation data.  
00052         See the cookbook and User Reference Manual for
00053         mathematical details.
00054 
00055         The main control of the calculation is given by parameter
00056         moments:
00057         
00058         moments=-1  - mean value of the spectrum
00059         moments=0   - integrated value of the spectrum
00060         moments=1   - intensity weighted coordinate;traditionally used to get 
00061                       'velocity fields'
00062         moments=2   - intensity weighted dispersion of the coordinate; traditionally
00063                       used to get "velocity dispersion"
00064         moments=3   - median of I
00065         moments=4   - median coordinate
00066         moments=5   - standard deviation about the mean of the spectrum
00067         moments=6   - root mean square of the spectrum
00068         moments=7   - absolute mean deviation of the spectrum
00069         moments=8   - maximum value of the spectrum
00070         moments=9   - coordinate of the maximum value of the spectrum
00071         moments=10  - minimum value of the spectrum
00072         moments=11  - coordinate of the minimum value of the spectrum
00073 
00074         Note that includemask and excludemask cannot set simultaneously. 
00075 
00076         Keyword arguments:
00077         infile -- Name of input MS data
00078                 default: none; example: infile="OrionS_rawACSmod"
00079         moments -- List of moments you would like to compute
00080                 default: 0 (integrated spectrum);example: moments=[0,1]
00081                 see list above
00082         antenna -- antenna name or id that the user wants to compute moments
00083                 default: '' (all antennae)
00084         field -- field name or id that the user wants to compute moments
00085                 default: '' (all fields)
00086         spw -- spectral window id that the user wants to compute moments
00087                 default: '' (all spectral windows)
00088 
00089         includemask -- List of masks to include
00090                 default: [-1] (include all channels); example=[2,100]
00091         excludemask -- List of masks to exclude
00092                 default: [-1] (don't exclude channels); example=[100,200]
00093         outfile -- Output MS file name (or root for multiple moments)
00094                 default: '' (input+auto-determined suffix);example: outfile='source_moment'
00095         overwrite -- Overwrite existing output files
00096                 default: false
00097 
00098         Example for finding the 1-momment, intensity-weighted
00099         coordinate, often used for finding velocity fields.
00100         msmoments( infile='mydata', moment=1, outfile='velocityfields' )
00101 
00102 
00103         """
00104         if not hasattr(self, "__globals__") or self.__globals__ == None :
00105            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00106         #casac = self.__globals__['casac']
00107         casalog = self.__globals__['casalog']
00108         #casalog = casac.casac.logsink()
00109         self.__globals__['__last_task'] = 'msmoments'
00110         self.__globals__['taskname'] = 'msmoments'
00111         ###
00112         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00113         ###
00114         ###
00115         #Handle globals or user over-ride of arguments
00116         #
00117         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00118         useLocalDefaults = False
00119 
00120         for item in function_signature_defaults.iteritems():
00121                 key,val = item
00122                 keyVal = eval(key)
00123                 if (keyVal == None):
00124                         #user hasn't set it - use global/default
00125                         pass
00126                 else:
00127                         #user has set it - use over-ride
00128                         if (key != 'self') :
00129                            useLocalDefaults = True
00130 
00131         myparams = {}
00132         if useLocalDefaults :
00133            for item in function_signature_defaults.iteritems():
00134                key,val = item
00135                keyVal = eval(key)
00136                exec('myparams[key] = keyVal')
00137                self.parameters[key] = keyVal
00138                if (keyVal == None):
00139                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00140                    keyVal = eval(key)
00141                    if(type(keyVal) == dict) :
00142                       if len(keyVal) > 0 :
00143                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00144                       else :
00145                          exec('myparams[key] = ' + key + ' = {}')
00146 
00147         else :
00148             async = self.parameters['async']
00149             myparams['infile'] = infile = self.parameters['infile']
00150             myparams['moments'] = moments = self.parameters['moments']
00151             myparams['antenna'] = antenna = self.parameters['antenna']
00152             myparams['field'] = field = self.parameters['field']
00153             myparams['spw'] = spw = self.parameters['spw']
00154             myparams['includemask'] = includemask = self.parameters['includemask']
00155             myparams['excludemask'] = excludemask = self.parameters['excludemask']
00156             myparams['outfile'] = outfile = self.parameters['outfile']
00157             myparams['overwrite'] = overwrite = self.parameters['overwrite']
00158 
00159         if type(moments)==int: moments=[moments]
00160 
00161         result = None
00162 
00163 #
00164 #    The following is work around to avoid a bug with current python translation
00165 #
00166         mytmp = {}
00167 
00168         mytmp['infile'] = infile
00169         mytmp['moments'] = moments
00170         mytmp['antenna'] = antenna
00171         mytmp['field'] = field
00172         mytmp['spw'] = spw
00173         mytmp['includemask'] = includemask
00174         mytmp['excludemask'] = excludemask
00175         mytmp['outfile'] = outfile
00176         mytmp['overwrite'] = overwrite
00177         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00178         trec = casac.casac.utils().torecord(pathname+'msmoments.xml')
00179 
00180         casalog.origin('msmoments')
00181         try :
00182           #if not trec.has_key('msmoments') or not casac.casac.utils().verify(mytmp, trec['msmoments']) :
00183             #return False
00184 
00185           casac.casac.utils().verify(mytmp, trec['msmoments'], True)
00186           scriptstr=['']
00187           saveinputs = self.__globals__['saveinputs']
00188           saveinputs('msmoments', 'msmoments.last', myparams, self.__globals__,scriptstr=scriptstr)
00189           if async :
00190             count = 0
00191             keybase =  time.strftime("%y%m%d.%H%M%S")
00192             key = keybase + "_" + str(count)
00193             while self.__async__.has_key(key) :
00194                count += 1
00195                key = keybase + "_" + str(count)
00196             result = tm.execute('msmoments', infile, moments, antenna, field, spw, includemask, excludemask, outfile, overwrite)
00197             print "Use: "
00198             print "      tm.retrieve(return_value) # to retrieve the status"
00199             print 
00200             self.rkey = key
00201             self.__async__[key] = result
00202           else :
00203               tname = 'msmoments'
00204               spaces = ' '*(18-len(tname))
00205               casalog.post('\n##########################################'+
00206                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00207               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00208               result = msmoments(infile, moments, antenna, field, spw, includemask, excludemask, outfile, overwrite)
00209               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00210                            '\n##########################################')
00211 
00212         except Exception, instance:
00213           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00214              raise
00215           else :
00216              #print '**** Error **** ',instance
00217              tname = 'msmoments'
00218              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00219              pass
00220 
00221         gc.collect()
00222         return result
00223 #
00224 #
00225 #
00226     def paramgui(self, useGlobals=True, ipython_globals=None):
00227         """
00228         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00229         """
00230         import paramgui
00231         if not hasattr(self, "__globals__") or self.__globals__ == None :
00232            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00233 
00234         if useGlobals:
00235             if ipython_globals == None:
00236                 myf=self.__globals__
00237             else:
00238                 myf=ipython_globals
00239 
00240             paramgui.setGlobals(myf)
00241         else:
00242             paramgui.setGlobals({})
00243 
00244         paramgui.runTask('msmoments', myf['_ip'])
00245         paramgui.setGlobals({})
00246 
00247 #
00248 #
00249 #
00250     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00251         if not hasattr(self, "__globals__") or self.__globals__ == None :
00252            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00253         if ipython_globals == None:
00254             myf=self.__globals__
00255         else:
00256             myf=ipython_globals
00257 
00258         a = odict()
00259         a['infile']  = ''
00260         a['moments']  = [0]
00261         a['antenna']  = ''
00262         a['field']  = ''
00263         a['spw']  = ''
00264         a['includemask']  = -1
00265         a['excludemask']  = -1
00266         a['outfile']  = ''
00267         a['overwrite']  = False
00268 
00269         a['async']=False
00270 
00271 ### This function sets the default values but also will return the list of
00272 ### parameters or the default value of a given parameter
00273         if(param == None):
00274                 myf['__set_default_parameters'](a)
00275         elif(param == 'paramkeys'):
00276                 return a.keys()
00277         else:
00278             if(paramvalue==None and subparam==None):
00279                if(a.has_key(param)):
00280                   return a[param]
00281                else:
00282                   return self.itsdefault(param)
00283             else:
00284                retval=a[param]
00285                if(type(a[param])==dict):
00286                   for k in range(len(a[param])):
00287                      valornotval='value'
00288                      if(a[param][k].has_key('notvalue')):
00289                         valornotval='notvalue'
00290                      if((a[param][k][valornotval])==paramvalue):
00291                         retval=a[param][k].copy()
00292                         retval.pop(valornotval)
00293                         if(subparam != None):
00294                            if(retval.has_key(subparam)):
00295                               retval=retval[subparam]
00296                            else:
00297                               retval=self.itsdefault(subparam)
00298                      else:
00299                         retval=self.itsdefault(subparam)
00300                return retval
00301 
00302 
00303 #
00304 #
00305     def check_params(self, param=None, value=None, ipython_globals=None):
00306       if ipython_globals == None:
00307           myf=self.__globals__
00308       else:
00309           myf=ipython_globals
00310 #      print 'param:', param, 'value:', value
00311       try :
00312          if str(type(value)) != "<type 'instance'>" :
00313             value0 = value
00314             value = myf['cu'].expandparam(param, value)
00315             matchtype = False
00316             if(type(value) == numpy.ndarray):
00317                if(type(value) == type(value0)):
00318                   myf[param] = value.tolist()
00319                else:
00320                   #print 'value:', value, 'value0:', value0
00321                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00322                   myf[param] = value0
00323                   if type(value0) != list :
00324                      matchtype = True
00325             else :
00326                myf[param] = value
00327             value = myf['cu'].verifyparam({param:value})
00328             if matchtype:
00329                value = False
00330       except Exception, instance:
00331          #ignore the exception and just return it unchecked
00332          myf[param] = value
00333       return value
00334 #
00335 #
00336     def description(self, key='msmoments', subkey=None):
00337         desc={'msmoments': 'Compute moments from an MS',
00338                'infile': 'Name of the input MS data',
00339                'moments': 'List of moments you want to compute',
00340                'antenna': 'antenna name or id',
00341                'field': 'field name or id',
00342                'spw': 'spectral window id',
00343                'includemask': 'Range of rows to include',
00344                'excludemask': 'Range of rows to exclude',
00345                'outfile': 'Output file name (or root for multiple moments) ',
00346                'overwrite': 'Overwrite existing output files',
00347 
00348                'async': 'If true the taskname must be started using msmoments(...)'
00349               }
00350 
00351         if(desc.has_key(key)) :
00352            return desc[key]
00353 
00354     def itsdefault(self, paramname) :
00355         a = {}
00356         a['infile']  = ''
00357         a['moments']  = [0]
00358         a['antenna']  = ''
00359         a['field']  = ''
00360         a['spw']  = ''
00361         a['includemask']  = -1
00362         a['excludemask']  = -1
00363         a['outfile']  = ''
00364         a['overwrite']  = False
00365 
00366         #a = sys._getframe(len(inspect.stack())-1).f_globals
00367 
00368         if a.has_key(paramname) :
00369               return a[paramname]
00370 msmoments_cli = msmoments_cli_()