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