casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
simanalyze_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_simanalyze import simanalyze
00016 from task_simanalyze import casalog
00017 
00018 class simanalyze_pg_:
00019     __name__ = "simanalyze"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (simanalyze_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, project=None, image=None, imagename=None, vis=None, modelimage=None, cell=None, imsize=None, imdirection=None, niter=None, threshold=None, weighting=None, mask=None, outertaper=None, stokes=None, analyze=None, showuv=None, showpsf=None, showmodel=None, showconvolved=None, showclean=None, showresidual=None, showdifference=None, showfidelity=None, graphics=None, verbose=None, overwrite=None, async=None):
00027 
00028         """image and analyze simulated datasets
00029 
00030     This task is for imaging and analyzing datasets created with 
00031     simobserve or simalma.  New functionality is actively 
00032     being added, so if you have changed versions of CASA, check 
00033     the inputs carefully.
00034     More information and examples are availible at 
00035      http://casaguides.nrao.edu/index.php?title=Simulating_Observations_in_CASA
00036     Please contact CASA experts with any questions.
00037     -------------------------------
00038     project -- root filename for all output files.
00039                must be the same as used when simulating the observation.
00040                in particular $project/$project.skymodel will be required
00041                to compare output and input images.
00042     image -- invert and deconvolve the measurement set(s)
00043        * NOTE: interactive clean or more parameters than the subset visible
00044          here are available by simply running the clean task directly, 
00045          then returning to simanalyze to run "analyze" if desired.
00046        * NOTE: the channelization of the output image cube will be the 
00047          same as that in the simulated Measurement Set.
00048        * if graphics turned on, display the clean image and residual image
00049        * uses Cotton-Schwab clean for single fields and Mosaic gridding
00050          for multiple fields (with Clark PSF calculation in minor cycles).
00051     vis -- the simulated interferometric MS, or total-power one, or both
00052        * one can use '$project' to let the task automatically replace it to
00053          the project name, e.g., vis='$project.noisy.ms,$project.noisy.sd.ms'.
00054          However, note that if you created measurement set(s) using simobserve,
00055          they will have names including the configuration, e.g. 
00056          $project.alma_out20.noisy.ms
00057        * setting this paramter to "default" will find and attempt to image
00058          all measurement sets (interferometric and single dish) in the 
00059          project directory
00060     modelimage -- prior (e.g. SD) image to be used in clean
00061     cell -- cell size e.g '10arcsec'.  "" defaults to the skymodel cell
00062     imsize -- image size in spatial pixels (x,y)
00063        0 or -1 will use the model image size; example: imsize=[500,500]
00064     imdirection -- phase center for synthesized image.  default is to 
00065        center on the sky model.
00066     niter -- number of clean/deconvolution iterations, 0 for no cleaning
00067     threshold -- flux level to stop cleaning
00068     weighting -- weighting to apply to visibilities
00069        options: 'natural','uniform','briggs' (robust=0.5)
00070     mask -- Specification of cleanbox(es), mask image(s), primary beam
00071        coverage level, and/or region(s) to be used for CLEANing.
00072        CLEAN tends to perform better, and is less likely to diverge, if 
00073        the CLEAN component placement is limited by a mask to where real 
00074        emission is expected to be.  e.g. pixel ranges mask=[110,110,150,145],
00075        filename of mask image mask='myimage.mask', or a file with mask 
00076        regions --  see help for the clean task.
00077     outertaper -- apply additional uv outer taper of visibilities
00078     stokes -- Stokes parameters to image; 'I','IV','IQU','IQUV'
00079     -------------------------------
00080     analyze -- compute and display difference between model and output, 
00081          fidelity, etc. 
00082     showuv -- display uv coverage
00083     showpsf -- display synthesized (dirty) beam (ignored in single dish simulation)
00084     showmodel -- display sky model at original resolution
00085     showconvolved -- display sky model convolved with output beam 
00086     showclean -- display the synthesized image
00087     showresidual -- display the clean residual image (ignored in single dish simulation)
00088     showdifference -- display difference between output cleaned image and 
00089          input model sky image convolved with output clean beam
00090     showfidelity -- display fidelity image
00091          fidelity = abs(input) / max[ abs(input-output), 0.7*rms(output) ]
00092     
00093     graphics -- view plots on the screen, saved to file, both, or neither
00094     verbose -- print extra information to the logger and terminal
00095     overwrite -- overwrite existing files in the project subdirectory
00096 
00097     Note that the RMS is calculated in the lower quarter of the image.  
00098          This is likely not the best choice, so you are encouraged to 
00099          measure RMS yourself in an off-source region using the viewer.
00100 
00101 
00102     -------------------------------
00103     Output produced: (not all will always exist, depending on input parameters)
00104     To support different runs with different arrays, the names have the
00105     configuration name from antennalist appended.
00106     -------------------------------
00107     project.[cfg].skymodel.flat.regrid.conv = input sky regridded to match 
00108          the output image, and convolved with the output clean beam
00109 
00110     project.[cfg].image = synthesized image
00111     project.[cfg].flux.pbcoverage = primary beam correction for mosaic image
00112     project.[cfg].residual = residual image after cleaning
00113     project.[cfg].clean.last = parameter file of what parameters were used in
00114           the clean task
00115     project.[cfg].psf = synthesized (dirty) beam calculated from weighted uv 
00116           distribution
00117     project.[cfg].image.png = diagnostic figure of clean image and residual
00118             
00119     project.[cfg].fidelity = fidelity image
00120     project.[cfg].analysis.png = diagnostic figure of difference and fidelity
00121             
00122     project.[cfg].simanalyze.last = saved input parameters for simanalyze task
00123 
00124 
00125         """
00126         a=inspect.stack()
00127         stacklevel=0
00128         for k in range(len(a)):
00129           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00130                 stacklevel=k
00131                 break
00132         myf=sys._getframe(stacklevel).f_globals
00133         myf['__last_task'] = 'simanalyze'
00134         myf['taskname'] = 'simanalyze'
00135         ###
00136         myf['update_params'](func=myf['taskname'],printtext=False)
00137         ###
00138         ###
00139         #Handle globals or user over-ride of arguments
00140         #
00141         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00142         useLocalDefaults = False
00143 
00144         for item in function_signature_defaults.iteritems():
00145                 key,val = item
00146                 keyVal = eval(key)
00147                 if (keyVal == None):
00148                         #user hasn't set it - use global/default
00149                         pass
00150                 else:
00151                         #user has set it - use over-ride
00152                         if (key != 'self') :
00153                            useLocalDefaults = True
00154                         #myf[key]=keyVal
00155 
00156         myparams = {}
00157         if useLocalDefaults :
00158            for item in function_signature_defaults.iteritems():
00159                key,val = item
00160                keyVal = eval(key)
00161                exec('myparams[key] = keyVal')
00162                if (keyVal == None):
00163                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00164                    keyVal = eval(key)
00165                    if(type(keyVal) == dict) :
00166                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00167 
00168         else :
00169             uselessvariable = None 
00170             myparams['project'] = project = myf['project']
00171             myparams['image'] = image = myf['image']
00172             myparams['imagename'] = imagename = myf['imagename']
00173             myparams['vis'] = vis = myf['vis']
00174             myparams['modelimage'] = modelimage = myf['modelimage']
00175             myparams['cell'] = cell = myf['cell']
00176             myparams['imsize'] = imsize = myf['imsize']
00177             myparams['imdirection'] = imdirection = myf['imdirection']
00178             myparams['niter'] = niter = myf['niter']
00179             myparams['threshold'] = threshold = myf['threshold']
00180             myparams['weighting'] = weighting = myf['weighting']
00181             myparams['mask'] = mask = myf['mask']
00182             myparams['outertaper'] = outertaper = myf['outertaper']
00183             myparams['stokes'] = stokes = myf['stokes']
00184             myparams['analyze'] = analyze = myf['analyze']
00185             myparams['showuv'] = showuv = myf['showuv']
00186             myparams['showpsf'] = showpsf = myf['showpsf']
00187             myparams['showmodel'] = showmodel = myf['showmodel']
00188             myparams['showconvolved'] = showconvolved = myf['showconvolved']
00189             myparams['showclean'] = showclean = myf['showclean']
00190             myparams['showresidual'] = showresidual = myf['showresidual']
00191             myparams['showdifference'] = showdifference = myf['showdifference']
00192             myparams['showfidelity'] = showfidelity = myf['showfidelity']
00193             myparams['graphics'] = graphics = myf['graphics']
00194             myparams['verbose'] = verbose = myf['verbose']
00195             myparams['overwrite'] = overwrite = myf['overwrite']
00196 
00197         if type(imsize)==int: imsize=[imsize]
00198         if type(outertaper)==str: outertaper=[outertaper]
00199 
00200         result = None
00201 
00202 #
00203 #    The following is work around to avoid a bug with current python translation
00204 #
00205         mytmp = {}
00206 
00207         mytmp['project'] = project
00208         mytmp['image'] = image
00209         mytmp['imagename'] = imagename
00210         mytmp['vis'] = vis
00211         mytmp['modelimage'] = modelimage
00212         mytmp['cell'] = cell
00213         mytmp['imsize'] = imsize
00214         mytmp['imdirection'] = imdirection
00215         mytmp['niter'] = niter
00216         mytmp['threshold'] = threshold
00217         mytmp['weighting'] = weighting
00218         mytmp['mask'] = mask
00219         mytmp['outertaper'] = outertaper
00220         mytmp['stokes'] = stokes
00221         mytmp['analyze'] = analyze
00222         mytmp['showuv'] = showuv
00223         mytmp['showpsf'] = showpsf
00224         mytmp['showmodel'] = showmodel
00225         mytmp['showconvolved'] = showconvolved
00226         mytmp['showclean'] = showclean
00227         mytmp['showresidual'] = showresidual
00228         mytmp['showdifference'] = showdifference
00229         mytmp['showfidelity'] = showfidelity
00230         mytmp['graphics'] = graphics
00231         mytmp['verbose'] = verbose
00232         mytmp['overwrite'] = overwrite
00233         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00234         trec = casac.utils().torecord(pathname+'simanalyze.xml')
00235 
00236         casalog.origin('simanalyze')
00237         if not trec.has_key('simanalyze') or not casac.utils().verify(mytmp, trec['simanalyze']) :
00238             return False
00239 
00240 
00241         try :
00242           casalog.post('')
00243           casalog.post('##########################################')
00244           casalog.post('##### Begin Task: simanalyze           #####')
00245           casalog.post('')
00246           result = simanalyze(project, image, imagename, vis, modelimage, cell, imsize, imdirection, niter, threshold, weighting, mask, outertaper, stokes, analyze, showuv, showpsf, showmodel, showconvolved, showclean, showresidual, showdifference, showfidelity, graphics, verbose, overwrite)
00247           casalog.post('')
00248           casalog.post('##### End Task: simanalyze           #####')
00249           casalog.post('##########################################')
00250 
00251 
00252 # saveinputs for individule engine has no use
00253 # saveinputs should alos be removed from casa_in_py.py
00254 #
00255 #
00256 #          saveinputs = myf['saveinputs']
00257 #          saveinputs('simanalyze', 'simanalyze.last', myparams)
00258 #
00259 #
00260         except Exception, instance:
00261           #print '**** Error **** ',instance
00262           pass
00263 
00264         gc.collect()
00265         return result
00266 #
00267 #
00268 ##
00269 #    def paramgui(self, useGlobals=True):
00270 #        """
00271 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00272 #        """
00273 #        import paramgui
00274 #
00275 #        a=inspect.stack()
00276 #        stacklevel=0
00277 #        for k in range(len(a)):
00278 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00279 #            stacklevel=k
00280 #            break
00281 #        myf = sys._getframe(stacklevel).f_globals
00282 #
00283 #        if useGlobals:
00284 #            paramgui.setGlobals(myf)
00285 #        else:
00286 #            paramgui.setGlobals({})
00287 #
00288 #        paramgui.runTask('simanalyze', myf['_ip'])
00289 #        paramgui.setGlobals({})
00290 #
00291 #
00292 #
00293 #
00294     def defaults(self, param=None):
00295         a=inspect.stack()
00296         stacklevel=0
00297         for k in range(len(a)):
00298           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00299                 stacklevel=k
00300                 break
00301         myf=sys._getframe(stacklevel).f_globals
00302         a = odict()
00303         a['project']  = 'sim'
00304         a['image']  = True
00305         a['analyze']  = False
00306         a['graphics']  = 'both'
00307         a['verbose']  = False
00308         a['overwrite']  = True
00309 
00310         a['async']=False
00311         a['image'] = {
00312                     0:odict([{'value':True}, {'vis':'default'}, {'modelimage':''}, {'imsize':0}, {'imdirection':''}, {'cell':''}, {'niter':500}, {'threshold':'0.1mJy'}, {'weighting':'natural'}, {'mask':[]}, {'outertaper':[]}, {'stokes':'I'}]), 
00313                     1:odict([{'value':False}, {'imagename':'default'}])}
00314         a['analyze'] = {
00315                     0:{'value':False}, 
00316                     1:odict([{'value':True}, {'showuv':True}, {'showpsf':True}, {'showmodel':True}, {'showconvolved':False}, {'showclean':True}, {'showresidual':False}, {'showdifference':True}, {'showfidelity':True}])}
00317 
00318 ### This function sets the default values but also will return the list of
00319 ### parameters or the default value of a given parameter
00320         if(param == None):
00321                 myf['__set_default_parameters'](a)
00322         elif(param == 'paramkeys'):
00323                 return a.keys()
00324         else:
00325                 if(a.has_key(param)):
00326                    #if(type(a[param]) == dict) :
00327                    #   return a[param][len(a[param])-1]['value']
00328                    #else :
00329                       return a[param]
00330 
00331 
00332 #
00333 #
00334     def check_params(self, param=None, value=None):
00335       a=inspect.stack() 
00336       stacklevel=0
00337       for k in range(len(a)):
00338         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00339             stacklevel=k
00340             break
00341       myf=sys._getframe(stacklevel).f_globals
00342 
00343 #      print 'param:', param, 'value:', value
00344       try :
00345          if str(type(value)) != "<type 'instance'>" :
00346             value0 = value
00347             value = myf['cu'].expandparam(param, value)
00348             matchtype = False
00349             if(type(value) == numpy.ndarray):
00350                if(type(value) == type(value0)):
00351                   myf[param] = value.tolist()
00352                else:
00353                   #print 'value:', value, 'value0:', value0
00354                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00355                   myf[param] = value0
00356                   if type(value0) != list :
00357                      matchtype = True
00358             else :
00359                myf[param] = value
00360             value = myf['cu'].verifyparam({param:value})
00361             if matchtype:
00362                value = False
00363       except Exception, instance:
00364          #ignore the exception and just return it unchecked
00365          myf[param] = value
00366       return value
00367 
00368 #
00369 #
00370     def description(self, key='simanalyze', subkey=None):
00371         desc={'simanalyze': 'image and analyze simulated datasets',
00372                'project': 'root prefix for output file names',
00373                'image': '(re)image $project.*.ms to $project.image',
00374                'imagename': 'image to analyze (default = first $project/*.image found)',
00375                'vis': 'Measurement Set(s) to image',
00376                'modelimage': 'prior image to use in clean e.g. existing single dish image',
00377                'cell': 'cell size with units or "" to equal model',
00378                'imsize': 'output image size in pixels (x,y) or 0 to match model',
00379                'imdirection': 'set output image direction, (otherwise center on the model)',
00380                'niter': 'maximum number of iterations (0 for dirty image)',
00381                'threshold': 'flux level (+units) to stop cleaning',
00382                'weighting': 'weighting to apply to visibilities',
00383                'mask': 'Cleanbox(es), mask image(s), region(s), or a level',
00384                'outertaper': 'uv-taper on outer baselines in uv-plane',
00385                'stokes': 'Stokes params to image',
00386                'analyze': '(only first 6 selected outputs will be displayed)',
00387                'showuv': 'display uv coverage',
00388                'showpsf': 'display synthesized (dirty) beam (ignored in single dish simulation)',
00389                'showmodel': 'display sky model at original resolution',
00390                'showconvolved': 'display sky model convolved with output clean beam',
00391                'showclean': 'display the synthesized image',
00392                'showresidual': 'display the clean residual image (ignored in single dish simulation)',
00393                'showdifference': 'display difference between output cleaned image and input model sky image convolved with output clean beam',
00394                'showfidelity': 'display fidelity (see help)',
00395                'graphics': 'display graphics at each stage to [screen|file|both|none]',
00396                'verbose': '',
00397                'overwrite': 'overwrite files starting with $project',
00398 
00399                'async': 'If true the taskname must be started using simanalyze(...)'
00400               }
00401 
00402 #
00403 # Set subfields defaults if needed
00404 #
00405 
00406         if(desc.has_key(key)) :
00407            return desc[key]
00408 
00409     def itsdefault(self, paramname) :
00410         a = {}
00411         a['project']  = 'sim'
00412         a['image']  = True
00413         a['imagename']  = 'default'
00414         a['vis']  = 'default'
00415         a['modelimage']  = ''
00416         a['cell']  = ''
00417         a['imsize']  = [128, 128]
00418         a['imdirection']  = ''
00419         a['niter']  = 500
00420         a['threshold']  = '0.1mJy'
00421         a['weighting']  = 'natural'
00422         a['mask']  = []
00423         a['outertaper']  = ['']
00424         a['stokes']  = 'I'
00425         a['analyze']  = False
00426         a['showuv']  = True
00427         a['showpsf']  = True
00428         a['showmodel']  = True
00429         a['showconvolved']  = False
00430         a['showclean']  = True
00431         a['showresidual']  = False
00432         a['showdifference']  = True
00433         a['showfidelity']  = True
00434         a['graphics']  = 'both'
00435         a['verbose']  = False
00436         a['overwrite']  = True
00437 
00438         if a.has_key(paramname) :
00439               return a[paramname]
00440 simanalyze_pg = simanalyze_pg_()