casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
browsetable_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_browsetable import browsetable
00018 class browsetable_cli_:
00019     __name__ = "browsetable"
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__ = (browsetable_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'tablename':None, 'mightedit':None, 'sortlist':None, 'taql':None, 'skipcols':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, tablename=None, mightedit=None, sortlist=None, taql=None, skipcols=None,  async=None):
00047 
00048         """Browse a table (MS, calibration table, image)
00049     This task brings up a browser that can open and display any CASA table.
00050     The tablename can be specified at startup, or any table can be loaded after
00051     the browser comes up.
00052             
00053     Parameters:
00054     tablename -- Name of table file on disk (vis, calibration table, image)
00055                  default: none; example: tablename='ngc5921.ms'
00056     mightedit -- If True disable the filtering options (below) and allow
00057                  editing the table.  Warning: the GUI appears to ignore
00058                  whether the table tool is opened read-only - just be
00059                  aware that you should not edit filtered tables unless
00060                  you know what you are doing.
00061     sortlist  -- List of columns to sort by.
00062                  default: [] (none)
00063     taql      -- TaQL query string for prefiltering the table.
00064                  default: "" (none); example: taql="ANTENNA2 < 6"
00065     skipcols  -- Columns to NOT display.
00066                  default: [] (none); example: skipcols='feed1, feed2'    
00067             
00068     
00069     Some comments on using browsetable (see cookbook also):
00070     
00071      Most often you will browse a measurement set.  Either specify the vis name
00072      as the tablename, or when the browser comes up,
00073     
00074             click on <file> (upper left), then click on <open table>
00075     
00076      If you want to look at sub-tables, use the tab table keywords along the
00077      left side to bring up a panel with the sub-tables listed (Fig 3.8), then
00078      choose (left-click) a table and View.
00079     
00080      Note that one useful feature is that you can Edit any table and its
00081      contents. Use the Edit tab (to the right of the file tab).  Be careful
00082      with this, and make a backup copy of the table before editing!
00083     
00084      Use the Close Tables and Exit option from the Files menu to quit the
00085      casabrowser.
00086     
00087      To get a plot of two table values, click on tools, then click on plot 2D.
00088      For example, to get a u-v plot, in the Plotter Option Gui,
00089           set Rows:  0   to  <Large Number>
00090           X Axis:  UVW      Slice  (set 0)
00091           Y Axis:  UVW      Slice  (set 1)
00092           click 'Clear and Plot' on right.
00093     
00094      For visibility plots
00095           X Axis:  TIME
00096           Y Axis:  DATA     Slice Amplitude
00097           click 'Clear and Plot' on right.
00098        
00099        
00100 
00101         """
00102         if not hasattr(self, "__globals__") or self.__globals__ == None :
00103            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00104         #casac = self.__globals__['casac']
00105         casalog = self.__globals__['casalog']
00106         #casalog = casac.casac.logsink()
00107         self.__globals__['__last_task'] = 'browsetable'
00108         self.__globals__['taskname'] = 'browsetable'
00109         ###
00110         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00111         ###
00112         ###
00113         #Handle globals or user over-ride of arguments
00114         #
00115         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00116         useLocalDefaults = False
00117 
00118         for item in function_signature_defaults.iteritems():
00119                 key,val = item
00120                 keyVal = eval(key)
00121                 if (keyVal == None):
00122                         #user hasn't set it - use global/default
00123                         pass
00124                 else:
00125                         #user has set it - use over-ride
00126                         if (key != 'self') :
00127                            useLocalDefaults = True
00128 
00129         myparams = {}
00130         if useLocalDefaults :
00131            for item in function_signature_defaults.iteritems():
00132                key,val = item
00133                keyVal = eval(key)
00134                exec('myparams[key] = keyVal')
00135                self.parameters[key] = keyVal
00136                if (keyVal == None):
00137                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00138                    keyVal = eval(key)
00139                    if(type(keyVal) == dict) :
00140                       if len(keyVal) > 0 :
00141                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00142                       else :
00143                          exec('myparams[key] = ' + key + ' = {}')
00144 
00145         else :
00146             async = self.parameters['async']
00147             myparams['tablename'] = tablename = self.parameters['tablename']
00148             myparams['mightedit'] = mightedit = self.parameters['mightedit']
00149             myparams['sortlist'] = sortlist = self.parameters['sortlist']
00150             myparams['taql'] = taql = self.parameters['taql']
00151             myparams['skipcols'] = skipcols = self.parameters['skipcols']
00152 
00153 
00154         result = None
00155 
00156 #
00157 #    The following is work around to avoid a bug with current python translation
00158 #
00159         mytmp = {}
00160 
00161         mytmp['tablename'] = tablename
00162         mytmp['mightedit'] = mightedit
00163         mytmp['sortlist'] = sortlist
00164         mytmp['taql'] = taql
00165         mytmp['skipcols'] = skipcols
00166         #
00167         # This task is never suppose to use the task manager to run async
00168         #
00169         async=False
00170         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00171         trec = casac.casac.utils().torecord(pathname+'browsetable.xml')
00172 
00173         casalog.origin('browsetable')
00174         try :
00175           #if not trec.has_key('browsetable') or not casac.casac.utils().verify(mytmp, trec['browsetable']) :
00176             #return False
00177 
00178           casac.casac.utils().verify(mytmp, trec['browsetable'], True)
00179           scriptstr=['']
00180           saveinputs = self.__globals__['saveinputs']
00181           saveinputs('browsetable', 'browsetable.last', myparams, self.__globals__,scriptstr=scriptstr)
00182           if async :
00183             count = 0
00184             keybase =  time.strftime("%y%m%d.%H%M%S")
00185             key = keybase + "_" + str(count)
00186             while self.__async__.has_key(key) :
00187                count += 1
00188                key = keybase + "_" + str(count)
00189             result = tm.execute('browsetable', tablename, mightedit, sortlist, taql, skipcols)
00190             print "Use: "
00191             print "      tm.retrieve(return_value) # to retrieve the status"
00192             print 
00193             self.rkey = key
00194             self.__async__[key] = result
00195           else :
00196               tname = 'browsetable'
00197               spaces = ' '*(18-len(tname))
00198               casalog.post('\n##########################################'+
00199                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00200               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00201               result = browsetable(tablename, mightedit, sortlist, taql, skipcols)
00202               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00203                            '\n##########################################')
00204 
00205         except Exception, instance:
00206           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00207              raise
00208           else :
00209              #print '**** Error **** ',instance
00210              tname = 'browsetable'
00211              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00212              pass
00213 
00214         gc.collect()
00215         return result
00216 #
00217 #
00218 #
00219     def paramgui(self, useGlobals=True, ipython_globals=None):
00220         """
00221         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00222         """
00223         import paramgui
00224         if not hasattr(self, "__globals__") or self.__globals__ == None :
00225            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00226 
00227         if useGlobals:
00228             if ipython_globals == None:
00229                 myf=self.__globals__
00230             else:
00231                 myf=ipython_globals
00232 
00233             paramgui.setGlobals(myf)
00234         else:
00235             paramgui.setGlobals({})
00236 
00237         paramgui.runTask('browsetable', myf['_ip'])
00238         paramgui.setGlobals({})
00239 
00240 #
00241 #
00242 #
00243     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00244         if not hasattr(self, "__globals__") or self.__globals__ == None :
00245            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00246         if ipython_globals == None:
00247             myf=self.__globals__
00248         else:
00249             myf=ipython_globals
00250 
00251         a = odict()
00252         a['tablename']  = ''
00253 
00254         a['async']=False
00255         a['tablename'] = {
00256                     0:odict([{'notvalue':''}, {'mightedit':False}, {'sortlist':''}, {'taql':''}, {'skipcols':''}])}
00257 
00258 ### This function sets the default values but also will return the list of
00259 ### parameters or the default value of a given parameter
00260         if(param == None):
00261                 myf['__set_default_parameters'](a)
00262         elif(param == 'paramkeys'):
00263                 return a.keys()
00264         else:
00265             if(paramvalue==None and subparam==None):
00266                if(a.has_key(param)):
00267                   return a[param]
00268                else:
00269                   return self.itsdefault(param)
00270             else:
00271                retval=a[param]
00272                if(type(a[param])==dict):
00273                   for k in range(len(a[param])):
00274                      valornotval='value'
00275                      if(a[param][k].has_key('notvalue')):
00276                         valornotval='notvalue'
00277                      if((a[param][k][valornotval])==paramvalue):
00278                         retval=a[param][k].copy()
00279                         retval.pop(valornotval)
00280                         if(subparam != None):
00281                            if(retval.has_key(subparam)):
00282                               retval=retval[subparam]
00283                            else:
00284                               retval=self.itsdefault(subparam)
00285                      else:
00286                         retval=self.itsdefault(subparam)
00287                return retval
00288 
00289 
00290 #
00291 #
00292     def check_params(self, param=None, value=None, ipython_globals=None):
00293       if ipython_globals == None:
00294           myf=self.__globals__
00295       else:
00296           myf=ipython_globals
00297 #      print 'param:', param, 'value:', value
00298       try :
00299          if str(type(value)) != "<type 'instance'>" :
00300             value0 = value
00301             value = myf['cu'].expandparam(param, value)
00302             matchtype = False
00303             if(type(value) == numpy.ndarray):
00304                if(type(value) == type(value0)):
00305                   myf[param] = value.tolist()
00306                else:
00307                   #print 'value:', value, 'value0:', value0
00308                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00309                   myf[param] = value0
00310                   if type(value0) != list :
00311                      matchtype = True
00312             else :
00313                myf[param] = value
00314             value = myf['cu'].verifyparam({param:value})
00315             if matchtype:
00316                value = False
00317       except Exception, instance:
00318          #ignore the exception and just return it unchecked
00319          myf[param] = value
00320       return value
00321 #
00322 #
00323     def description(self, key='browsetable', subkey=None):
00324         desc={'browsetable': 'Browse a table (MS, calibration table, image)',
00325                'tablename': 'Name of input table',
00326                'mightedit': 'Warning: the GUI seems to ignore whether the table tool is opened read-only - just be careful, esp. if filtering.',
00327                'sortlist': 'Columns to sort by (ascending)',
00328                'taql': 'TaQL query string for prefiltering the table.',
00329                'skipcols': 'Columns to omit',
00330 
00331                'async': 'If true the taskname must be started using browsetable(...)'
00332               }
00333 
00334 #
00335 # Set subfields defaults if needed
00336 #
00337 
00338         if(desc.has_key(key)) :
00339            return desc[key]
00340 
00341     def itsdefault(self, paramname) :
00342         a = {}
00343         a['tablename']  = ''
00344         a['mightedit']  = False
00345         a['sortlist']  = ''
00346         a['taql']  = ''
00347         a['skipcols']  = ''
00348 
00349         #a = sys._getframe(len(inspect.stack())-1).f_globals
00350 
00351         if self.parameters['tablename']  != '':
00352             a['mightedit'] = False
00353             a['sortlist'] = ''
00354             a['taql'] = ''
00355             a['skipcols'] = ''
00356 
00357         if a.has_key(paramname) :
00358               return a[paramname]
00359 browsetable_cli = browsetable_cli_()