casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
listpartition_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_listpartition import listpartition
00018 class listpartition_cli_:
00019     __name__ = "listpartition"
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__ = (listpartition_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'createdict':None, 'listfile':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, createdict=None, listfile=None,  async=None):
00047 
00048         """List the summary of a multi-MS data set in the logger or in a file
00049 
00050        A multi-measurement set (MMS) is an MS that has been split into sub-MSs.
00051        An MMS contains a reference MS in the top directory and the sub-MSs are 
00052        located in a directory called SUBMSS inside the MMS directory.
00053        Example of a MS that was 'split' in two scans using the task partition: 
00054        
00055        > ls pScan.mms/
00056          SUBMSS/     table.dat   table.info
00057        
00058        > ls pScan.mms/SUBMSS/
00059          pScan.0000.ms/ pScan.0001.ms/
00060        
00061        
00062        The task lists the following properties of a multi-MS or MS:
00063        sub-MS name, scan, spw list, list of number of channels per spw, 
00064        number of rows for each scan and the size in disk. Example of logger output:
00065        
00066         Sub-MS         Scan  Spw               Nchan             Nrows   Size  
00067         pScan.0000.ms  31    [ 0  1  2  3  4]  [64 64 64 64 64]  8640    42M   
00068         pScan.0001.ms  30    [ 0  1  2  3  4]  [64 64 64 64 64]  8544    42M   
00069 
00070 
00071 
00072        Keyword arguments:
00073        vis -- Name of multi-MS or normal MS.
00074               default: ''. 
00075               example: vis='pScan.mms'
00076 
00077        createdict -- Create and return a dictionary containing scan summaries of each
00078                      sub-MS. 
00079               default: False
00080               
00081               If set to True, the returned dictionary will contain information from
00082               ms.getscansummary() and ms.getspectralwindowinfo(), with the addition of an 
00083               index as the top key and the sub-MS name.
00084               Example:
00085               
00086             {0: {'MS': 'pScan.0000.ms',
00087                  'scanId': {31: {'nchans': array([64, 64, 64, 64, 64]),
00088                                  'nrows': 8640,
00089                                  'spwIds': array([ 0,  1,  2,  3,  4])}},
00090                  'size': '42M'},
00091              1: {'MS': 'pScan.0001.ms',
00092                  'scanId': {30: {'nchans': array([64, 64, 64, 64, 64]),
00093                                  'nrows': 8544,
00094                                  'spwIds': array([ 0,  1,  2,  3,  4])}},
00095                  'size': '42M'}}
00096 
00097                     
00098        listfile -- Name of ASCII file to save output to. If empty, it will 
00099                    list on the logger/terminal.
00100               default: ''
00101               example: listfile='pscan.txt'
00102 
00103  
00104         """
00105         if not hasattr(self, "__globals__") or self.__globals__ == None :
00106            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00107         #casac = self.__globals__['casac']
00108         casalog = self.__globals__['casalog']
00109         #casalog = casac.casac.logsink()
00110         self.__globals__['__last_task'] = 'listpartition'
00111         self.__globals__['taskname'] = 'listpartition'
00112         ###
00113         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00114         ###
00115         ###
00116         #Handle globals or user over-ride of arguments
00117         #
00118         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00119         useLocalDefaults = False
00120 
00121         for item in function_signature_defaults.iteritems():
00122                 key,val = item
00123                 keyVal = eval(key)
00124                 if (keyVal == None):
00125                         #user hasn't set it - use global/default
00126                         pass
00127                 else:
00128                         #user has set it - use over-ride
00129                         if (key != 'self') :
00130                            useLocalDefaults = True
00131 
00132         myparams = {}
00133         if useLocalDefaults :
00134            for item in function_signature_defaults.iteritems():
00135                key,val = item
00136                keyVal = eval(key)
00137                exec('myparams[key] = keyVal')
00138                self.parameters[key] = keyVal
00139                if (keyVal == None):
00140                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00141                    keyVal = eval(key)
00142                    if(type(keyVal) == dict) :
00143                       if len(keyVal) > 0 :
00144                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00145                       else :
00146                          exec('myparams[key] = ' + key + ' = {}')
00147 
00148         else :
00149             async = self.parameters['async']
00150             myparams['vis'] = vis = self.parameters['vis']
00151             myparams['createdict'] = createdict = self.parameters['createdict']
00152             myparams['listfile'] = listfile = self.parameters['listfile']
00153 
00154 
00155         result = None
00156 
00157 #
00158 #    The following is work around to avoid a bug with current python translation
00159 #
00160         mytmp = {}
00161 
00162         mytmp['vis'] = vis
00163         mytmp['createdict'] = createdict
00164         mytmp['listfile'] = listfile
00165         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00166         trec = casac.casac.utils().torecord(pathname+'listpartition.xml')
00167 
00168         casalog.origin('listpartition')
00169         try :
00170           #if not trec.has_key('listpartition') or not casac.casac.utils().verify(mytmp, trec['listpartition']) :
00171             #return False
00172 
00173           casac.casac.utils().verify(mytmp, trec['listpartition'], True)
00174           scriptstr=['']
00175           saveinputs = self.__globals__['saveinputs']
00176           saveinputs('listpartition', 'listpartition.last', myparams, self.__globals__,scriptstr=scriptstr)
00177           if async :
00178             count = 0
00179             keybase =  time.strftime("%y%m%d.%H%M%S")
00180             key = keybase + "_" + str(count)
00181             while self.__async__.has_key(key) :
00182                count += 1
00183                key = keybase + "_" + str(count)
00184             result = tm.execute('listpartition', vis, createdict, listfile)
00185             print "Use: "
00186             print "      tm.retrieve(return_value) # to retrieve the status"
00187             print 
00188             self.rkey = key
00189             self.__async__[key] = result
00190           else :
00191               tname = 'listpartition'
00192               spaces = ' '*(18-len(tname))
00193               casalog.post('\n##########################################'+
00194                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00195               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00196               result = listpartition(vis, createdict, listfile)
00197               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00198                            '\n##########################################')
00199 
00200         except Exception, instance:
00201           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00202              raise
00203           else :
00204              #print '**** Error **** ',instance
00205              tname = 'listpartition'
00206              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00207              pass
00208 
00209         gc.collect()
00210         return result
00211 #
00212 #
00213 #
00214     def paramgui(self, useGlobals=True, ipython_globals=None):
00215         """
00216         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00217         """
00218         import paramgui
00219         if not hasattr(self, "__globals__") or self.__globals__ == None :
00220            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00221 
00222         if useGlobals:
00223             if ipython_globals == None:
00224                 myf=self.__globals__
00225             else:
00226                 myf=ipython_globals
00227 
00228             paramgui.setGlobals(myf)
00229         else:
00230             paramgui.setGlobals({})
00231 
00232         paramgui.runTask('listpartition', myf['_ip'])
00233         paramgui.setGlobals({})
00234 
00235 #
00236 #
00237 #
00238     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00239         if not hasattr(self, "__globals__") or self.__globals__ == None :
00240            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00241         if ipython_globals == None:
00242             myf=self.__globals__
00243         else:
00244             myf=ipython_globals
00245 
00246         a = odict()
00247         a['vis']  = ''
00248         a['createdict']  = False
00249         a['listfile']  = ''
00250 
00251         a['async']=False
00252 
00253 ### This function sets the default values but also will return the list of
00254 ### parameters or the default value of a given parameter
00255         if(param == None):
00256                 myf['__set_default_parameters'](a)
00257         elif(param == 'paramkeys'):
00258                 return a.keys()
00259         else:
00260             if(paramvalue==None and subparam==None):
00261                if(a.has_key(param)):
00262                   return a[param]
00263                else:
00264                   return self.itsdefault(param)
00265             else:
00266                retval=a[param]
00267                if(type(a[param])==dict):
00268                   for k in range(len(a[param])):
00269                      valornotval='value'
00270                      if(a[param][k].has_key('notvalue')):
00271                         valornotval='notvalue'
00272                      if((a[param][k][valornotval])==paramvalue):
00273                         retval=a[param][k].copy()
00274                         retval.pop(valornotval)
00275                         if(subparam != None):
00276                            if(retval.has_key(subparam)):
00277                               retval=retval[subparam]
00278                            else:
00279                               retval=self.itsdefault(subparam)
00280                      else:
00281                         retval=self.itsdefault(subparam)
00282                return retval
00283 
00284 
00285 #
00286 #
00287     def check_params(self, param=None, value=None, ipython_globals=None):
00288       if ipython_globals == None:
00289           myf=self.__globals__
00290       else:
00291           myf=ipython_globals
00292 #      print 'param:', param, 'value:', value
00293       try :
00294          if str(type(value)) != "<type 'instance'>" :
00295             value0 = value
00296             value = myf['cu'].expandparam(param, value)
00297             matchtype = False
00298             if(type(value) == numpy.ndarray):
00299                if(type(value) == type(value0)):
00300                   myf[param] = value.tolist()
00301                else:
00302                   #print 'value:', value, 'value0:', value0
00303                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00304                   myf[param] = value0
00305                   if type(value0) != list :
00306                      matchtype = True
00307             else :
00308                myf[param] = value
00309             value = myf['cu'].verifyparam({param:value})
00310             if matchtype:
00311                value = False
00312       except Exception, instance:
00313          #ignore the exception and just return it unchecked
00314          myf[param] = value
00315       return value
00316 #
00317 #
00318     def description(self, key='listpartition', subkey=None):
00319         desc={'listpartition': 'List the summary of a multi-MS data set in the logger or in a file',
00320                'vis': 'Name of multi-MS or normal MS.',
00321                'createdict': 'Create and return a dictionary with sub-MS information',
00322                'listfile': 'Name of ASCII file to save output: \'\'==>to terminal',
00323 
00324                'async': 'If true the taskname must be started using listpartition(...)'
00325               }
00326 
00327         if(desc.has_key(key)) :
00328            return desc[key]
00329 
00330     def itsdefault(self, paramname) :
00331         a = {}
00332         a['vis']  = ''
00333         a['createdict']  = False
00334         a['listfile']  = ''
00335 
00336         #a = sys._getframe(len(inspect.stack())-1).f_globals
00337 
00338         if a.has_key(paramname) :
00339               return a[paramname]
00340 listpartition_cli = listpartition_cli_()