casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
sdflagmanager_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_sdflagmanager import sdflagmanager
00018 class sdflagmanager_cli_:
00019     __name__ = "sdflagmanager"
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__ = (sdflagmanager_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'infile':None, 'mode':None, 'versionname':None, 'oldname':None, 'comment':None, 'merge':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, mode=None, versionname=None, oldname=None, comment=None, merge=None,  async=None):
00047 
00048         """ASAP SD task: enable list, save, restore, delete and rename flag version files
00049 
00050 
00051         These flag version files are copies of the flag column for a
00052         measurement set.  They can be restored to the data set to obtain
00053         a previous flag version.  It is wise to
00054         save a flagversion at the beginning or after serious editing.    
00055 
00056         Keyword arguments:
00057         infile -- Name of input SD dataset
00058                 default: ''. example: infile='ngc5921.asap'
00059         mode -- Flag version operation
00060                 default: 'list'; to list existing flagtables
00061                 'save' will save flag column from infile to a specified flag file
00062                 'restore' will place the specified flag file into infile
00063                 'delete' will delete specified flag file
00064                 'rename' will rename a specified flag file
00065 
00066             >>> mode expandable parameters             
00067                  versionname -- Flag version name
00068                          default: none; example: versionname='original_data'
00069                          No imbedded blanks in the versionname
00070                  comment -- Short description of a versionname, when mode is 'save' 
00071                             or 'rename'
00072                          default: ''; example: comment='Clip above 1.85'
00073                          comment = versionname
00074                  oldname -- When mode='rename', the flag file to rename
00075                  merge -- Merge operation
00076                          Options: 'or','and', but not recommended for now.
00077 
00078  
00079         """
00080         if not hasattr(self, "__globals__") or self.__globals__ == None :
00081            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00082         #casac = self.__globals__['casac']
00083         casalog = self.__globals__['casalog']
00084         #casalog = casac.casac.logsink()
00085         self.__globals__['__last_task'] = 'sdflagmanager'
00086         self.__globals__['taskname'] = 'sdflagmanager'
00087         ###
00088         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00089         ###
00090         ###
00091         #Handle globals or user over-ride of arguments
00092         #
00093         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00094         useLocalDefaults = False
00095 
00096         for item in function_signature_defaults.iteritems():
00097                 key,val = item
00098                 keyVal = eval(key)
00099                 if (keyVal == None):
00100                         #user hasn't set it - use global/default
00101                         pass
00102                 else:
00103                         #user has set it - use over-ride
00104                         if (key != 'self') :
00105                            useLocalDefaults = True
00106 
00107         myparams = {}
00108         if useLocalDefaults :
00109            for item in function_signature_defaults.iteritems():
00110                key,val = item
00111                keyVal = eval(key)
00112                exec('myparams[key] = keyVal')
00113                self.parameters[key] = keyVal
00114                if (keyVal == None):
00115                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00116                    keyVal = eval(key)
00117                    if(type(keyVal) == dict) :
00118                       if len(keyVal) > 0 :
00119                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00120                       else :
00121                          exec('myparams[key] = ' + key + ' = {}')
00122 
00123         else :
00124             async = self.parameters['async']
00125             myparams['infile'] = infile = self.parameters['infile']
00126             myparams['mode'] = mode = self.parameters['mode']
00127             myparams['versionname'] = versionname = self.parameters['versionname']
00128             myparams['oldname'] = oldname = self.parameters['oldname']
00129             myparams['comment'] = comment = self.parameters['comment']
00130             myparams['merge'] = merge = self.parameters['merge']
00131 
00132 
00133         result = None
00134 
00135 #
00136 #    The following is work around to avoid a bug with current python translation
00137 #
00138         mytmp = {}
00139 
00140         mytmp['infile'] = infile
00141         mytmp['mode'] = mode
00142         mytmp['versionname'] = versionname
00143         mytmp['oldname'] = oldname
00144         mytmp['comment'] = comment
00145         mytmp['merge'] = merge
00146         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00147         trec = casac.casac.utils().torecord(pathname+'sdflagmanager.xml')
00148 
00149         casalog.origin('sdflagmanager')
00150         try :
00151           #if not trec.has_key('sdflagmanager') or not casac.casac.utils().verify(mytmp, trec['sdflagmanager']) :
00152             #return False
00153 
00154           casac.casac.utils().verify(mytmp, trec['sdflagmanager'], True)
00155           scriptstr=['']
00156           saveinputs = self.__globals__['saveinputs']
00157           saveinputs('sdflagmanager', 'sdflagmanager.last', myparams, self.__globals__,scriptstr=scriptstr)
00158           if async :
00159             count = 0
00160             keybase =  time.strftime("%y%m%d.%H%M%S")
00161             key = keybase + "_" + str(count)
00162             while self.__async__.has_key(key) :
00163                count += 1
00164                key = keybase + "_" + str(count)
00165             result = tm.execute('sdflagmanager', infile, mode, versionname, oldname, comment, merge)
00166             print "Use: "
00167             print "      tm.retrieve(return_value) # to retrieve the status"
00168             print 
00169             self.rkey = key
00170             self.__async__[key] = result
00171           else :
00172               tname = 'sdflagmanager'
00173               spaces = ' '*(18-len(tname))
00174               casalog.post('\n##########################################'+
00175                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00176               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00177               result = sdflagmanager(infile, mode, versionname, oldname, comment, merge)
00178               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00179                            '\n##########################################')
00180 
00181         except Exception, instance:
00182           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00183              raise
00184           else :
00185              #print '**** Error **** ',instance
00186              tname = 'sdflagmanager'
00187              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00188              pass
00189 
00190         gc.collect()
00191         return result
00192 #
00193 #
00194 #
00195     def paramgui(self, useGlobals=True, ipython_globals=None):
00196         """
00197         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00198         """
00199         import paramgui
00200         if not hasattr(self, "__globals__") or self.__globals__ == None :
00201            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00202 
00203         if useGlobals:
00204             if ipython_globals == None:
00205                 myf=self.__globals__
00206             else:
00207                 myf=ipython_globals
00208 
00209             paramgui.setGlobals(myf)
00210         else:
00211             paramgui.setGlobals({})
00212 
00213         paramgui.runTask('sdflagmanager', myf['_ip'])
00214         paramgui.setGlobals({})
00215 
00216 #
00217 #
00218 #
00219     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00220         if not hasattr(self, "__globals__") or self.__globals__ == None :
00221            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00222         if ipython_globals == None:
00223             myf=self.__globals__
00224         else:
00225             myf=ipython_globals
00226 
00227         a = odict()
00228         a['infile']  = ''
00229         a['mode']  = 'list'
00230 
00231         a['async']=False
00232         a['mode'] = {
00233                     0:{'value':'list'}, 
00234                     1:odict([{'value':'save'}, {'versionname':''}, {'comment':''}, {'merge':'replace'}]), 
00235                     2:odict([{'value':'restore'}, {'versionname':''}, {'merge':'replace'}]), 
00236                     3:odict([{'value':'delete'}, {'versionname':''}]), 
00237                     4:odict([{'value':'rename'}, {'oldname':''}, {'versionname':''}, {'comment':''}])}
00238 
00239 ### This function sets the default values but also will return the list of
00240 ### parameters or the default value of a given parameter
00241         if(param == None):
00242                 myf['__set_default_parameters'](a)
00243         elif(param == 'paramkeys'):
00244                 return a.keys()
00245         else:
00246             if(paramvalue==None and subparam==None):
00247                if(a.has_key(param)):
00248                   return a[param]
00249                else:
00250                   return self.itsdefault(param)
00251             else:
00252                retval=a[param]
00253                if(type(a[param])==dict):
00254                   for k in range(len(a[param])):
00255                      valornotval='value'
00256                      if(a[param][k].has_key('notvalue')):
00257                         valornotval='notvalue'
00258                      if((a[param][k][valornotval])==paramvalue):
00259                         retval=a[param][k].copy()
00260                         retval.pop(valornotval)
00261                         if(subparam != None):
00262                            if(retval.has_key(subparam)):
00263                               retval=retval[subparam]
00264                            else:
00265                               retval=self.itsdefault(subparam)
00266                      else:
00267                         retval=self.itsdefault(subparam)
00268                return retval
00269 
00270 
00271 #
00272 #
00273     def check_params(self, param=None, value=None, ipython_globals=None):
00274       if ipython_globals == None:
00275           myf=self.__globals__
00276       else:
00277           myf=ipython_globals
00278 #      print 'param:', param, 'value:', value
00279       try :
00280          if str(type(value)) != "<type 'instance'>" :
00281             value0 = value
00282             value = myf['cu'].expandparam(param, value)
00283             matchtype = False
00284             if(type(value) == numpy.ndarray):
00285                if(type(value) == type(value0)):
00286                   myf[param] = value.tolist()
00287                else:
00288                   #print 'value:', value, 'value0:', value0
00289                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00290                   myf[param] = value0
00291                   if type(value0) != list :
00292                      matchtype = True
00293             else :
00294                myf[param] = value
00295             value = myf['cu'].verifyparam({param:value})
00296             if matchtype:
00297                value = False
00298       except Exception, instance:
00299          #ignore the exception and just return it unchecked
00300          myf[param] = value
00301       return value
00302 #
00303 #
00304     def description(self, key='sdflagmanager', subkey=None):
00305         desc={'sdflagmanager': 'ASAP SD task: enable list, save, restore, delete and rename flag version files',
00306                'infile': 'Name of input SD dataset (ASAP scantable)',
00307                'mode': 'Operation: list, save, restore, delete, rename',
00308                'versionname': 'Flag version name',
00309                'oldname': 'Flag version to rename',
00310                'comment': 'Short description of a versionname',
00311                'merge': 'Merge option: replace will save or over-write the flags',
00312 
00313                'async': 'If true the taskname must be started using sdflagmanager(...)'
00314               }
00315 
00316 #
00317 # Set subfields defaults if needed
00318 #
00319 
00320         if(desc.has_key(key)) :
00321            return desc[key]
00322 
00323     def itsdefault(self, paramname) :
00324         a = {}
00325         a['infile']  = ''
00326         a['mode']  = 'list'
00327         a['versionname']  = ''
00328         a['oldname']  = ''
00329         a['comment']  = ''
00330         a['merge']  = 'replace'
00331 
00332         #a = sys._getframe(len(inspect.stack())-1).f_globals
00333 
00334         if self.parameters['mode']  == 'save':
00335             a['versionname'] = ''
00336             a['comment'] = ''
00337             a['merge'] = 'replace'
00338 
00339         if self.parameters['mode']  == 'restore':
00340             a['versionname'] = ''
00341             a['merge'] = 'replace'
00342 
00343         if self.parameters['mode']  == 'delete':
00344             a['versionname'] = ''
00345 
00346         if self.parameters['mode']  == 'rename':
00347             a['oldname'] = ''
00348             a['versionname'] = ''
00349             a['comment'] = ''
00350 
00351         if a.has_key(paramname) :
00352               return a[paramname]
00353 sdflagmanager_cli = sdflagmanager_cli_()