casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
exportasdm_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_exportasdm import exportasdm
00018 class exportasdm_cli_:
00019     __name__ = "exportasdm"
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__ = (exportasdm_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'asdm':None, 'datacolumn':None, 'archiveid':None, 'rangeid':None, 'subscanduration':None, 'sbduration':None, 'apcorrected':None, 'verbose':None, 'showversion':None, 'useversion':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, asdm=None, datacolumn=None, archiveid=None, rangeid=None, subscanduration=None, sbduration=None, apcorrected=None, verbose=None, showversion=None, useversion=None,  async=None):
00047 
00048         """Convert a CASA visibility file (MS) into an ALMA Science Data Model
00049 
00050   Keyword arguments:
00051   vis -- MS name,
00052          default: none
00053 
00054   asdm -- Name of output ASDM file (directory),
00055           default: none; example: asdm='ExecBlock3'
00056 
00057   datacolumn -- specifies which of the MS data columns (data,
00058            corrected, or model) should be used as the
00059            visibilities in the ASDM, default: data
00060 
00061   archiveid -- the X0 in uid://X0/X1/X<running>
00062                default: "S0"
00063 
00064   rangeid -- the X1 in uid://X0/X1/X<running>
00065              default: "X1"
00066 
00067   subscanduration -- maximum duration of a subscan in the output ASDM
00068                      default: "24h"
00069 
00070   sbduration -- maximum duration of a scheduling block in the output ASDM
00071                      default: "2700s"
00072 
00073   apcorrected -- If true, the data in column datacolumn will be marked
00074                  as having atmospheric phase correction, default: True
00075 
00076   verbose     -- produce log output, default: True
00077 
00078   showversion -- report the version of the ASDM class set, 
00079                  default: True
00080 
00081   useversion -- Selects the version of MS2asdm to be used (\'v3\' (default) or \'v2\' (version before May 2011))
00082                 default: v3
00083 
00084   exportasdm(vis='ngc4826.ms', asdm='uid___S021_X1418_X1', 
00085   datacolumn='corrected', archiveid='S021', rangeid='X1418', 
00086   verbose=False)
00087   will produce an ASDM named 'uid___S021_X1418_X1' using the 
00088   datacolumn 'corrected' in the MS 'ngc4826.ms' with minimal
00089   log output. 
00090 
00091   Note concerning ALMA data: exportasdm presently is not able to export 
00092   from MSs containing WVR data. If you attempt to export such an MS, you
00093   will receive an error message saying that you can only export data of
00094   processor type "CORRELATOR". It will also give you the list of SPWs
00095   which contain CORRELATOR data. You will then have to split out these
00096   SPWs using the task "split" and run exportasdm on the resulting MS. 
00097 
00098   
00099         """
00100         if not hasattr(self, "__globals__") or self.__globals__ == None :
00101            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00102         #casac = self.__globals__['casac']
00103         casalog = self.__globals__['casalog']
00104         #casalog = casac.casac.logsink()
00105         self.__globals__['__last_task'] = 'exportasdm'
00106         self.__globals__['taskname'] = 'exportasdm'
00107         ###
00108         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00109         ###
00110         ###
00111         #Handle globals or user over-ride of arguments
00112         #
00113         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00114         useLocalDefaults = False
00115 
00116         for item in function_signature_defaults.iteritems():
00117                 key,val = item
00118                 keyVal = eval(key)
00119                 if (keyVal == None):
00120                         #user hasn't set it - use global/default
00121                         pass
00122                 else:
00123                         #user has set it - use over-ride
00124                         if (key != 'self') :
00125                            useLocalDefaults = True
00126 
00127         myparams = {}
00128         if useLocalDefaults :
00129            for item in function_signature_defaults.iteritems():
00130                key,val = item
00131                keyVal = eval(key)
00132                exec('myparams[key] = keyVal')
00133                self.parameters[key] = keyVal
00134                if (keyVal == None):
00135                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00136                    keyVal = eval(key)
00137                    if(type(keyVal) == dict) :
00138                       if len(keyVal) > 0 :
00139                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00140                       else :
00141                          exec('myparams[key] = ' + key + ' = {}')
00142 
00143         else :
00144             async = self.parameters['async']
00145             myparams['vis'] = vis = self.parameters['vis']
00146             myparams['asdm'] = asdm = self.parameters['asdm']
00147             myparams['datacolumn'] = datacolumn = self.parameters['datacolumn']
00148             myparams['archiveid'] = archiveid = self.parameters['archiveid']
00149             myparams['rangeid'] = rangeid = self.parameters['rangeid']
00150             myparams['subscanduration'] = subscanduration = self.parameters['subscanduration']
00151             myparams['sbduration'] = sbduration = self.parameters['sbduration']
00152             myparams['apcorrected'] = apcorrected = self.parameters['apcorrected']
00153             myparams['verbose'] = verbose = self.parameters['verbose']
00154             myparams['showversion'] = showversion = self.parameters['showversion']
00155             myparams['useversion'] = useversion = self.parameters['useversion']
00156 
00157 
00158         result = None
00159 
00160 #
00161 #    The following is work around to avoid a bug with current python translation
00162 #
00163         mytmp = {}
00164 
00165         mytmp['vis'] = vis
00166         mytmp['asdm'] = asdm
00167         mytmp['datacolumn'] = datacolumn
00168         mytmp['archiveid'] = archiveid
00169         mytmp['rangeid'] = rangeid
00170         mytmp['subscanduration'] = subscanduration
00171         mytmp['sbduration'] = sbduration
00172         mytmp['apcorrected'] = apcorrected
00173         mytmp['verbose'] = verbose
00174         mytmp['showversion'] = showversion
00175         mytmp['useversion'] = useversion
00176         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00177         trec = casac.casac.utils().torecord(pathname+'exportasdm.xml')
00178 
00179         casalog.origin('exportasdm')
00180         try :
00181           #if not trec.has_key('exportasdm') or not casac.casac.utils().verify(mytmp, trec['exportasdm']) :
00182             #return False
00183 
00184           casac.casac.utils().verify(mytmp, trec['exportasdm'], True)
00185           scriptstr=['']
00186           saveinputs = self.__globals__['saveinputs']
00187           saveinputs('exportasdm', 'exportasdm.last', myparams, self.__globals__,scriptstr=scriptstr)
00188           if async :
00189             count = 0
00190             keybase =  time.strftime("%y%m%d.%H%M%S")
00191             key = keybase + "_" + str(count)
00192             while self.__async__.has_key(key) :
00193                count += 1
00194                key = keybase + "_" + str(count)
00195             result = tm.execute('exportasdm', vis, asdm, datacolumn, archiveid, rangeid, subscanduration, sbduration, apcorrected, verbose, showversion, useversion)
00196             print "Use: "
00197             print "      tm.retrieve(return_value) # to retrieve the status"
00198             print 
00199             self.rkey = key
00200             self.__async__[key] = result
00201           else :
00202               tname = 'exportasdm'
00203               spaces = ' '*(18-len(tname))
00204               casalog.post('\n##########################################'+
00205                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00206               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00207               result = exportasdm(vis, asdm, datacolumn, archiveid, rangeid, subscanduration, sbduration, apcorrected, verbose, showversion, useversion)
00208               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00209                            '\n##########################################')
00210 
00211         except Exception, instance:
00212           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00213              raise
00214           else :
00215              #print '**** Error **** ',instance
00216              tname = 'exportasdm'
00217              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00218              pass
00219 
00220         gc.collect()
00221         return result
00222 #
00223 #
00224 #
00225     def paramgui(self, useGlobals=True, ipython_globals=None):
00226         """
00227         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00228         """
00229         import paramgui
00230         if not hasattr(self, "__globals__") or self.__globals__ == None :
00231            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00232 
00233         if useGlobals:
00234             if ipython_globals == None:
00235                 myf=self.__globals__
00236             else:
00237                 myf=ipython_globals
00238 
00239             paramgui.setGlobals(myf)
00240         else:
00241             paramgui.setGlobals({})
00242 
00243         paramgui.runTask('exportasdm', myf['_ip'])
00244         paramgui.setGlobals({})
00245 
00246 #
00247 #
00248 #
00249     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00250         if not hasattr(self, "__globals__") or self.__globals__ == None :
00251            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00252         if ipython_globals == None:
00253             myf=self.__globals__
00254         else:
00255             myf=ipython_globals
00256 
00257         a = odict()
00258         a['vis']  = ''
00259         a['asdm']  = ''
00260         a['datacolumn']  = 'data'
00261         a['archiveid']  = 'S0'
00262         a['rangeid']  = 'X1'
00263         a['subscanduration']  = '24h'
00264         a['sbduration']  = '2700s'
00265         a['apcorrected']  = True
00266         a['verbose']  = True
00267         a['showversion']  = True
00268         a['useversion']  = 'v3'
00269 
00270         a['async']=False
00271 
00272 ### This function sets the default values but also will return the list of
00273 ### parameters or the default value of a given parameter
00274         if(param == None):
00275                 myf['__set_default_parameters'](a)
00276         elif(param == 'paramkeys'):
00277                 return a.keys()
00278         else:
00279             if(paramvalue==None and subparam==None):
00280                if(a.has_key(param)):
00281                   return a[param]
00282                else:
00283                   return self.itsdefault(param)
00284             else:
00285                retval=a[param]
00286                if(type(a[param])==dict):
00287                   for k in range(len(a[param])):
00288                      valornotval='value'
00289                      if(a[param][k].has_key('notvalue')):
00290                         valornotval='notvalue'
00291                      if((a[param][k][valornotval])==paramvalue):
00292                         retval=a[param][k].copy()
00293                         retval.pop(valornotval)
00294                         if(subparam != None):
00295                            if(retval.has_key(subparam)):
00296                               retval=retval[subparam]
00297                            else:
00298                               retval=self.itsdefault(subparam)
00299                      else:
00300                         retval=self.itsdefault(subparam)
00301                return retval
00302 
00303 
00304 #
00305 #
00306     def check_params(self, param=None, value=None, ipython_globals=None):
00307       if ipython_globals == None:
00308           myf=self.__globals__
00309       else:
00310           myf=ipython_globals
00311 #      print 'param:', param, 'value:', value
00312       try :
00313          if str(type(value)) != "<type 'instance'>" :
00314             value0 = value
00315             value = myf['cu'].expandparam(param, value)
00316             matchtype = False
00317             if(type(value) == numpy.ndarray):
00318                if(type(value) == type(value0)):
00319                   myf[param] = value.tolist()
00320                else:
00321                   #print 'value:', value, 'value0:', value0
00322                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00323                   myf[param] = value0
00324                   if type(value0) != list :
00325                      matchtype = True
00326             else :
00327                myf[param] = value
00328             value = myf['cu'].verifyparam({param:value})
00329             if matchtype:
00330                value = False
00331       except Exception, instance:
00332          #ignore the exception and just return it unchecked
00333          myf[param] = value
00334       return value
00335 #
00336 #
00337     def description(self, key='exportasdm', subkey=None):
00338         desc={'exportasdm': 'Convert a CASA visibility file (MS) into an ALMA Science Data Model',
00339                'vis': 'MS name',
00340                'asdm': 'Name of output ASDM directory (on disk)',
00341                'datacolumn': 'specifies which MS data column is used to fill the visibilites in the ASDM',
00342                'archiveid': 'the X0 in uid://X0/X1/X<running>',
00343                'rangeid': 'the X1 in uid://X0/X1/X<running>',
00344                'subscanduration': 'maximum duration of a subscan in the output ASDM',
00345                'sbduration': 'maximum duration of a scheduling block (and therefore exec block) in the output ASDM',
00346                'apcorrected': 'data to be marked as having atmospheric phase correction',
00347                'verbose': 'produce log output',
00348                'showversion': 'Report the version of ASDM class set being used',
00349                'useversion': 'Selects the version of MS2asdm to be used (\'v3\' (default and only option presently))',
00350 
00351                'async': 'If true the taskname must be started using exportasdm(...)'
00352               }
00353 
00354         if(desc.has_key(key)) :
00355            return desc[key]
00356 
00357     def itsdefault(self, paramname) :
00358         a = {}
00359         a['vis']  = ''
00360         a['asdm']  = ''
00361         a['datacolumn']  = 'data'
00362         a['archiveid']  = 'S0'
00363         a['rangeid']  = 'X1'
00364         a['subscanduration']  = '24h'
00365         a['sbduration']  = '2700s'
00366         a['apcorrected']  = True
00367         a['verbose']  = True
00368         a['showversion']  = True
00369         a['useversion']  = 'v3'
00370 
00371         #a = sys._getframe(len(inspect.stack())-1).f_globals
00372 
00373         if a.has_key(paramname) :
00374               return a[paramname]
00375 exportasdm_cli = exportasdm_cli_()