casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
exportuvfits_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_exportuvfits import exportuvfits
00018 class exportuvfits_cli_:
00019     __name__ = "exportuvfits"
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__ = (exportuvfits_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'fitsfile':None, 'datacolumn':None, 'field':None, 'spw':None, 'antenna':None, 'timerange':None, 'avgchan':None, 'writesyscal':None, 'multisource':None, 'combinespw':None, 'writestation':None, 'padwithflags':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, fitsfile=None, datacolumn=None, field=None, spw=None, antenna=None, timerange=None, avgchan=None, writesyscal=None, multisource=None, combinespw=None, writestation=None, padwithflags=None,  async=None):
00047 
00048         """Convert a CASA visibility data set to a UVFITS file:
00049 
00050         This task writes a UVFITS file, a general format data set used
00051         to transfer data between different software systems.  It is
00052         written in floating point format.  Different programs have different
00053         restrictions on what forms of UVFITS files they will use, especially
00054         whether they will accept multiple sources and/or spectral windows in
00055         the same file.  See the spw, multisource, and combinespw descriptions
00056         below.
00057 
00058         Keyword arguments:
00059         vis -- Name of input visibility file
00060                 default: none;  example: vis='ngc5921.ms'
00061         fitsfile -- Name of output UV FITS file
00062                 default: none;  example='3C273XC1.fits'
00063         datacolumn -- Visibility file data column
00064                 default: => 'corrected'; example: datacolumn='model'
00065                 Options: 'data' (raw),'corrected','model','weight'
00066         field -- Select field using field id(s) or field name(s).
00067                   [run listobs to obtain the list id's or names]
00068                default: ''=all fields
00069                If field string is a non-negative integer, it is assumed a field index
00070                otherwise, it is assumed a field name
00071                field='0~2'; field ids 0,1,2
00072                field='0,4,5~7'; field ids 0,4,5,6,7
00073                field='3C286,3C295'; field named 3C286 adn 3C295
00074                field = '3,4C*'; field id 3, all names starting with 4C
00075         spw -- Select spectral window/channels 
00076                  type 'help par.selection' for more examples.
00077                spw='0~2,4'; spectral windows 0,1,2,4 (all channels)
00078                spw='<2';  spectral windows less than 2 (i.e. 0,1)
00079                spw='0:5~61'; spw 0, channels 5 to 61, INCLUSIVE
00080                spw='*:5~61'; all spw with channels 5 to 62
00081                spw='0,10,3:3~45'; spw 0,10 all channels, spw 3, channels 3 to 45.
00082                spw='0~2:2~6'; spw 0,1,2 with channels 2 through 6 in each.
00083                spw='0:0~10;15~60'; spectral window 0 with channels 0-10,15-60
00084                          NOTE ';' to separate channel selections
00085                spw='0:0~10^2,1:20~30^5'; spw 0, channels 0,2,4,6,8,10,
00086                      spw 1, channels 20,25,30
00087         antenna -- Select data based on antenna/baseline
00088                default: '' (all)
00089                If antenna string is a non-negative integer, it is assumed
00090                   an antenna index
00091                  otherwise, it is assumed as an antenna name
00092                antenna='5&6'; baseline between antenna index 5 and index 6.
00093                antenna='VA05&VA06'; baseline between VLA antenna 5 and 6.
00094                antenna='5&6;7&8'; baseline 5-6 and 7-8
00095                antenna='5'; all baselines with antenna index 5
00096                antenna='05'; all baselines with antenna name '05', vla antenna
00097                antenna='5,6,10'; all baselines with antennas 5, 6 and 10
00098         timerange  -- Select data based on time range:
00099                default = '' (all); examples,
00100                timerange = 'YYYY/MM/DD/hh:mm:ss~YYYY/MM/DD/hh:mm:ss'
00101                Note: if YYYY/MM/DD is missing dat defaults to first day in data set
00102                timerange='09:14:0~09:54:0' picks 40 min on first day
00103                timerange='25:00:00~27:30:00' picks 1 hr to 3 hr 30min on next day
00104                timerange='09:44:00' data within one integration of time
00105                timerange='>10:24:00' data after this time
00106         avgchan -- Channel averaging width (value > 1 indicates averaging)
00107                 default =>1; example: avgchan=3
00108                 output data will average channels in groups of three.
00109         multisource -- Write in multi-source format
00110                 default: => True;
00111                    false if one source is selected
00112                 True works with AIPS, but not difmap.
00113         combinespw -- If True, export the spectral windows as IFs.
00114                       Otherwise multiple windows will use multiple FREQIDs.
00115                 default: =>  True;
00116                    all spectral windows must have same shape.
00117                 True is recommended for AIPS, and mandatory for difmap.
00118         padwithflags -- If True, and combinespw is True, fill in missing
00119                         data as needed to fit the IF structure.  This is
00120                         appropriate if the MS had a few frequency-dependent
00121                         flags applied, and was then time-averaged by split, or
00122                         when exporting for use by difmap.  If the spectral
00123                         windows were observed at different times,
00124                         padwithflags=True will add a large number of flags,
00125                         making the output file significantly longer.  It does
00126                         not yet support spectral windows with different widths.
00127         writestation -- Write station name instead of antenna name
00128                 default: True;
00129         writesyscal -- Write GC and TY tables
00130                 default: => False; Not yet available
00131         async --  Run asynchronously
00132                 default = False;
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'] = 'exportuvfits'
00142         self.__globals__['taskname'] = 'exportuvfits'
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['fitsfile'] = fitsfile = self.parameters['fitsfile']
00183             myparams['datacolumn'] = datacolumn = self.parameters['datacolumn']
00184             myparams['field'] = field = self.parameters['field']
00185             myparams['spw'] = spw = self.parameters['spw']
00186             myparams['antenna'] = antenna = self.parameters['antenna']
00187             myparams['timerange'] = timerange = self.parameters['timerange']
00188             myparams['avgchan'] = avgchan = self.parameters['avgchan']
00189             myparams['writesyscal'] = writesyscal = self.parameters['writesyscal']
00190             myparams['multisource'] = multisource = self.parameters['multisource']
00191             myparams['combinespw'] = combinespw = self.parameters['combinespw']
00192             myparams['writestation'] = writestation = self.parameters['writestation']
00193             myparams['padwithflags'] = padwithflags = self.parameters['padwithflags']
00194 
00195 
00196         result = None
00197 
00198 #
00199 #    The following is work around to avoid a bug with current python translation
00200 #
00201         mytmp = {}
00202 
00203         mytmp['vis'] = vis
00204         mytmp['fitsfile'] = fitsfile
00205         mytmp['datacolumn'] = datacolumn
00206         mytmp['field'] = field
00207         mytmp['spw'] = spw
00208         mytmp['antenna'] = antenna
00209         mytmp['timerange'] = timerange
00210         mytmp['avgchan'] = avgchan
00211         mytmp['writesyscal'] = writesyscal
00212         mytmp['multisource'] = multisource
00213         mytmp['combinespw'] = combinespw
00214         mytmp['writestation'] = writestation
00215         mytmp['padwithflags'] = padwithflags
00216         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00217         trec = casac.casac.utils().torecord(pathname+'exportuvfits.xml')
00218 
00219         casalog.origin('exportuvfits')
00220         try :
00221           #if not trec.has_key('exportuvfits') or not casac.casac.utils().verify(mytmp, trec['exportuvfits']) :
00222             #return False
00223 
00224           casac.casac.utils().verify(mytmp, trec['exportuvfits'], True)
00225           scriptstr=['']
00226           saveinputs = self.__globals__['saveinputs']
00227           saveinputs('exportuvfits', 'exportuvfits.last', myparams, self.__globals__,scriptstr=scriptstr)
00228           if async :
00229             count = 0
00230             keybase =  time.strftime("%y%m%d.%H%M%S")
00231             key = keybase + "_" + str(count)
00232             while self.__async__.has_key(key) :
00233                count += 1
00234                key = keybase + "_" + str(count)
00235             result = tm.execute('exportuvfits', vis, fitsfile, datacolumn, field, spw, antenna, timerange, avgchan, writesyscal, multisource, combinespw, writestation, padwithflags)
00236             print "Use: "
00237             print "      tm.retrieve(return_value) # to retrieve the status"
00238             print 
00239             self.rkey = key
00240             self.__async__[key] = result
00241           else :
00242               tname = 'exportuvfits'
00243               spaces = ' '*(18-len(tname))
00244               casalog.post('\n##########################################'+
00245                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00246               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00247               result = exportuvfits(vis, fitsfile, datacolumn, field, spw, antenna, timerange, avgchan, writesyscal, multisource, combinespw, writestation, padwithflags)
00248               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00249                            '\n##########################################')
00250 
00251         except Exception, instance:
00252           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00253              raise
00254           else :
00255              #print '**** Error **** ',instance
00256              tname = 'exportuvfits'
00257              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00258              pass
00259 
00260         gc.collect()
00261         return result
00262 #
00263 #
00264 #
00265     def paramgui(self, useGlobals=True, ipython_globals=None):
00266         """
00267         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00268         """
00269         import paramgui
00270         if not hasattr(self, "__globals__") or self.__globals__ == None :
00271            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00272 
00273         if useGlobals:
00274             if ipython_globals == None:
00275                 myf=self.__globals__
00276             else:
00277                 myf=ipython_globals
00278 
00279             paramgui.setGlobals(myf)
00280         else:
00281             paramgui.setGlobals({})
00282 
00283         paramgui.runTask('exportuvfits', myf['_ip'])
00284         paramgui.setGlobals({})
00285 
00286 #
00287 #
00288 #
00289     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00290         if not hasattr(self, "__globals__") or self.__globals__ == None :
00291            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00292         if ipython_globals == None:
00293             myf=self.__globals__
00294         else:
00295             myf=ipython_globals
00296 
00297         a = odict()
00298         a['vis']  = ''
00299         a['fitsfile']  = ''
00300         a['datacolumn']  = 'corrected'
00301         a['field']  = ''
00302         a['spw']  = ''
00303         a['antenna']  = ''
00304         a['timerange']  = ''
00305         a['avgchan']  = 1
00306         a['writesyscal']  = False
00307         a['multisource']  = True
00308         a['combinespw']  = True
00309         a['writestation']  = True
00310 
00311         a['async']=False
00312         a['combinespw'] = {
00313                     0:odict([{'value':True}, {'padwithflags':True}]), 
00314                     1:{'value':False}}
00315 
00316 ### This function sets the default values but also will return the list of
00317 ### parameters or the default value of a given parameter
00318         if(param == None):
00319                 myf['__set_default_parameters'](a)
00320         elif(param == 'paramkeys'):
00321                 return a.keys()
00322         else:
00323             if(paramvalue==None and subparam==None):
00324                if(a.has_key(param)):
00325                   return a[param]
00326                else:
00327                   return self.itsdefault(param)
00328             else:
00329                retval=a[param]
00330                if(type(a[param])==dict):
00331                   for k in range(len(a[param])):
00332                      valornotval='value'
00333                      if(a[param][k].has_key('notvalue')):
00334                         valornotval='notvalue'
00335                      if((a[param][k][valornotval])==paramvalue):
00336                         retval=a[param][k].copy()
00337                         retval.pop(valornotval)
00338                         if(subparam != None):
00339                            if(retval.has_key(subparam)):
00340                               retval=retval[subparam]
00341                            else:
00342                               retval=self.itsdefault(subparam)
00343                      else:
00344                         retval=self.itsdefault(subparam)
00345                return retval
00346 
00347 
00348 #
00349 #
00350     def check_params(self, param=None, value=None, ipython_globals=None):
00351       if ipython_globals == None:
00352           myf=self.__globals__
00353       else:
00354           myf=ipython_globals
00355 #      print 'param:', param, 'value:', value
00356       try :
00357          if str(type(value)) != "<type 'instance'>" :
00358             value0 = value
00359             value = myf['cu'].expandparam(param, value)
00360             matchtype = False
00361             if(type(value) == numpy.ndarray):
00362                if(type(value) == type(value0)):
00363                   myf[param] = value.tolist()
00364                else:
00365                   #print 'value:', value, 'value0:', value0
00366                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00367                   myf[param] = value0
00368                   if type(value0) != list :
00369                      matchtype = True
00370             else :
00371                myf[param] = value
00372             value = myf['cu'].verifyparam({param:value})
00373             if matchtype:
00374                value = False
00375       except Exception, instance:
00376          #ignore the exception and just return it unchecked
00377          myf[param] = value
00378       return value
00379 #
00380 #
00381     def description(self, key='exportuvfits', subkey=None):
00382         desc={'exportuvfits': 'Convert a CASA visibility data set to a UVFITS file:',
00383                'vis': 'Name of input visibility file',
00384                'fitsfile': 'Name of output UV FITS file',
00385                'datacolumn': 'Visibility file data column',
00386                'field': 'Select field using field id(s) or field name(s)',
00387                'spw': 'Select spectral window/channels',
00388                'antenna': 'Select data based on antenna/baseline',
00389                'timerange': 'Select data based on time range',
00390                'avgchan': 'Channel averaging width (value > 1 indicates averaging)',
00391                'writesyscal': 'Write GC and TY tables, (Not yet available)',
00392                'multisource': 'Write in multi-source format',
00393                'combinespw': 'Export the spectral windows as IFs',
00394                'writestation': 'Write station name instead of antenna name',
00395                'padwithflags': 'Fill in missing data with flags to fit IFs',
00396 
00397                'async': 'If true the taskname must be started using exportuvfits(...)'
00398               }
00399 
00400 #
00401 # Set subfields defaults if needed
00402 #
00403 
00404         if(desc.has_key(key)) :
00405            return desc[key]
00406 
00407     def itsdefault(self, paramname) :
00408         a = {}
00409         a['vis']  = ''
00410         a['fitsfile']  = ''
00411         a['datacolumn']  = 'corrected'
00412         a['field']  = ''
00413         a['spw']  = ''
00414         a['antenna']  = ''
00415         a['timerange']  = ''
00416         a['avgchan']  = 1
00417         a['writesyscal']  = False
00418         a['multisource']  = True
00419         a['combinespw']  = True
00420         a['writestation']  = True
00421         a['padwithflags']  = False
00422 
00423         #a = sys._getframe(len(inspect.stack())-1).f_globals
00424 
00425         if self.parameters['combinespw']  == True:
00426             a['padwithflags'] = True
00427 
00428         if a.has_key(paramname) :
00429               return a[paramname]
00430 exportuvfits_cli = exportuvfits_cli_()