casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
cvel_pg.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 string
00010 import time
00011 import inspect
00012 import gc
00013 import numpy
00014 from odict import odict
00015 from task_cvel import cvel
00016 from task_cvel import casalog
00017 
00018 class cvel_pg_:
00019     __name__ = "cvel"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (cvel_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, vis=None, outputvis=None, passall=None, field=None, spw=None, selectdata=None, antenna=None, timerange=None, scan=None, array=None, mode=None, nchan=None, start=None, width=None, interpolation=None, phasecenter=None, restfreq=None, outframe=None, veltype=None, hanning=None, async=None):
00027 
00028         """regrid an MS to a new spectral window / channel structure or frame
00029 
00030        vis -- Name of input visibility file
00031                default: none; example: vis='ngc5921.ms'    
00032 
00033        outputvis -- Name of output measurement set (required)
00034                default: none; example: vis='ngc5921-regridded.ms'    
00035                
00036        passall --  if False, data not meeting the selection is omitted/deleted 
00037                or flagged (if in-row); if True, data not meeting the selection 
00038                on field and spw is passed through without modification
00039                default: False; example: 
00040                field='NGC5921'
00041                passall=False : only data from NGC5921 is included in output MS, 
00042                          no data from other fields (e.g. 1331+305) is included
00043                passall=True : data from NGC5921 is transformed by cvel, all other 
00044                          fields are passed through unchanged 
00045 
00046        field -- Select fields in mosaic.  Use field id(s) or field name(s).
00047                   ['go listobs' to obtain the list id's or names]
00048               default: ''= all fields
00049               If field string is a non-negative integer, it is assumed to
00050                   be a field index otherwise, it is assumed to be a 
00051                   field name
00052               field='0~2'; field ids 0,1,2
00053               field='0,4,5~7'; field ids 0,4,5,6,7
00054               field='3C286,3C295'; field named 3C286 and 3C295
00055               field = '3,4C*'; field id 3, all names starting with 4C
00056 
00057        spw --Select spectral window/channels
00058               NOTE: This selects the data passed as the INPUT to mode
00059               default: ''=all spectral windows and channels
00060                 spw='0~2,4'; spectral windows 0,1,2,4 (all channels)
00061                 spw='0:5~61'; spw 0, channels 5 to 61
00062                 spw='<2';   spectral windows less than 2 (i.e. 0,1)
00063                 spw='0,10,3:3~45'; spw 0,10 all channels, spw 3, 
00064                                    channels 3 to 45.
00065                 spw='0~2:2~6'; spw 0,1,2 with channels 2 through 6 in each.
00066                 spw='0:0~10;15~60'; spectral window 0 with channels 
00067                                     0-10,15-60
00068                 spw='0:0~10,1:20~30,2:1;2;3'; spw 0, channels 0-10,
00069                       spw 1, channels 20-30, and spw 2, channels, 1,2 and 3
00070 
00071        selectdata -- Other data selection parameters
00072               default: True
00073 
00074   >>> selectdata=True expandable parameters
00075 
00076               antenna -- Select data based on antenna/baseline
00077                   default: '' (all)
00078                   If antenna string is a non-negative integer, it is 
00079                     assumed to be an antenna index, otherwise, it is
00080                     considered an antenna name.
00081                   antenna='5&6'; baseline between antenna index 5 and 
00082                                  index 6.
00083                   antenna='VA05&VA06'; baseline between VLA antenna 5 
00084                                        and 6.
00085                   antenna='5&6;7&8'; baselines 5-6 and 7-8
00086                   antenna='5'; all baselines with antenna index 5
00087                   antenna='05'; all baselines with antenna number 05 
00088                                 (VLA old name)
00089                   antenna='5,6,9'; all baselines with antennas 5,6,9 
00090                                    index numbers
00091 
00092               timerange  -- Select data based on time range:
00093                  default = '' (all); examples,
00094                   timerange = 'YYYY/MM/DD/hh:mm:ss~YYYY/MM/DD/hh:mm:ss'
00095                   Note: if YYYY/MM/DD is missing date defaults to first 
00096                         day in data set
00097                   timerange='09:14:0~09:54:0' picks 40 min on first day
00098                   timerange= '25:00:00~27:30:00' picks 1 hr to 3 hr 
00099                              30min on NEXT day
00100                   timerange='09:44:00' pick data within one integration 
00101                              of time
00102                   timerange='>10:24:00' data after this time
00103 
00104               scan -- Scan number range.
00105                   default: '' (all)
00106                   example: scan='1~5'
00107                   Check 'go listobs' to insure the scan numbers are in 
00108                         order.
00109 
00110               array -- Select data by (sub)array indices
00111                   default: '' (all); example:
00112                   array='0~2'; arrays 0 to 2 
00113 
00114       mode -- Frequency Specification:
00115                NOTE: See examples below:
00116                default: 'channel'
00117                  mode = 'channel'; Use with nchan, start, width to specify
00118                          output spw. Produces equidistant grid based on first
00119                          selected channel. See examples below.
00120                  mode = 'velocity', means channels are specified in 
00121                       velocity.
00122                  mode = 'frequency', means channels are specified in 
00123                       frequency.
00124                  mode = 'channel_b', alternative 'channel' mode.
00125                          Does not force an equidistant grid. Faster.
00126 
00127   >>> mode expandable parameters 
00128                Start, width are given in units of channels, frequency 
00129                   or velocity as indicated by mode 
00130                nchan -- Number of channels in output spw
00131                  default: -1 = all channels; example: nchan=3
00132                start -- Start or end input channel (zero-based) depending on the sign of the width parameter
00133                  default=0; example: start=5
00134                width -- Output channel width in units of the input
00135                      channel width (sign indicates whether the start parameter is lower(+) or upper(-) end of the range)
00136                  default=1; example: width=4
00137                interpolation -- Interpolation method (linear, nearest, cubic, spline, fftshift)
00138                  default = 'linear'
00139            examples:
00140                spw = '0,1'; mode = 'channel'
00141                   will produce a single spw containing all channels in spw 
00142                        0 and 1
00143                spw='0:5~28^2'; mode = 'channel'
00144                   will produce a single spw made with channels 
00145                        (5,7,9,...,25,27)
00146                spw = '0'; mode = 'channel': nchan=3; start=5; width=4
00147                   will produce an spw with 3 output channels
00148                   new channel 1 contains data from channels (5+6+7+8)
00149                   new channel 2 contains data from channels (9+10+11+12)
00150                   new channel 3 contains data from channels (13+14+15+16)
00151                spw = '0:0~63^3'; mode='channel'; nchan=21; start = 0; 
00152                    width = 1
00153                   will produce an spw with 21 channels
00154                   new channel 1 contains data from channel 0
00155                   new channel 2 contains data from channel 2
00156                   new channel 21 contains data from channel 61
00157                spw = '0:0~40^2'; mode = 'channel'; nchan = 3; start = 
00158                    5; width = 4
00159                   will produce an spw with three output channels
00160                   new channel 1 contains channels (5,7)
00161                   new channel 2 contains channels (13,15)
00162                   new channel 3 contains channels (21,23)
00163 
00164       phasecenter -- direction measure  or fieldid for the mosaic center
00165                default: '' => first field selected ; example: phasecenter=6
00166                or phasecenter='J2000 19h30m00 -40d00m00'
00167 
00168       restfreq -- Specify rest frequency to use for output image
00169                default='' Occasionally it is necessary to set this (for
00170                example some VLA spectral line data).  For example for
00171                NH_3 (1,1) put restfreq='23.694496GHz'
00172 
00173       outframe -- output reference frame
00174                default='' (keep original reference frame) ; example: outframe='bary'     
00175 
00176       veltype -- definition of velocity (in mode)
00177                default = 'radio'
00178 
00179       hanning -- if true, Hanning smooth frequency channel data to remove Gibbs ringing
00180 
00181 ==================================================================
00182 
00183 The intent of cvel is to transform channel labels and the 
00184 visibilities to a spectral reference frame which is appropriate
00185 for the science analysis, e.g. from TOPO to LSRK to correct for 
00186 Doppler shifts throughout the time of the observation. Naturally, 
00187 this will change the shape of the spectral feature to some extent. 
00188 According to the Nyquist theorem you should oversample a spectrum 
00189 with twice the numbers of channels to retain the shape. Based on 
00190 some tests, however, we recommend to observe with at least 
00191 3-4 times the number of channels for each significant spectral 
00192 feature (like 3-4 times the linewidth). This will minimize 
00193 regridding artifacts in cvel.
00194 
00195 If cvel has already established the grid that is desired for the
00196 imaging, clean should be run with exactly the same frequency/velocity 
00197 parameters as used in cvel in order to avoid additional regridding in 
00198 clean.
00199 
00200 Hanning smoothing is optionally offered in cvel, but tests have 
00201 shown that already the regridding process itself, if it involved 
00202 a transformation from TOPO to a non-terrestrial reference frame, 
00203 implies some smoothing (due to channel interpolation) such that 
00204 Hanning smoothing may not be necessary.
00205 
00206         """
00207         a=inspect.stack()
00208         stacklevel=0
00209         for k in range(len(a)):
00210           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00211                 stacklevel=k
00212                 break
00213         myf=sys._getframe(stacklevel).f_globals
00214         myf['__last_task'] = 'cvel'
00215         myf['taskname'] = 'cvel'
00216         ###
00217         myf['update_params'](func=myf['taskname'],printtext=False)
00218         ###
00219         ###
00220         #Handle globals or user over-ride of arguments
00221         #
00222         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00223         useLocalDefaults = False
00224 
00225         for item in function_signature_defaults.iteritems():
00226                 key,val = item
00227                 keyVal = eval(key)
00228                 if (keyVal == None):
00229                         #user hasn't set it - use global/default
00230                         pass
00231                 else:
00232                         #user has set it - use over-ride
00233                         if (key != 'self') :
00234                            useLocalDefaults = True
00235                         #myf[key]=keyVal
00236 
00237         myparams = {}
00238         if useLocalDefaults :
00239            for item in function_signature_defaults.iteritems():
00240                key,val = item
00241                keyVal = eval(key)
00242                exec('myparams[key] = keyVal')
00243                if (keyVal == None):
00244                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00245                    keyVal = eval(key)
00246                    if(type(keyVal) == dict) :
00247                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00248 
00249         else :
00250             uselessvariable = None 
00251             myparams['vis'] = vis = myf['vis']
00252             myparams['outputvis'] = outputvis = myf['outputvis']
00253             myparams['passall'] = passall = myf['passall']
00254             myparams['field'] = field = myf['field']
00255             myparams['spw'] = spw = myf['spw']
00256             myparams['selectdata'] = selectdata = myf['selectdata']
00257             myparams['antenna'] = antenna = myf['antenna']
00258             myparams['timerange'] = timerange = myf['timerange']
00259             myparams['scan'] = scan = myf['scan']
00260             myparams['array'] = array = myf['array']
00261             myparams['mode'] = mode = myf['mode']
00262             myparams['nchan'] = nchan = myf['nchan']
00263             myparams['start'] = start = myf['start']
00264             myparams['width'] = width = myf['width']
00265             myparams['interpolation'] = interpolation = myf['interpolation']
00266             myparams['phasecenter'] = phasecenter = myf['phasecenter']
00267             myparams['restfreq'] = restfreq = myf['restfreq']
00268             myparams['outframe'] = outframe = myf['outframe']
00269             myparams['veltype'] = veltype = myf['veltype']
00270             myparams['hanning'] = hanning = myf['hanning']
00271 
00272 
00273         result = None
00274 
00275 #
00276 #    The following is work around to avoid a bug with current python translation
00277 #
00278         mytmp = {}
00279 
00280         mytmp['vis'] = vis
00281         mytmp['outputvis'] = outputvis
00282         mytmp['passall'] = passall
00283         mytmp['field'] = field
00284         mytmp['spw'] = spw
00285         mytmp['selectdata'] = selectdata
00286         mytmp['antenna'] = antenna
00287         mytmp['timerange'] = timerange
00288         mytmp['scan'] = scan
00289         mytmp['array'] = array
00290         mytmp['mode'] = mode
00291         mytmp['nchan'] = nchan
00292         mytmp['start'] = start
00293         mytmp['width'] = width
00294         mytmp['interpolation'] = interpolation
00295         mytmp['phasecenter'] = phasecenter
00296         mytmp['restfreq'] = restfreq
00297         mytmp['outframe'] = outframe
00298         mytmp['veltype'] = veltype
00299         mytmp['hanning'] = hanning
00300         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00301         trec = casac.utils().torecord(pathname+'cvel.xml')
00302 
00303         casalog.origin('cvel')
00304         if not trec.has_key('cvel') or not casac.utils().verify(mytmp, trec['cvel']) :
00305             return False
00306 
00307 
00308         try :
00309           casalog.post('')
00310           casalog.post('##########################################')
00311           casalog.post('##### Begin Task: cvel           #####')
00312           casalog.post('')
00313           result = cvel(vis, outputvis, passall, field, spw, selectdata, antenna, timerange, scan, array, mode, nchan, start, width, interpolation, phasecenter, restfreq, outframe, veltype, hanning)
00314           casalog.post('')
00315           casalog.post('##### End Task: cvel           #####')
00316           casalog.post('##########################################')
00317 
00318 
00319 # saveinputs for individule engine has no use
00320 # saveinputs should alos be removed from casa_in_py.py
00321 #
00322 #
00323 #          saveinputs = myf['saveinputs']
00324 #          saveinputs('cvel', 'cvel.last', myparams)
00325 #
00326 #
00327         except Exception, instance:
00328           #print '**** Error **** ',instance
00329           pass
00330 
00331         gc.collect()
00332         return result
00333 #
00334 #
00335 ##
00336 #    def paramgui(self, useGlobals=True):
00337 #        """
00338 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00339 #        """
00340 #        import paramgui
00341 #
00342 #        a=inspect.stack()
00343 #        stacklevel=0
00344 #        for k in range(len(a)):
00345 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00346 #            stacklevel=k
00347 #            break
00348 #        myf = sys._getframe(stacklevel).f_globals
00349 #
00350 #        if useGlobals:
00351 #            paramgui.setGlobals(myf)
00352 #        else:
00353 #            paramgui.setGlobals({})
00354 #
00355 #        paramgui.runTask('cvel', myf['_ip'])
00356 #        paramgui.setGlobals({})
00357 #
00358 #
00359 #
00360 #
00361     def defaults(self, param=None):
00362         a=inspect.stack()
00363         stacklevel=0
00364         for k in range(len(a)):
00365           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00366                 stacklevel=k
00367                 break
00368         myf=sys._getframe(stacklevel).f_globals
00369         a = odict()
00370         a['vis']  = ''
00371         a['outputvis']  = ''
00372         a['passall']  = False
00373         a['field']  = ''
00374         a['spw']  = ''
00375         a['selectdata']  = True
00376         a['mode']  = 'channel'
00377         a['phasecenter']  = ''
00378         a['restfreq']  = ''
00379         a['outframe']  = ''
00380         a['veltype']  = 'radio'
00381         a['hanning']  = False
00382 
00383         a['async']=False
00384         a['selectdata'] = {
00385                     0:odict([{'value':True}, {'timerange':''}, {'array':''}, {'antenna':''}, {'scan':''}]), 
00386                     1:{'value':False}}
00387         a['mode'] = {
00388                     0:odict([{'value':'channel'}, {'nchan':-1}, {'start':0}, {'width':1}, {'interpolation':'linear'}]), 
00389                     1:odict([{'value':'channel_b'}, {'nchan':-1}, {'start':0}, {'width':1}, {'interpolation':'linear'}]), 
00390                     2:odict([{'value':'velocity'}, {'nchan':-1}, {'start':''}, {'width':''}, {'interpolation':'linear'}]), 
00391                     3:odict([{'value':'frequency'}, {'nchan':-1}, {'start':''}, {'width':''}, {'interpolation':'linear'}])}
00392 
00393 ### This function sets the default values but also will return the list of
00394 ### parameters or the default value of a given parameter
00395         if(param == None):
00396                 myf['__set_default_parameters'](a)
00397         elif(param == 'paramkeys'):
00398                 return a.keys()
00399         else:
00400                 if(a.has_key(param)):
00401                    #if(type(a[param]) == dict) :
00402                    #   return a[param][len(a[param])-1]['value']
00403                    #else :
00404                       return a[param]
00405 
00406 
00407 #
00408 #
00409     def check_params(self, param=None, value=None):
00410       a=inspect.stack() 
00411       stacklevel=0
00412       for k in range(len(a)):
00413         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00414             stacklevel=k
00415             break
00416       myf=sys._getframe(stacklevel).f_globals
00417 
00418 #      print 'param:', param, 'value:', value
00419       try :
00420          if str(type(value)) != "<type 'instance'>" :
00421             value0 = value
00422             value = myf['cu'].expandparam(param, value)
00423             matchtype = False
00424             if(type(value) == numpy.ndarray):
00425                if(type(value) == type(value0)):
00426                   myf[param] = value.tolist()
00427                else:
00428                   #print 'value:', value, 'value0:', value0
00429                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00430                   myf[param] = value0
00431                   if type(value0) != list :
00432                      matchtype = True
00433             else :
00434                myf[param] = value
00435             value = myf['cu'].verifyparam({param:value})
00436             if matchtype:
00437                value = False
00438       except Exception, instance:
00439          #ignore the exception and just return it unchecked
00440          myf[param] = value
00441       return value
00442 
00443 #
00444 #
00445     def description(self, key='cvel', subkey=None):
00446         desc={'cvel': 'regrid an MS to a new spectral window / channel structure or frame',
00447                'vis': 'Name of input measurement set',
00448                'outputvis': 'Name of output measurement set',
00449                'passall': 'Pass through (write to output MS) non-selected data with no change',
00450                'field': 'Select field using field id(s) or field name(s)',
00451                'spw': 'Select spectral window/channels',
00452                'selectdata': 'Other data selection parameters',
00453                'antenna': 'Select data based on antenna/baseline',
00454                'timerange': 'Range of time to select from data',
00455                'scan': 'scan number range',
00456                'array': '(sub)array indices',
00457                'mode': ' Regridding mode ',
00458                'nchan': 'Number of channels in output spw (-1=all)',
00459                'start': 'First channel in input to use',
00460                'width': 'Number of input channels to average',
00461                'interpolation': 'Spectral interpolation method',
00462                'phasecenter': 'Image phase center: position or field index',
00463                'restfreq': 'rest frequency (see help)',
00464                'outframe': 'Output frame (\'\'=keep input frame)',
00465                'veltype': 'velocity definition',
00466                'hanning': ' If true, Hanning smooth data before regridding to remove Gibbs ringing.',
00467 
00468                'async': 'If true the taskname must be started using cvel(...)'
00469               }
00470 
00471 #
00472 # Set subfields defaults if needed
00473 #
00474         if(subkey == 'channel'):
00475           desc['start'] = 'first input channel to use'
00476         if(subkey == 'channel_b'):
00477           desc['start'] = 'first input channel to use'
00478         if(subkey == 'velocity'):
00479           desc['start'] = 'Velocity of first image channel: e.g \'0.0km/s\''
00480         if(subkey == 'velocity'):
00481           desc['width'] = 'image channel width in velocity units: e.g \'-1.0km/s\''
00482         if(subkey == 'frequency'):
00483           desc['start'] = 'Frequency of first image channel: e.q. \'1.4GHz\''
00484         if(subkey == 'frequency'):
00485           desc['width'] = 'Image channel width in frequency units: e.g \'1.0kHz\''
00486 
00487         if(desc.has_key(key)) :
00488            return desc[key]
00489 
00490     def itsdefault(self, paramname) :
00491         a = {}
00492         a['vis']  = ''
00493         a['outputvis']  = ''
00494         a['passall']  = False
00495         a['field']  = ''
00496         a['spw']  = ''
00497         a['selectdata']  = True
00498         a['antenna']  = ''
00499         a['timerange']  = ''
00500         a['scan']  = ''
00501         a['array']  = ''
00502         a['mode']  = 'channel'
00503         a['nchan']  = -1
00504         a['start']  = 0
00505         a['width']  = 1
00506         a['interpolation']  = 'linear'
00507         a['phasecenter']  = ''
00508         a['restfreq']  = ''
00509         a['outframe']  = ''
00510         a['veltype']  = 'radio'
00511         a['hanning']  = False
00512 
00513         if a.has_key(paramname) :
00514               return a[paramname]
00515 cvel_pg = cvel_pg_()