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