casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
virtualconcat_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_virtualconcat import virtualconcat
00018 class virtualconcat_cli_:
00019     __name__ = "virtualconcat"
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__ = (virtualconcat_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'concatvis':None, 'freqtol':None, 'dirtol':None, 'respectname':None, 'visweightscale':None, 'keepcopy':None, 'copypointing':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, concatvis=None, freqtol=None, dirtol=None, respectname=None, visweightscale=None, keepcopy=None, copypointing=None,  async=None):
00047 
00048         """Concatenate several visibility data sets into a multi-MS
00049 
00050 The list of data sets given in the vis argument are moved into an output
00051 multi-MS data set concatvis and virtually concatenated. 
00052 
00053 NOTE: This task will modify the input datasets by moving them and reindexing them.
00054 If you want to keep a copy of your original data, please set the parameter 
00055 keepcopy to True.
00056 
00057 There is no limit to the number of input data sets.
00058 
00059 If none of the input data sets have any scratch columns (model and corrected
00060 columns), none are created in the concatvis.  Otherwise these columns are
00061 created on output and initialized to their default value (1 in model column,
00062 data in corrected column) for those data with no input columns.
00063 
00064 Spectral windows for each data set with the same chanelization, and within a
00065 specified frequency tolerance of another data set will be combined into one
00066 spectral window.
00067 
00068 A field position in one data set that is within a specified direction tolerance
00069 of another field position in any other data set will be combined into one
00070 field.  The field names need not be the same---only their position is used.
00071 
00072 Each appended dataset is assigned a new observation id if the corresponding
00073 rows in the observation table are not the same.
00074 
00075 Keyword arguments:
00076 vis -- Name of input visibility files to be combined
00077         default: none; example: vis = ['src2.ms','ngc5921.ms','ngc315.ms']
00078 concatvis -- Name of visibility file that will contain the concatenated data
00079         note: if this file exits on disk then the input files are 
00080               added to this file.  Otherwise the new file contains  
00081               the concatenated data.  Be careful here when concatenating to
00082               an existing file.
00083         default: none; example: concatvis='src2.ms'
00084                  example: concatvis='outvis.ms'
00085 
00086         other examples: 
00087            virtualconcat(vis=['src2.ms','ngc5921.ms'], concatvis='out.mms') 
00088                will concatenate 'ngc5921.ms' and 'src2.ms' into a file named 
00089                'out.mms'; the original 'ngc5921.ms' and 'src2.ms' are gone.
00090                'out.mms' is a multims. As most of the data is only moved, not 
00091                copied, this is faster and subsequent tasks can run in parallel
00092                on the subMSs of out.mms.
00093            virtualconcat(vis=['src2.ms','ngc5921.ms'], concatvis='out.mms', keepcopy=True) 
00094                will concatenate 'ngc5921.ms' and 'src2.ms' into a file named 
00095                'out.mms'; the original 'ngc5921.ms' and 'src2.ms' are as before
00096                but you consume more disk space and time for the copy.
00097                .
00098 
00099      Note: run flagmanager to save flags in the concatvis
00100 
00101 freqtol -- Frequency shift tolerance for considering data to be in the same
00102            spwid.  The number of channels must also be the same.
00103         default: ''  do not combine unless frequencies are equal
00104         example: freqtol='10MHz' will not combine spwid unless they are
00105            within 10 MHz.
00106         Note: This option is useful to conbine spectral windows with very slight
00107            frequency differences caused by Doppler tracking, for example.
00108 
00109 dirtol -- Direction shift tolerance for considering data as the same field
00110         default: '' means always combine.
00111         example: dirtol='1.arcsec' will not combine data for a field unless
00112            their phase center differ by less than 1 arcsec.  If the field names
00113            are different in the input data sets, the name in the output data
00114            set will be the first relevant data set in the list.
00115 
00116 respectname -- If true, fields with a different name are not merged even if their 
00117         direction agrees (within dirtol). 
00118         default: True
00119 
00120 visweightscale -- The weights of the individual MSs will be scaled in the concatenated
00121         output MS by the factors in this list. Useful for handling heterogeneous arrays.
00122         Use plotms to inspect the "Wt" column as a reference for determining the scaling 
00123         factors. See the cookbook for more details.
00124         example: [1.,3.,3.] - scale the weights of the second and third MS by a factor 3.
00125         default: [] (empty list) - no scaling
00126 
00127 keepcopy -- If true, a copy of the input MSs is kept in their original place.
00128         default: false
00129 
00130 copypointing -- If true, the POINTING table information will be present in the output.
00131                 If false, the result is an empty POINTING table.
00132          default: true
00133 
00134 
00135         """
00136         if not hasattr(self, "__globals__") or self.__globals__ == None :
00137            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00138         #casac = self.__globals__['casac']
00139         casalog = self.__globals__['casalog']
00140         #casalog = casac.casac.logsink()
00141         self.__globals__['__last_task'] = 'virtualconcat'
00142         self.__globals__['taskname'] = 'virtualconcat'
00143         ###
00144         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00145         ###
00146         ###
00147         #Handle globals or user over-ride of arguments
00148         #
00149         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00150         useLocalDefaults = False
00151 
00152         for item in function_signature_defaults.iteritems():
00153                 key,val = item
00154                 keyVal = eval(key)
00155                 if (keyVal == None):
00156                         #user hasn't set it - use global/default
00157                         pass
00158                 else:
00159                         #user has set it - use over-ride
00160                         if (key != 'self') :
00161                            useLocalDefaults = True
00162 
00163         myparams = {}
00164         if useLocalDefaults :
00165            for item in function_signature_defaults.iteritems():
00166                key,val = item
00167                keyVal = eval(key)
00168                exec('myparams[key] = keyVal')
00169                self.parameters[key] = keyVal
00170                if (keyVal == None):
00171                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00172                    keyVal = eval(key)
00173                    if(type(keyVal) == dict) :
00174                       if len(keyVal) > 0 :
00175                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00176                       else :
00177                          exec('myparams[key] = ' + key + ' = {}')
00178 
00179         else :
00180             async = self.parameters['async']
00181             myparams['vis'] = vis = self.parameters['vis']
00182             myparams['concatvis'] = concatvis = self.parameters['concatvis']
00183             myparams['freqtol'] = freqtol = self.parameters['freqtol']
00184             myparams['dirtol'] = dirtol = self.parameters['dirtol']
00185             myparams['respectname'] = respectname = self.parameters['respectname']
00186             myparams['visweightscale'] = visweightscale = self.parameters['visweightscale']
00187             myparams['keepcopy'] = keepcopy = self.parameters['keepcopy']
00188             myparams['copypointing'] = copypointing = self.parameters['copypointing']
00189 
00190         if type(vis)==str: vis=[vis]
00191         if type(visweightscale)==float: visweightscale=[visweightscale]
00192 
00193         result = None
00194 
00195 #
00196 #    The following is work around to avoid a bug with current python translation
00197 #
00198         mytmp = {}
00199 
00200         mytmp['vis'] = vis
00201         mytmp['concatvis'] = concatvis
00202         mytmp['freqtol'] = freqtol
00203         mytmp['dirtol'] = dirtol
00204         mytmp['respectname'] = respectname
00205         mytmp['visweightscale'] = visweightscale
00206         mytmp['keepcopy'] = keepcopy
00207         mytmp['copypointing'] = copypointing
00208         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00209         trec = casac.casac.utils().torecord(pathname+'virtualconcat.xml')
00210 
00211         casalog.origin('virtualconcat')
00212         try :
00213           #if not trec.has_key('virtualconcat') or not casac.casac.utils().verify(mytmp, trec['virtualconcat']) :
00214             #return False
00215 
00216           casac.casac.utils().verify(mytmp, trec['virtualconcat'], True)
00217           scriptstr=['']
00218           saveinputs = self.__globals__['saveinputs']
00219           saveinputs('virtualconcat', 'virtualconcat.last', myparams, self.__globals__,scriptstr=scriptstr)
00220           if async :
00221             count = 0
00222             keybase =  time.strftime("%y%m%d.%H%M%S")
00223             key = keybase + "_" + str(count)
00224             while self.__async__.has_key(key) :
00225                count += 1
00226                key = keybase + "_" + str(count)
00227             result = tm.execute('virtualconcat', vis, concatvis, freqtol, dirtol, respectname, visweightscale, keepcopy, copypointing)
00228             print "Use: "
00229             print "      tm.retrieve(return_value) # to retrieve the status"
00230             print 
00231             self.rkey = key
00232             self.__async__[key] = result
00233           else :
00234               tname = 'virtualconcat'
00235               spaces = ' '*(18-len(tname))
00236               casalog.post('\n##########################################'+
00237                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00238               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00239               result = virtualconcat(vis, concatvis, freqtol, dirtol, respectname, visweightscale, keepcopy, copypointing)
00240               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00241                            '\n##########################################')
00242 
00243         except Exception, instance:
00244           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00245              raise
00246           else :
00247              #print '**** Error **** ',instance
00248              tname = 'virtualconcat'
00249              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00250              pass
00251 
00252         gc.collect()
00253         return result
00254 #
00255 #
00256 #
00257     def paramgui(self, useGlobals=True, ipython_globals=None):
00258         """
00259         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00260         """
00261         import paramgui
00262         if not hasattr(self, "__globals__") or self.__globals__ == None :
00263            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00264 
00265         if useGlobals:
00266             if ipython_globals == None:
00267                 myf=self.__globals__
00268             else:
00269                 myf=ipython_globals
00270 
00271             paramgui.setGlobals(myf)
00272         else:
00273             paramgui.setGlobals({})
00274 
00275         paramgui.runTask('virtualconcat', myf['_ip'])
00276         paramgui.setGlobals({})
00277 
00278 #
00279 #
00280 #
00281     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00282         if not hasattr(self, "__globals__") or self.__globals__ == None :
00283            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00284         if ipython_globals == None:
00285             myf=self.__globals__
00286         else:
00287             myf=ipython_globals
00288 
00289         a = odict()
00290         a['vis']  = ['']
00291         a['concatvis']  = ''
00292         a['freqtol']  = ''
00293         a['dirtol']  = ''
00294         a['respectname']  = True
00295         a['visweightscale']  = []
00296         a['keepcopy']  = False
00297         a['copypointing']  = True
00298 
00299         a['async']=False
00300 
00301 ### This function sets the default values but also will return the list of
00302 ### parameters or the default value of a given parameter
00303         if(param == None):
00304                 myf['__set_default_parameters'](a)
00305         elif(param == 'paramkeys'):
00306                 return a.keys()
00307         else:
00308             if(paramvalue==None and subparam==None):
00309                if(a.has_key(param)):
00310                   return a[param]
00311                else:
00312                   return self.itsdefault(param)
00313             else:
00314                retval=a[param]
00315                if(type(a[param])==dict):
00316                   for k in range(len(a[param])):
00317                      valornotval='value'
00318                      if(a[param][k].has_key('notvalue')):
00319                         valornotval='notvalue'
00320                      if((a[param][k][valornotval])==paramvalue):
00321                         retval=a[param][k].copy()
00322                         retval.pop(valornotval)
00323                         if(subparam != None):
00324                            if(retval.has_key(subparam)):
00325                               retval=retval[subparam]
00326                            else:
00327                               retval=self.itsdefault(subparam)
00328                      else:
00329                         retval=self.itsdefault(subparam)
00330                return retval
00331 
00332 
00333 #
00334 #
00335     def check_params(self, param=None, value=None, ipython_globals=None):
00336       if ipython_globals == None:
00337           myf=self.__globals__
00338       else:
00339           myf=ipython_globals
00340 #      print 'param:', param, 'value:', value
00341       try :
00342          if str(type(value)) != "<type 'instance'>" :
00343             value0 = value
00344             value = myf['cu'].expandparam(param, value)
00345             matchtype = False
00346             if(type(value) == numpy.ndarray):
00347                if(type(value) == type(value0)):
00348                   myf[param] = value.tolist()
00349                else:
00350                   #print 'value:', value, 'value0:', value0
00351                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00352                   myf[param] = value0
00353                   if type(value0) != list :
00354                      matchtype = True
00355             else :
00356                myf[param] = value
00357             value = myf['cu'].verifyparam({param:value})
00358             if matchtype:
00359                value = False
00360       except Exception, instance:
00361          #ignore the exception and just return it unchecked
00362          myf[param] = value
00363       return value
00364 #
00365 #
00366     def description(self, key='virtualconcat', subkey=None):
00367         desc={'virtualconcat': 'Concatenate several visibility data sets into a multi-MS',
00368                'vis': 'List of names of input visibility files to be concatenated',
00369                'concatvis': 'Name of the output visibility file (a multi-MS)',
00370                'freqtol': 'Frequency shift tolerance for considering data as the same spwid',
00371                'dirtol': 'Direction shift tolerance for considering data as the same field',
00372                'respectname': 'If true, fields with a different name are not merged even if their direction agrees',
00373                'visweightscale': 'List of the weight scaling factors to be applied to the individual MSs',
00374                'keepcopy': 'If true, a copy of the input MSs is kept in their original place.',
00375                'copypointing': 'If true, keep the POINTING table information in the output MMS. If false, don\'t.',
00376 
00377                'async': 'If true the taskname must be started using virtualconcat(...)'
00378               }
00379 
00380         if(desc.has_key(key)) :
00381            return desc[key]
00382 
00383     def itsdefault(self, paramname) :
00384         a = {}
00385         a['vis']  = ['']
00386         a['concatvis']  = ''
00387         a['freqtol']  = ''
00388         a['dirtol']  = ''
00389         a['respectname']  = True
00390         a['visweightscale']  = []
00391         a['keepcopy']  = False
00392         a['copypointing']  = True
00393 
00394         #a = sys._getframe(len(inspect.stack())-1).f_globals
00395 
00396         if a.has_key(paramname) :
00397               return a[paramname]
00398 virtualconcat_cli = virtualconcat_cli_()