casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
sdgrid_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_sdgrid import sdgrid
00018 class sdgrid_cli_:
00019     __name__ = "sdgrid"
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__ = (sdgrid_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'infiles':None, 'antenna':None, 'scanlist':None, 'ifno':None, 'pollist':None, 'gridfunction':None, 'convsupport':None, 'truncate':None, 'gwidth':None, 'jwidth':None, 'weight':None, 'clipminmax':None, 'outfile':None, 'overwrite':None, 'npix':None, 'cell':None, 'center':None, 'plot':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, infiles=None, antenna=None, scanlist=None, ifno=None, pollist=None, gridfunction=None, convsupport=None, truncate=None, gwidth=None, jwidth=None, weight=None, clipminmax=None, outfile=None, overwrite=None, npix=None, cell=None, center=None, plot=None,  async=None):
00047 
00048         """SD task: gridding single dish data
00049   Keyword arguments:
00050         infiles -- name of input SD dataset. can be list.
00051                 example: 'testimage.asap' 
00052                          ['testimage1.asap','testimage2.asap']
00053         antenna -- select data based on antenna name(s) or id(s)
00054                 default: -1
00055                 example: 0, 'DV01'
00056         scanlist -- list of scan numbers to process
00057                 default: [] (use all scans)
00058                 example: [21,22,23,24]
00059         ifno -- IFNO to be gridded
00060                 default: -1 (only process IFNO in the first row)
00061                 example: 1
00062         pollist -- POLNO to be gridded
00063                 default: [] (all polarizations)
00064                 example: 1,[0,1]
00065         gridfunction -- gridding function 
00066                 options: 'BOX' (Box-car), 'SF' (Spheroidal), 
00067                          'GAUSS' (Gaussian), 'PB' (Primary-beam)
00068                          'GJINC' (Gaussian*Jinc)
00069                 default: 'BOX'
00070                 example: 'SF'
00071             >>> gridfunction expandable parameter:
00072                convsupport -- convolution support for 'SF' 
00073                    default: -1 (use default for each gridfunction)
00074                    example: 3
00075                truncate -- truncattion radius of convolution kernel.
00076                            effective only for 'GAUSS' and 'GJINC'.
00077                    default: '-1' (use default for each gridfunction)
00078                    example: 3, '20arcsec', '3pixel'
00079                gwidth -- HWHM for gaussian. Effective only for 
00080                          'GAUSS' and 'GJINC'.
00081                    default: '-1' (use default for each gridfunction)
00082                    example: 3, '20arcsec', '3pixel'
00083                jwidth -- Width of jinc function. Effective only for 
00084                          'GJINC'.
00085                    default: '-1' (use default for each gridfunction)
00086                    example: 3, '20arcsec', '3pixel'
00087         weight -- weight type (both lower-case and upper-case are 
00088                   acceptable)
00089                 options: 'UNIFORM',
00090                          'TSYS'  (1/Tsys**2 weighted)
00091                          'TINT'  (integration time weighted)
00092                          'TINTSYS'  (Tint/Tsys**2)
00093                 default: 'UNIFORM'
00094         clipminmax -- do min/max cliping if True
00095                 default: False
00096         outfile -- output data name
00097                 default: '' (outfile will be set to infile+'.grid')
00098                 example: 'mydata.asap.grid'
00099         overwrite -- overwrite option for outfile
00100                 default: False (not overwrite)
00101                 options: True, False
00102                 example: if True, existing file will be overwritten
00103         npix -- x and y image size in pixels, symmetric for single value
00104                 default: -1 (automatically calculated from cell size and 
00105                              the data)
00106                 example: npix=200 (equivalent to [200,200])
00107         cell -- x and y cell size. default unit arcsec
00108                 default: '' (automatically calculated from npix if it is 
00109                              set, otherwise '1.0arcmin')
00110                 example: cell=['0.2arcmin, 0.2arcmin']
00111                          cell='0.2arcmin' (equivalent to example above)
00112                          cell=12.0 (interpreted as '12.0arcsec'='0.2arcmin')
00113         center -- grid center
00114                 default: '' (automatically calculated from the data)
00115                 example: 'J2000 13h44m00 -17d02m00'
00116                          ['05:34:48.2', '-05.22.17.7'] (in J2000 frame)
00117                          [1.46, -0.09] (interpreted as radian in J2000 frame)
00118         plot -- Plot result or not
00119                 default: False (not plot)
00120                 example: if True, result will be plotted
00121 
00122         DESCRIPTION:
00123 
00124         The sdgrid task performs spatial gridding according to the user 
00125         specification of spatial grid, convolution function, etc.
00126 
00127         For grid configuration, the task supplements necessary information 
00128         by referring input data if any of gridding parameter ('npix', 
00129         'cell', or 'center') is not specified by the user. If 'center' is 
00130         default value (empty string), central position of the grid will be 
00131         set to the center of observed area, i.e. x=0.5*(xmax+xmin), 
00132         y=0.5*(ymax+ymin). If either 'cell' or 'npix' is set, unspecified 
00133         one will be calculated from the others. In that case, total extent of 
00134         the grid will be set to cover all observed position. If neither 'cell' 
00135         nor 'npix' is set, cell size will be set to 1.0 arcmin and number of 
00136         pixel will be calculated based on that cell size.
00137  
00138         Currently, only J2000 frame is supported.
00139  
00140         The parameter gridfunction sets gridding function for imaging. 
00141         Currently, the task supports 'BOX' (Box-car), 'SF' (Prolate 
00142         Spheroidal Wave Function), 'GAUSS' (Gaussian), 'GJINC' (Gaussian*
00143         Jinc), where Jinc(x) = J_1(pi*x/c)/(pi*x/c) with a first order 
00144         Bessel function J_1, and 'PB' (Primary Beam, not implemented yet). 
00145         For 'PB', correct antenna informations should be included in input 
00146         file. 
00147         
00148         There are four subparameters for gridfunction: convsupport, truncate, 
00149         gwidth, and jwidth. The convsupport is an integer specifying cut-off 
00150         radius for 'SF' in units of pixel. By default (convsupport=-1), 
00151         the cut-off radius is set to 3 pixels. The truncate is a cut-off 
00152         radius for 'GAUSS' or 'GJINC'. It accepts integer, float, and 
00153         string values of numeric plus unit. Allowed units are angular 
00154         units such as 'deg', 'arcmin', 'arcsec', and 'pixel'. Default unit 
00155         is 'pixel' so that string without unit or numerical values (integer 
00156         or float) will be interpreted as radius in pixel. Default value 
00157         for truncate, which is used when negative radius is set, is 3*HWHM 
00158         for 'GAUSS' and radius at first null for 'GJINC'. The gwidth is 
00159         the HWHM of gaussian for 'GAUSS' and 'GJINC'. Default value is 
00160         sqrt(log(2)) pixel for 'GAUSS' and 2.52*sqrt(log(2)) pixel for 
00161         'GJINC'. The jwidth specifies width of the jinc function (parameter 
00162         'c' in the definition above). Default is 1.55 pixel. Both gwidth 
00163         jwidth allows integer, float, or string of numeric plus unit. 
00164         Default values for gwidth and jwidth are taken from Mangum et al. 
00165         (2007).
00166 
00167         Boolean parameter 'plot' controls whether gridded result is plotted 
00168         or not. If True, color map of gridded data will be shown. Pixel 
00169         center and observed position are overlayed as blue dot and red dot, 
00170         respectively. Currently, channel averaged value will be plotted.
00171   
00172         """
00173         if not hasattr(self, "__globals__") or self.__globals__ == None :
00174            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00175         #casac = self.__globals__['casac']
00176         casalog = self.__globals__['casalog']
00177         #casalog = casac.casac.logsink()
00178         self.__globals__['__last_task'] = 'sdgrid'
00179         self.__globals__['taskname'] = 'sdgrid'
00180         ###
00181         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00182         ###
00183         ###
00184         #Handle globals or user over-ride of arguments
00185         #
00186         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00187         useLocalDefaults = False
00188 
00189         for item in function_signature_defaults.iteritems():
00190                 key,val = item
00191                 keyVal = eval(key)
00192                 if (keyVal == None):
00193                         #user hasn't set it - use global/default
00194                         pass
00195                 else:
00196                         #user has set it - use over-ride
00197                         if (key != 'self') :
00198                            useLocalDefaults = True
00199 
00200         myparams = {}
00201         if useLocalDefaults :
00202            for item in function_signature_defaults.iteritems():
00203                key,val = item
00204                keyVal = eval(key)
00205                exec('myparams[key] = keyVal')
00206                self.parameters[key] = keyVal
00207                if (keyVal == None):
00208                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00209                    keyVal = eval(key)
00210                    if(type(keyVal) == dict) :
00211                       if len(keyVal) > 0 :
00212                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00213                       else :
00214                          exec('myparams[key] = ' + key + ' = {}')
00215 
00216         else :
00217             async = self.parameters['async']
00218             myparams['infiles'] = infiles = self.parameters['infiles']
00219             myparams['antenna'] = antenna = self.parameters['antenna']
00220             myparams['scanlist'] = scanlist = self.parameters['scanlist']
00221             myparams['ifno'] = ifno = self.parameters['ifno']
00222             myparams['pollist'] = pollist = self.parameters['pollist']
00223             myparams['gridfunction'] = gridfunction = self.parameters['gridfunction']
00224             myparams['convsupport'] = convsupport = self.parameters['convsupport']
00225             myparams['truncate'] = truncate = self.parameters['truncate']
00226             myparams['gwidth'] = gwidth = self.parameters['gwidth']
00227             myparams['jwidth'] = jwidth = self.parameters['jwidth']
00228             myparams['weight'] = weight = self.parameters['weight']
00229             myparams['clipminmax'] = clipminmax = self.parameters['clipminmax']
00230             myparams['outfile'] = outfile = self.parameters['outfile']
00231             myparams['overwrite'] = overwrite = self.parameters['overwrite']
00232             myparams['npix'] = npix = self.parameters['npix']
00233             myparams['cell'] = cell = self.parameters['cell']
00234             myparams['center'] = center = self.parameters['center']
00235             myparams['plot'] = plot = self.parameters['plot']
00236 
00237         if type(scanlist)==int: scanlist=[scanlist]
00238 
00239         result = None
00240 
00241 #
00242 #    The following is work around to avoid a bug with current python translation
00243 #
00244         mytmp = {}
00245 
00246         mytmp['infiles'] = infiles
00247         mytmp['antenna'] = antenna
00248         mytmp['scanlist'] = scanlist
00249         mytmp['ifno'] = ifno
00250         mytmp['pollist'] = pollist
00251         mytmp['gridfunction'] = gridfunction
00252         mytmp['convsupport'] = convsupport
00253         mytmp['truncate'] = truncate
00254         mytmp['gwidth'] = gwidth
00255         mytmp['jwidth'] = jwidth
00256         mytmp['weight'] = weight
00257         mytmp['clipminmax'] = clipminmax
00258         mytmp['outfile'] = outfile
00259         mytmp['overwrite'] = overwrite
00260         mytmp['npix'] = npix
00261         mytmp['cell'] = cell
00262         mytmp['center'] = center
00263         mytmp['plot'] = plot
00264         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00265         trec = casac.casac.utils().torecord(pathname+'sdgrid.xml')
00266 
00267         casalog.origin('sdgrid')
00268         try :
00269           #if not trec.has_key('sdgrid') or not casac.casac.utils().verify(mytmp, trec['sdgrid']) :
00270             #return False
00271 
00272           casac.casac.utils().verify(mytmp, trec['sdgrid'], True)
00273           scriptstr=['']
00274           saveinputs = self.__globals__['saveinputs']
00275           saveinputs('sdgrid', 'sdgrid.last', myparams, self.__globals__,scriptstr=scriptstr)
00276           if async :
00277             count = 0
00278             keybase =  time.strftime("%y%m%d.%H%M%S")
00279             key = keybase + "_" + str(count)
00280             while self.__async__.has_key(key) :
00281                count += 1
00282                key = keybase + "_" + str(count)
00283             result = tm.execute('sdgrid', infiles, antenna, scanlist, ifno, pollist, gridfunction, convsupport, truncate, gwidth, jwidth, weight, clipminmax, outfile, overwrite, npix, cell, center, plot)
00284             print "Use: "
00285             print "      tm.retrieve(return_value) # to retrieve the status"
00286             print 
00287             self.rkey = key
00288             self.__async__[key] = result
00289           else :
00290               tname = 'sdgrid'
00291               spaces = ' '*(18-len(tname))
00292               casalog.post('\n##########################################'+
00293                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00294               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00295               result = sdgrid(infiles, antenna, scanlist, ifno, pollist, gridfunction, convsupport, truncate, gwidth, jwidth, weight, clipminmax, outfile, overwrite, npix, cell, center, plot)
00296               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00297                            '\n##########################################')
00298 
00299         except Exception, instance:
00300           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00301              raise
00302           else :
00303              #print '**** Error **** ',instance
00304              tname = 'sdgrid'
00305              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00306              pass
00307 
00308         gc.collect()
00309         return result
00310 #
00311 #
00312 #
00313     def paramgui(self, useGlobals=True, ipython_globals=None):
00314         """
00315         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00316         """
00317         import paramgui
00318         if not hasattr(self, "__globals__") or self.__globals__ == None :
00319            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00320 
00321         if useGlobals:
00322             if ipython_globals == None:
00323                 myf=self.__globals__
00324             else:
00325                 myf=ipython_globals
00326 
00327             paramgui.setGlobals(myf)
00328         else:
00329             paramgui.setGlobals({})
00330 
00331         paramgui.runTask('sdgrid', myf['_ip'])
00332         paramgui.setGlobals({})
00333 
00334 #
00335 #
00336 #
00337     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00338         if not hasattr(self, "__globals__") or self.__globals__ == None :
00339            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00340         if ipython_globals == None:
00341             myf=self.__globals__
00342         else:
00343             myf=ipython_globals
00344 
00345         a = odict()
00346         a['infiles']  = [""]
00347         a['antenna']  = -1
00348         a['scanlist']  = []
00349         a['ifno']  = -1
00350         a['pollist']  = []
00351         a['gridfunction']  = 'BOX'
00352         a['weight']  = 'UNIFORM'
00353         a['clipminmax']  = False
00354         a['outfile']  = ''
00355         a['overwrite']  = False
00356         a['npix']  = -1
00357         a['cell']  = ''
00358         a['center']  = ''
00359         a['plot']  = False
00360 
00361         a['async']=False
00362         a['gridfunction'] = {
00363                     0:{'value':'BOX'}, 
00364                     1:{'value':'box'}, 
00365                     2:odict([{'value':'SF'}, {'convsupport':-1}]), 
00366                     3:odict([{'value':'sf'}, {'convsupport':-1}]), 
00367                     4:odict([{'value':'GAUSS'}, {'truncate':-1}, {'gwidth':-1}]), 
00368                     5:odict([{'value':'gauss'}, {'truncate':-1}, {'gwidth':-1}]), 
00369                     6:odict([{'value':'GJINC'}, {'truncate':-1}, {'gwidth':-1}, {'jwidth':-1}]), 
00370                     7:odict([{'value':'gjinc'}, {'truncate':-1}, {'gwidth':-1}, {'jwidth':-1}]), 
00371                     8:{'value':'PB'}, 
00372                     9:{'value':'pb'}}
00373 
00374 ### This function sets the default values but also will return the list of
00375 ### parameters or the default value of a given parameter
00376         if(param == None):
00377                 myf['__set_default_parameters'](a)
00378         elif(param == 'paramkeys'):
00379                 return a.keys()
00380         else:
00381             if(paramvalue==None and subparam==None):
00382                if(a.has_key(param)):
00383                   return a[param]
00384                else:
00385                   return self.itsdefault(param)
00386             else:
00387                retval=a[param]
00388                if(type(a[param])==dict):
00389                   for k in range(len(a[param])):
00390                      valornotval='value'
00391                      if(a[param][k].has_key('notvalue')):
00392                         valornotval='notvalue'
00393                      if((a[param][k][valornotval])==paramvalue):
00394                         retval=a[param][k].copy()
00395                         retval.pop(valornotval)
00396                         if(subparam != None):
00397                            if(retval.has_key(subparam)):
00398                               retval=retval[subparam]
00399                            else:
00400                               retval=self.itsdefault(subparam)
00401                      else:
00402                         retval=self.itsdefault(subparam)
00403                return retval
00404 
00405 
00406 #
00407 #
00408     def check_params(self, param=None, value=None, ipython_globals=None):
00409       if ipython_globals == None:
00410           myf=self.__globals__
00411       else:
00412           myf=ipython_globals
00413 #      print 'param:', param, 'value:', value
00414       try :
00415          if str(type(value)) != "<type 'instance'>" :
00416             value0 = value
00417             value = myf['cu'].expandparam(param, value)
00418             matchtype = False
00419             if(type(value) == numpy.ndarray):
00420                if(type(value) == type(value0)):
00421                   myf[param] = value.tolist()
00422                else:
00423                   #print 'value:', value, 'value0:', value0
00424                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00425                   myf[param] = value0
00426                   if type(value0) != list :
00427                      matchtype = True
00428             else :
00429                myf[param] = value
00430             value = myf['cu'].verifyparam({param:value})
00431             if matchtype:
00432                value = False
00433       except Exception, instance:
00434          #ignore the exception and just return it unchecked
00435          myf[param] = value
00436       return value
00437 #
00438 #
00439     def description(self, key='sdgrid', subkey=None):
00440         desc={'sdgrid': 'SD task: gridding single dish data',
00441                'infiles': '(list of) input SD dataset',
00442                'antenna': 'antenna name(s) or id(s)',
00443                'scanlist': 'list of scans to use (e.g. [1,2,3,4])',
00444                'ifno': 'IFNO for gridding',
00445                'pollist': 'POLNO for gridding',
00446                'gridfunction': 'gridding function for imaging ("BOX","SF","GAUSS","PB")',
00447                'convsupport': 'truncate of convolution kernel',
00448                'truncate': 'truncation radius of convolution kernel',
00449                'gwidth': 'HWHM for gaussian',
00450                'jwidth': 'c-parameter for jinc function',
00451                'weight': 'weight type',
00452                'clipminmax': 'clip minimum and maximum values during gridding',
00453                'outfile': 'output image name',
00454                'overwrite': 'overwrite option',
00455                'npix': 'number of pixels in x and y, symmetric for single value',
00456                'cell': 'x and y cell size. default unit arcsec',
00457                'center': 'Image center',
00458                'plot': 'Plot result or not',
00459 
00460                'async': 'If true the taskname must be started using sdgrid(...)'
00461               }
00462 
00463 #
00464 # Set subfields defaults if needed
00465 #
00466 
00467         if(desc.has_key(key)) :
00468            return desc[key]
00469 
00470     def itsdefault(self, paramname) :
00471         a = {}
00472         a['infiles']  = [""]
00473         a['antenna']  = -1
00474         a['scanlist']  = []
00475         a['ifno']  = -1
00476         a['pollist']  = []
00477         a['gridfunction']  = 'BOX'
00478         a['convsupport']  = -1
00479         a['truncate']  = -1
00480         a['gwidth']  = -1
00481         a['jwidth']  = -1
00482         a['weight']  = 'UNIFORM'
00483         a['clipminmax']  = False
00484         a['outfile']  = ''
00485         a['overwrite']  = False
00486         a['npix']  = -1
00487         a['cell']  = ''
00488         a['center']  = ''
00489         a['plot']  = False
00490 
00491         #a = sys._getframe(len(inspect.stack())-1).f_globals
00492 
00493         if self.parameters['gridfunction']  == 'SF':
00494             a['convsupport'] = -1
00495 
00496         if self.parameters['gridfunction']  == 'sf':
00497             a['convsupport'] = -1
00498 
00499         if self.parameters['gridfunction']  == 'GAUSS':
00500             a['truncate'] = -1
00501             a['gwidth'] = -1
00502 
00503         if self.parameters['gridfunction']  == 'gauss':
00504             a['truncate'] = -1
00505             a['gwidth'] = -1
00506 
00507         if self.parameters['gridfunction']  == 'GJINC':
00508             a['truncate'] = -1
00509             a['gwidth'] = -1
00510             a['jwidth'] = -1
00511 
00512         if self.parameters['gridfunction']  == 'gjinc':
00513             a['truncate'] = -1
00514             a['gwidth'] = -1
00515             a['jwidth'] = -1
00516 
00517         if a.has_key(paramname) :
00518               return a[paramname]
00519 sdgrid_cli = sdgrid_cli_()