casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
uvmodelfit_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_uvmodelfit import uvmodelfit
00016 from task_uvmodelfit import casalog
00017 
00018 class uvmodelfit_pg_:
00019     __name__ = "uvmodelfit"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (uvmodelfit_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, vis=None, field=None, spw=None, selectdata=None, timerange=None, uvrange=None, antenna=None, scan=None, msselect=None, niter=None, comptype=None, sourcepar=None, varypar=None, outfile=None, async=None):
00027 
00028         """Fit a single component source model to the uv data
00029 
00030         Fit a single component source model to the uv data.  Three models
00031         are available: P=point; G=Gaussian; D=Disk.  Fitting parameters can
00032         be held fixed.   The results are given in the log and placed in a
00033         components file.
00034 
00035         Keyword arguments:
00036         vis -- Name of input visibility file 
00037                 default: none; example: vis='ngc5921.ms'
00038                 
00039         --- Data Selection
00040         field -- Select data based on field id(s) or name(s)
00041                 default: '' (all); example: field='1'
00042                 field='0~2' # field ids inclusive from 0 to 2
00043                 field='3C*' # all field names starting with 3C
00044         spw -- Select data based on spectral window
00045                 default: '' (all); example: spw='1'
00046                 spw='<2' #spectral windows less than 2
00047                 spw='>1' #spectral windows greater than 1
00048         selectdata -- Select a subset of the visibility using MSSelection
00049                 default: False; example: selectdata=True
00050         timerange  -- Select data based on time range:
00051                 default = '' (all); example,
00052                 timerange = 'YYYY/MM/DD/hh:mm:ss~YYYY/MM/DD/hh:mm:ss'
00053                 Note: YYYY/MM/DD can be dropped as needed:
00054                 timerange='09:14:0~09:54:0' # this time range
00055                 timerange='09:44:00' # data within one integration of time
00056                 timerange='>10:24:00' # data after this time
00057                 timerange='09:44:00+00:13:00' #data 13 minutes after time
00058         uvrange -- Select data within uvrange (default units kilo-lambda)
00059                default: '' (all); example:
00060                uvrange='0~1000kl'; uvrange from 0-1000 kilo-lamgda
00061                uvrange='>4kl';uvranges greater than 4 kilo lambda
00062                uvrange='0~1000km'; uvrange in kilometers
00063         antenna -- Select data based on antenna/baseline
00064                 default: '' (all); example: antenna='5&6' baseline 5-6
00065                 antenna='5&6;7&8' #baseline 5-6 and 7-8
00066                 antenna='5' # all baselines with antenna 5
00067                 antenna='5,6' # all baselines with antennas 5 and 6
00068         scan -- Select data based on scan number - New, under developement
00069                 default: '' (all); example: scan='>3'
00070         msselect -- Optional data selection (field,spw,time,etc)
00071                 default:'' means select all; example:msselect='FIELD_ID==0', 
00072                 msselect='FIELD_ID IN [0,1,2]' means select fields 0,1 and 2
00073                 msselect='FIELD_ID <= 1 means select fields 0, 1
00074                 msselect='FIELD_ID==0 && ANTENNA1 IN [0] && ANTENNA2 IN [2:26]'
00075                    means select field 0 and antennas 0 to 26, except antenna 1.
00076                 Other msselect fields are: 'DATA_DESC_ID', 'SPECTRAL_WINDOW_ID',
00077                 'POLARIZATION_ID', 'SCAN_NUMBER', 'TIME', 'UVW'
00078                 See ccokbook for more details
00079 
00080         niter -- Number of fitting iterations to execute
00081                 default: 5; example: niter=20
00082         comptype -- component model type
00083                 default: 'P';
00084                 Options: 'P' (point source), 'G' (elliptical gaussian),
00085                          'D' (elliptical disk)
00086         sourcepar -- Starting guess for component parameters
00087                 default: [1,0,0];  (for comptype='P')
00088                 IF comptype = 'P' then
00089                   sourcepar = [flux,xoff,yoff] where
00090                     flux = Jy, xoff = arcsec-east, yoff = arcsec-north.
00091                 IF comptype = 'G' or 'D', then
00092                   sourcepar = [flux,xoff,yoff,majax,axrat,pos] where
00093                     majax = arcsec, axrat < 1, pos=angle in deg
00094         varypar -- Control which parameters to let vary in the fit
00095                 default: [] (all vary);
00096                 example: vary=[F,T,T]
00097 
00098         examples:
00099 
00100              fit a point:
00101                 comptype = 'P'
00102                 sourcepar = [0.4,0.2,-0.3];
00103                 varypar = [T,T,T]
00104 
00105              fit a circular Gaussian:
00106                 comptype = 'G'
00107                 sourcepar = [1.4,0.3,-0.2,0.3, 1, 0]
00108                 varypar    = [ T , T ,  T , T , F, F]
00109                     
00110 
00111         outfile -- Optional output component list table
00112                 default: ''; example: outfile='componentlist.cl'
00113 
00114 
00115         How to get the output values:
00116 
00117             cl.open('componentlist.cl')
00118             fit = cl.getcompoent()             stores component information
00119             fit                                to see the whole mess
00120             flux = fit['flux']['value']        to store the I,Q,U,V, flux
00121             print flux
00122 
00123             ra = fit['shape']['direction']['m0']['value']
00124             dec =fit['shape']['direction']['m1']['value']
00125             print ra, dec
00126 
00127             bmaj = fit['shape']['majoraxis']['value']     to get major axis
00128             bmin = fit['shape']['minoraxis']['value']     to get minor axis
00129             
00130 
00131 
00132         """
00133         a=inspect.stack()
00134         stacklevel=0
00135         for k in range(len(a)):
00136           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00137                 stacklevel=k
00138                 break
00139         myf=sys._getframe(stacklevel).f_globals
00140         myf['__last_task'] = 'uvmodelfit'
00141         myf['taskname'] = 'uvmodelfit'
00142         ###
00143         myf['update_params'](func=myf['taskname'],printtext=False)
00144         ###
00145         ###
00146         #Handle globals or user over-ride of arguments
00147         #
00148         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00149         useLocalDefaults = False
00150 
00151         for item in function_signature_defaults.iteritems():
00152                 key,val = item
00153                 keyVal = eval(key)
00154                 if (keyVal == None):
00155                         #user hasn't set it - use global/default
00156                         pass
00157                 else:
00158                         #user has set it - use over-ride
00159                         if (key != 'self') :
00160                            useLocalDefaults = True
00161                         #myf[key]=keyVal
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                if (keyVal == None):
00170                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00171                    keyVal = eval(key)
00172                    if(type(keyVal) == dict) :
00173                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00174 
00175         else :
00176             uselessvariable = None 
00177             myparams['vis'] = vis = myf['vis']
00178             myparams['field'] = field = myf['field']
00179             myparams['spw'] = spw = myf['spw']
00180             myparams['selectdata'] = selectdata = myf['selectdata']
00181             myparams['timerange'] = timerange = myf['timerange']
00182             myparams['uvrange'] = uvrange = myf['uvrange']
00183             myparams['antenna'] = antenna = myf['antenna']
00184             myparams['scan'] = scan = myf['scan']
00185             myparams['msselect'] = msselect = myf['msselect']
00186             myparams['niter'] = niter = myf['niter']
00187             myparams['comptype'] = comptype = myf['comptype']
00188             myparams['sourcepar'] = sourcepar = myf['sourcepar']
00189             myparams['varypar'] = varypar = myf['varypar']
00190             myparams['outfile'] = outfile = myf['outfile']
00191 
00192         if type(sourcepar)==float: sourcepar=[sourcepar]
00193         if type(varypar)==bool: varypar=[varypar]
00194 
00195         result = None
00196 
00197 #
00198 #    The following is work around to avoid a bug with current python translation
00199 #
00200         mytmp = {}
00201 
00202         mytmp['vis'] = vis
00203         mytmp['field'] = field
00204         mytmp['spw'] = spw
00205         mytmp['selectdata'] = selectdata
00206         mytmp['timerange'] = timerange
00207         mytmp['uvrange'] = uvrange
00208         mytmp['antenna'] = antenna
00209         mytmp['scan'] = scan
00210         mytmp['msselect'] = msselect
00211         mytmp['niter'] = niter
00212         mytmp['comptype'] = comptype
00213         mytmp['sourcepar'] = sourcepar
00214         mytmp['varypar'] = varypar
00215         mytmp['outfile'] = outfile
00216         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00217         trec = casac.utils().torecord(pathname+'uvmodelfit.xml')
00218 
00219         casalog.origin('uvmodelfit')
00220         if not trec.has_key('uvmodelfit') or not casac.utils().verify(mytmp, trec['uvmodelfit']) :
00221             return False
00222 
00223 
00224         try :
00225           casalog.post('')
00226           casalog.post('##########################################')
00227           casalog.post('##### Begin Task: uvmodelfit           #####')
00228           casalog.post('')
00229           result = uvmodelfit(vis, field, spw, selectdata, timerange, uvrange, antenna, scan, msselect, niter, comptype, sourcepar, varypar, outfile)
00230           casalog.post('')
00231           casalog.post('##### End Task: uvmodelfit           #####')
00232           casalog.post('##########################################')
00233 
00234 
00235 # saveinputs for individule engine has no use
00236 # saveinputs should alos be removed from casa_in_py.py
00237 #
00238 #
00239 #          saveinputs = myf['saveinputs']
00240 #          saveinputs('uvmodelfit', 'uvmodelfit.last', myparams)
00241 #
00242 #
00243         except Exception, instance:
00244           #print '**** Error **** ',instance
00245           pass
00246 
00247         gc.collect()
00248         return result
00249 #
00250 #
00251 ##
00252 #    def paramgui(self, useGlobals=True):
00253 #        """
00254 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00255 #        """
00256 #        import paramgui
00257 #
00258 #        a=inspect.stack()
00259 #        stacklevel=0
00260 #        for k in range(len(a)):
00261 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00262 #            stacklevel=k
00263 #            break
00264 #        myf = sys._getframe(stacklevel).f_globals
00265 #
00266 #        if useGlobals:
00267 #            paramgui.setGlobals(myf)
00268 #        else:
00269 #            paramgui.setGlobals({})
00270 #
00271 #        paramgui.runTask('uvmodelfit', myf['_ip'])
00272 #        paramgui.setGlobals({})
00273 #
00274 #
00275 #
00276 #
00277     def defaults(self, param=None):
00278         a=inspect.stack()
00279         stacklevel=0
00280         for k in range(len(a)):
00281           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00282                 stacklevel=k
00283                 break
00284         myf=sys._getframe(stacklevel).f_globals
00285         a = odict()
00286         a['vis']  = ''
00287         a['field']  = ''
00288         a['spw']  = ''
00289         a['selectdata']  = True
00290         a['niter']  = 5
00291         a['comptype']  = 'P'
00292         a['sourcepar']  = [1.0, 0.0, 0.0]
00293         a['varypar']  = []
00294         a['outfile']  = ''
00295 
00296         a['async']=False
00297         a['selectdata'] = {
00298                     0:odict([{'value':True}, {'timerange':''}, {'uvrange':''}, {'antenna':''}, {'scan':''}, {'msselect':''}]), 
00299                     1:{'value':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(a.has_key(param)):
00309                    #if(type(a[param]) == dict) :
00310                    #   return a[param][len(a[param])-1]['value']
00311                    #else :
00312                       return a[param]
00313 
00314 
00315 #
00316 #
00317     def check_params(self, param=None, value=None):
00318       a=inspect.stack() 
00319       stacklevel=0
00320       for k in range(len(a)):
00321         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00322             stacklevel=k
00323             break
00324       myf=sys._getframe(stacklevel).f_globals
00325 
00326 #      print 'param:', param, 'value:', value
00327       try :
00328          if str(type(value)) != "<type 'instance'>" :
00329             value0 = value
00330             value = myf['cu'].expandparam(param, value)
00331             matchtype = False
00332             if(type(value) == numpy.ndarray):
00333                if(type(value) == type(value0)):
00334                   myf[param] = value.tolist()
00335                else:
00336                   #print 'value:', value, 'value0:', value0
00337                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00338                   myf[param] = value0
00339                   if type(value0) != list :
00340                      matchtype = True
00341             else :
00342                myf[param] = value
00343             value = myf['cu'].verifyparam({param:value})
00344             if matchtype:
00345                value = False
00346       except Exception, instance:
00347          #ignore the exception and just return it unchecked
00348          myf[param] = value
00349       return value
00350 
00351 #
00352 #
00353     def description(self, key='uvmodelfit', subkey=None):
00354         desc={'uvmodelfit': 'Fit a single component source model to the uv data',
00355                'vis': 'Name of input visibility file',
00356                'field': 'Select field using field id(s) or field name(s)',
00357                'spw': 'Select spectral window/channels',
00358                'selectdata': 'Other data selection parameters',
00359                'timerange': 'Select data based on time range',
00360                'uvrange': 'Select data within uvrange (default units meters)',
00361                'antenna': 'Select data based on antenna/baseline',
00362                'scan': 'Scan number range',
00363                'msselect': 'Optional complex data selection (ignore for now)',
00364                'niter': 'Number of fitting iterations to execute',
00365                'comptype': 'component model type',
00366                'sourcepar': 'Starting guess for component parameters',
00367                'varypar': 'Control which parameters to let vary in the fit',
00368                'outfile': 'Optional output component list table',
00369 
00370                'async': 'If true the taskname must be started using uvmodelfit(...)'
00371               }
00372 
00373 #
00374 # Set subfields defaults if needed
00375 #
00376 
00377         if(desc.has_key(key)) :
00378            return desc[key]
00379 
00380     def itsdefault(self, paramname) :
00381         a = {}
00382         a['vis']  = ''
00383         a['field']  = ''
00384         a['spw']  = ''
00385         a['selectdata']  = True
00386         a['timerange']  = ''
00387         a['uvrange']  = ''
00388         a['antenna']  = ''
00389         a['scan']  = ''
00390         a['msselect']  = ''
00391         a['niter']  = 5
00392         a['comptype']  = 'P'
00393         a['sourcepar']  = [1.0, 0.0, 0.0]
00394         a['varypar']  = []
00395         a['outfile']  = ''
00396 
00397         if a.has_key(paramname) :
00398               return a[paramname]
00399 uvmodelfit_pg = uvmodelfit_pg_()