casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
simalma_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_simalma import simalma
00016 from task_simalma import casalog
00017 
00018 class simalma_pg_:
00019     __name__ = "simalma"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (simalma_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, project=None, skymodel=None, inbright=None, indirection=None, incell=None, incenter=None, inwidth=None, complist=None, compwidth=None, setpointings=None, ptgfile=None, integration=None, direction=None, mapsize=None, antennalist=None, hourangle=None, totaltime=None, acaratio=None, acaconfig=None, pwv=None, image=None, imsize=None, imdirection=None, cell=None, niter=None, threshold=None, graphics=None, verbose=None, overwrite=None, async=None):
00027 
00028         """(Experimental) simple simulation task for ALMA 
00029 ALMA simulation task:
00030 
00031     ##### WARNING: This task is EXPERIMENTAL #####
00032     This task simulates ALMA observation including 12-m, ACA 7-m and total
00033     power arrays, and images and analyzes simulated data.
00034     New functionality is actively being added, so if you have changed
00035     versions of CASA, check the inputs carefully.
00036     More information and examples are availible at 
00037      http://casaguides.nrao.edu/index.php?title=Simulating_Observations_in_CASA
00038     Please contact CASA experts with any questions, especially 
00039     about features noted below as *experimental*    
00040     -------------------------------
00041     project -- root filename for all output files.
00042     -------------------------------
00043     skymodel -- image model of the sky in FITS or CASA image, 
00044          with optional parameters that can be overridden
00045     inbright -- peak brightness in Jy/pixel, or "" for unchanged
00046        * NOTE: "unchanged" will take the numerical values in your image 
00047          and assume they are in Jy/pixel, even if it says some other unit 
00048          in the header. 
00049     indirection -- central direction, or "" for unchanged
00050     incell -- spatial pixel size, or "" for unchanged
00051     incenter -- frequency of center channel e.g. "89GHz", or "" for unchanged
00052     inwidth -- width of channels, or "" for unchanged - this should be a 
00053          string representing a quantity with units e.g. "10MHz"
00054        * NOTE: only works reliably with frequencies, not velocities
00055        * NOTE: it is not possible to change the number of spectral planes
00056          of the sky model, only to relabel them with different frequencies
00057          That kind of regridding can be accomplished with the CASA toolkit.
00058     -------------------------------
00059     complist -- component list model of the sky, added to or instead of skymodel
00060     compwidth -- bandwidth of components; if simulating from components only, 
00061          this defines the bandwidth of the MS and output images
00062     -------------------------------
00063     setpointings -- calculate a map of pointings, or if false, provide ptgfile
00064        * if graphics are on, display the pointings shown on the model image
00065     ptgfile -- a text file specifying directions in the same 
00066          format as the example, and optional integration times, e.g.
00067          #Epoch     RA          DEC      TIME(optional)
00068          J2000 23h59m28.10 -019d52m12.35 10.0
00069        * if the time column is not present in the file, it will use
00070          "integration" for all pointings.
00071        * NOTE: at this time the file should contain only science pointings:
00072          simalma will observe these until totaltime is used up. 
00073     integration --- Time interval for each integration e.g '10s'
00074        * NOTE: to simulate a "scan" longer than one integration, use 
00075          setpointings to generate a pointing file, and then edit the 
00076          file to increase the time at each point to be larger than 
00077          the parameter integration time.
00078     direction -- mosaic center direction e.g 'J2000 19h00m00 -40d00m00'
00079        * can optionally be a list of pointings
00080        * otherwise simalma will pack mapsize with grids proper for the
00081          array (see below).
00082     mapsize -- angular size of map 
00083        * set to "" to span the model image
00084     -------------------------------
00085     antennalist -- ascii file containing antenna positions.
00086        * NOTE: In this task, it should be an ALMA configuration.
00087        * standard arrays are found in your CASA data repository, 
00088          os.getenv("CASAPATH").split()[0]+"/data/alma/simmos/"        
00089        * a string of the form "alma;0.5arcsec" will be parsed into a full 12m ALMA
00090          configuration.  This only works for full ALMA and may fail to find the 
00091          standard configuration files on some systems - see casaguides.nrao.edu
00092     hourangle -- hour angle of observation e.g. '-3h'
00093     totaltime --- total time of observation e.g '7200s' or if a number without
00094          units, interpreted as the number of times to repeat the map
00095     acaratio  --- ratio of the total observation time of ACA relative to 
00096          that of 12m array. Set 0 for no ACA observation. 
00097          For Cycle-1, set acaratio = 0 or 3.
00098     acaconfig --- ACA configuration. Available configurations are:
00099        * "" (default) : automatically defines based on antennalist. 
00100                If antennalist is Cycle-1 configuration, acaconfig='cycle1'.
00101                Otherwise, acaconfig='i'
00102        * 'cycle1' : Cycle-1 ACA-7m configuration. Uses 'aca_cycle1.cfg'.
00103        * "i" : Normal ACA configuration in full operation. Uses 'aca.i.cfg'.
00104        * "ns": North-South extended configuration in full operation. 
00105                Uses 'aca.ns.cfg'.
00106     -------------------------------
00107     pwv -- precipitable water vapor if constructing an atmospheric model.
00108          Set 0 for noise-free simulation. When pwv > 0, thermal noise is
00109          applied to the simulated data.
00110        * J. Pardo's ATM library will be used to construct anatmospheric
00111          profile for the ALMA site:
00112          altitude 5000m, ground pressure 650mbar, relhum=20%, 
00113          a water layer of user_pwv at altitude of 2km,
00114          the sky brightness temperature returned by ATM, and internally
00115          tabulated receiver temperatures.
00116        See the documents of simobserve for more details.
00117     -------------------------------
00118     image -- invert and deconvolve the simulated measurement set(s)
00119        * NOTE: interactive clean or more parameters than the subset visible
00120          here are available by simply running the clean task directly.
00121        * NOTE: the channelization of the output image cube will be the 
00122          same as that in the simulated Measurement Set.
00123        * if graphics turned on, display the clean image and residual image
00124        * uses Cotton-Schwab clean for single fields and Mosaic gridding
00125          for multiple fields (with Clark PSF calculation in minor cycles).
00126     imsize -- image size in spatial pixels (x,y)
00127        0 or -1 will use the model image size; example: imsize=[500,500]
00128     imdirection -- phase center for synthesized image.  default is to 
00129        center on the sky model.
00130     cell -- cell size e.g '10arcsec'.  "" defaults to the skymodel cell
00131     niter -- number of clean/deconvolution iterations, 0 for no cleaning
00132     threshold -- flux level to stop cleaning
00133     -------------------------------
00134     graphics -- view plots on the screen, saved to file, both, or neither
00135     verbose -- print extra information to the logger and terminal
00136     overwrite -- overwrite existing files in the project subdirectory
00137 
00138     -------------------------------
00139     What does this task do:
00140     -------------------------------
00141     simalma is a task to simulate ALMA observation with simple interface. 
00142     It simulates ALMA 12m observation and optionally ACA 7m and Total power
00143     observations when acaratio > 0. 
00144     When image=True, simulated data are imaged and analyzed. CLEAN is used
00145     to generate image(s) from simulated data. ALMA 12m and ACA data are
00146     combined (if both geneareted) by taking ACA image as an initial model
00147     in CLEAN of ALMA 12m data.
00148     NOTE this task is very experimental and may not exactly reproduce
00149     actual ALMA products.
00150 
00151     The following assumptions are made to make the interface simple:
00152     * This task is intended to be run only once with a set of parameters.
00153       Therefore, it always sets up input model and pointings, and invokes simulation.
00154       You can stop before imaging step and reduce data manually with the other tasks,
00155       e.g, simanalyze, clean, and feather.
00156     * acaratio controls whether or not ACA observation is simulated. if acaratio > 0,
00157       ACA observation is simulated with total observation time = acaratio * totaltime
00158       for both ACA 7m and Total power array.
00159     * pwv controls whether or not thermal noise is applied to simulated data.
00160       When pwv > 0, the thermal noise is applied to simulated data. J. Pardo's ATM
00161       library is used to construct an atmospheric profile of the ALMA site.
00162     * if a list of directions is not specified, ALMA 12m and ACA 7m arrays will
00163       pack mapsize with the same hex algorithm as the ALMA OT in Nyquist sampling
00164     * Total power array maps slightly (+1 PB) larger area compared to 12m array for
00165       later combined imaging. It samples the region with lattice grids of spacing, 
00166       0.36 lamba/d.
00167 
00168     -------------------------------
00169     How to specify a model image:
00170     -------------------------------
00171     * simalma requires a CASA or fits image. If you merely have a grid of 
00172       numbers, you will need to write them out as fits or write a CASA script to
00173       read them in and use the ia tool to create an image and insert the data.
00174     
00175     * simalma does NOT require a coordinate system in the header. If the
00176       coordinate information is incomplete, missing, or you would like to
00177       override it, set the appropriate "in" paremeters.  
00178       In the absence of other information, simalma will assume that the axes of 
00179       your input correspond to RA, Dec, and (optionally) frequency and 
00180       (optionally) Stokes parameter.  
00181 
00182     * If you have a proper Coordinate System, simalma will do its best to
00183       generate visibilities from that, and then create a synthesis image
00184       according to the specified user parameters.  Regridding the
00185       spectral dimension may not have complete flexibility yet.
00186 
00187     * You can manipulate an image header with the "imhead" task.
00188 
00189 
00190     Please see the documents of simobserve and simanalyze for
00191     the list of outputs produced.
00192 
00193 
00194         """
00195         a=inspect.stack()
00196         stacklevel=0
00197         for k in range(len(a)):
00198           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00199                 stacklevel=k
00200                 break
00201         myf=sys._getframe(stacklevel).f_globals
00202         myf['__last_task'] = 'simalma'
00203         myf['taskname'] = 'simalma'
00204         ###
00205         myf['update_params'](func=myf['taskname'],printtext=False)
00206         ###
00207         ###
00208         #Handle globals or user over-ride of arguments
00209         #
00210         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00211         useLocalDefaults = False
00212 
00213         for item in function_signature_defaults.iteritems():
00214                 key,val = item
00215                 keyVal = eval(key)
00216                 if (keyVal == None):
00217                         #user hasn't set it - use global/default
00218                         pass
00219                 else:
00220                         #user has set it - use over-ride
00221                         if (key != 'self') :
00222                            useLocalDefaults = True
00223                         #myf[key]=keyVal
00224 
00225         myparams = {}
00226         if useLocalDefaults :
00227            for item in function_signature_defaults.iteritems():
00228                key,val = item
00229                keyVal = eval(key)
00230                exec('myparams[key] = keyVal')
00231                if (keyVal == None):
00232                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00233                    keyVal = eval(key)
00234                    if(type(keyVal) == dict) :
00235                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00236 
00237         else :
00238             uselessvariable = None 
00239             myparams['project'] = project = myf['project']
00240             myparams['skymodel'] = skymodel = myf['skymodel']
00241             myparams['inbright'] = inbright = myf['inbright']
00242             myparams['indirection'] = indirection = myf['indirection']
00243             myparams['incell'] = incell = myf['incell']
00244             myparams['incenter'] = incenter = myf['incenter']
00245             myparams['inwidth'] = inwidth = myf['inwidth']
00246             myparams['complist'] = complist = myf['complist']
00247             myparams['compwidth'] = compwidth = myf['compwidth']
00248             myparams['setpointings'] = setpointings = myf['setpointings']
00249             myparams['ptgfile'] = ptgfile = myf['ptgfile']
00250             myparams['integration'] = integration = myf['integration']
00251             myparams['direction'] = direction = myf['direction']
00252             myparams['mapsize'] = mapsize = myf['mapsize']
00253             myparams['antennalist'] = antennalist = myf['antennalist']
00254             myparams['hourangle'] = hourangle = myf['hourangle']
00255             myparams['totaltime'] = totaltime = myf['totaltime']
00256             myparams['acaratio'] = acaratio = myf['acaratio']
00257             myparams['acaconfig'] = acaconfig = myf['acaconfig']
00258             myparams['pwv'] = pwv = myf['pwv']
00259             myparams['image'] = image = myf['image']
00260             myparams['imsize'] = imsize = myf['imsize']
00261             myparams['imdirection'] = imdirection = myf['imdirection']
00262             myparams['cell'] = cell = myf['cell']
00263             myparams['niter'] = niter = myf['niter']
00264             myparams['threshold'] = threshold = myf['threshold']
00265             myparams['graphics'] = graphics = myf['graphics']
00266             myparams['verbose'] = verbose = myf['verbose']
00267             myparams['overwrite'] = overwrite = myf['overwrite']
00268 
00269         if type(direction)==str: direction=[direction]
00270         if type(mapsize)==str: mapsize=[mapsize]
00271         if type(imsize)==int: imsize=[imsize]
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['project'] = project
00281         mytmp['skymodel'] = skymodel
00282         mytmp['inbright'] = inbright
00283         mytmp['indirection'] = indirection
00284         mytmp['incell'] = incell
00285         mytmp['incenter'] = incenter
00286         mytmp['inwidth'] = inwidth
00287         mytmp['complist'] = complist
00288         mytmp['compwidth'] = compwidth
00289         mytmp['setpointings'] = setpointings
00290         mytmp['ptgfile'] = ptgfile
00291         mytmp['integration'] = integration
00292         mytmp['direction'] = direction
00293         mytmp['mapsize'] = mapsize
00294         mytmp['antennalist'] = antennalist
00295         mytmp['hourangle'] = hourangle
00296         mytmp['totaltime'] = totaltime
00297         mytmp['acaratio'] = acaratio
00298         mytmp['acaconfig'] = acaconfig
00299         mytmp['pwv'] = pwv
00300         mytmp['image'] = image
00301         mytmp['imsize'] = imsize
00302         mytmp['imdirection'] = imdirection
00303         mytmp['cell'] = cell
00304         mytmp['niter'] = niter
00305         mytmp['threshold'] = threshold
00306         mytmp['graphics'] = graphics
00307         mytmp['verbose'] = verbose
00308         mytmp['overwrite'] = overwrite
00309         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00310         trec = casac.utils().torecord(pathname+'simalma.xml')
00311 
00312         casalog.origin('simalma')
00313         if not trec.has_key('simalma') or not casac.utils().verify(mytmp, trec['simalma']) :
00314             return False
00315 
00316 
00317         try :
00318           casalog.post('')
00319           casalog.post('##########################################')
00320           casalog.post('##### Begin Task: simalma           #####')
00321           casalog.post('')
00322           result = simalma(project, skymodel, inbright, indirection, incell, incenter, inwidth, complist, compwidth, setpointings, ptgfile, integration, direction, mapsize, antennalist, hourangle, totaltime, acaratio, acaconfig, pwv, image, imsize, imdirection, cell, niter, threshold, graphics, verbose, overwrite)
00323           casalog.post('')
00324           casalog.post('##### End Task: simalma           #####')
00325           casalog.post('##########################################')
00326 
00327 
00328 # saveinputs for individule engine has no use
00329 # saveinputs should alos be removed from casa_in_py.py
00330 #
00331 #
00332 #          saveinputs = myf['saveinputs']
00333 #          saveinputs('simalma', 'simalma.last', myparams)
00334 #
00335 #
00336         except Exception, instance:
00337           #print '**** Error **** ',instance
00338           pass
00339 
00340         gc.collect()
00341         return result
00342 #
00343 #
00344 ##
00345 #    def paramgui(self, useGlobals=True):
00346 #        """
00347 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00348 #        """
00349 #        import paramgui
00350 #
00351 #        a=inspect.stack()
00352 #        stacklevel=0
00353 #        for k in range(len(a)):
00354 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00355 #            stacklevel=k
00356 #            break
00357 #        myf = sys._getframe(stacklevel).f_globals
00358 #
00359 #        if useGlobals:
00360 #            paramgui.setGlobals(myf)
00361 #        else:
00362 #            paramgui.setGlobals({})
00363 #
00364 #        paramgui.runTask('simalma', myf['_ip'])
00365 #        paramgui.setGlobals({})
00366 #
00367 #
00368 #
00369 #
00370     def defaults(self, param=None):
00371         a=inspect.stack()
00372         stacklevel=0
00373         for k in range(len(a)):
00374           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00375                 stacklevel=k
00376                 break
00377         myf=sys._getframe(stacklevel).f_globals
00378         a = odict()
00379         a['project']  = 'sim'
00380         a['skymodel']  = ''
00381         a['complist']  = ''
00382         a['setpointings']  = True
00383         a['antennalist']  = 'alma_cycle1_1.cfg'
00384         a['hourangle']  = 'transit'
00385         a['totaltime']  = '7200s'
00386         a['acaratio']  = 0.0
00387         a['pwv']  = 0.0
00388         a['image']  = True
00389         a['graphics']  = 'both'
00390         a['verbose']  = False
00391         a['overwrite']  = False
00392 
00393         a['async']=False
00394         a['skymodel'] = {
00395                     0:odict([{'notvalue':''}, {'inbright':''}, {'indirection':''}, {'incell':''}, {'incenter':''}, {'inwidth':''}])}
00396         a['complist'] = {
00397                     0:odict([{'notvalue':''}, {'compwidth':'8GHz'}])}
00398         a['setpointings'] = {
00399                     0:odict([{'value':True}, {'integration':'10s'}, {'direction':''}, {'mapsize':['', '']}]), 
00400                     1:odict([{'value':False}, {'ptgfile':'$project.ptg.txt'}, {'integration':'10s'}])}
00401         a['acaratio'] = {
00402                     0:odict([{'notvalue':0}, {'acaconfig':''}])}
00403         a['image'] = {
00404                     0:odict([{'value':True}, {'imsize':0}, {'imdirection':''}, {'cell':''}, {'niter':500}, {'threshold':'0.1mJy'}]), 
00405                     1:{'value':False}}
00406 
00407 ### This function sets the default values but also will return the list of
00408 ### parameters or the default value of a given parameter
00409         if(param == None):
00410                 myf['__set_default_parameters'](a)
00411         elif(param == 'paramkeys'):
00412                 return a.keys()
00413         else:
00414                 if(a.has_key(param)):
00415                    #if(type(a[param]) == dict) :
00416                    #   return a[param][len(a[param])-1]['value']
00417                    #else :
00418                       return a[param]
00419 
00420 
00421 #
00422 #
00423     def check_params(self, param=None, value=None):
00424       a=inspect.stack() 
00425       stacklevel=0
00426       for k in range(len(a)):
00427         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00428             stacklevel=k
00429             break
00430       myf=sys._getframe(stacklevel).f_globals
00431 
00432 #      print 'param:', param, 'value:', value
00433       try :
00434          if str(type(value)) != "<type 'instance'>" :
00435             value0 = value
00436             value = myf['cu'].expandparam(param, value)
00437             matchtype = False
00438             if(type(value) == numpy.ndarray):
00439                if(type(value) == type(value0)):
00440                   myf[param] = value.tolist()
00441                else:
00442                   #print 'value:', value, 'value0:', value0
00443                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00444                   myf[param] = value0
00445                   if type(value0) != list :
00446                      matchtype = True
00447             else :
00448                myf[param] = value
00449             value = myf['cu'].verifyparam({param:value})
00450             if matchtype:
00451                value = False
00452       except Exception, instance:
00453          #ignore the exception and just return it unchecked
00454          myf[param] = value
00455       return value
00456 
00457 #
00458 #
00459     def description(self, key='simalma', subkey=None):
00460         desc={'simalma': '(Experimental) simple simulation task for ALMA ',
00461                'project': 'root prefix for output file names',
00462                'skymodel': 'model image to observe',
00463                'inbright': 'scale surface brightness of brightest pixel e.g. "1.2Jy/pixel"',
00464                'indirection': 'set new direction e.g. "J2000 19h00m00 -40d00m00"',
00465                'incell': 'set new cell/pixel size e.g. "0.1arcsec"',
00466                'incenter': 'set new frequency of center channel e.g. "89GHz" (required even for 2D model)',
00467                'inwidth': 'set new channel width e.g. "10MHz" (required even for 2D model)',
00468                'complist': 'componentlist to observe',
00469                'compwidth': 'bandwidth of components',
00470                'setpointings': '',
00471                'ptgfile': 'list of pointing positions',
00472                'integration': 'integration (sampling) time',
00473                'direction': '"J2000 19h00m00 -40d00m00" or "" to center on model',
00474                'mapsize': 'angular size of map or "" to cover model',
00475                'antennalist': 'antenna position file of ALMA 12m array',
00476                'hourangle': 'hour angle of observation center e.g. -3:00:00, or "transit"',
00477                'totaltime': 'total time of observation or number of repetitions',
00478                'acaratio': 'Ratio of the total observation time for ACA in relation to 12-m array or 0 for no ACA',
00479                'acaconfig': 'Antenna configuration of ACA 7-m array [""|"cycle1"|"i"|"ns"]',
00480                'pwv': 'Precipitable Water Vapor in mm. 0 for noise-free simulation',
00481                'image': 'image simulated data',
00482                'imsize': 'output image size in pixels (x,y) or 0 to match model',
00483                'imdirection': 'set output image direction, (otherwise center on the model)',
00484                'cell': 'cell size with units or "" to equal model',
00485                'niter': 'maximum number of iterations (0 for dirty image)',
00486                'threshold': 'flux level (+units) to stop cleaning',
00487                'graphics': 'display graphics at each stage to [screen|file|both|none]',
00488                'verbose': '',
00489                'overwrite': 'overwrite files starting with $project',
00490 
00491                'async': 'If true the taskname must be started using simalma(...)'
00492               }
00493 
00494 #
00495 # Set subfields defaults if needed
00496 #
00497         if(subkey == 'True'):
00498           desc['direction'] = 'center of map or "" to center on the model'
00499         if(subkey == 'False'):
00500           desc['integration'] = 'integration time (see below)'
00501 
00502         if(desc.has_key(key)) :
00503            return desc[key]
00504 
00505     def itsdefault(self, paramname) :
00506         a = {}
00507         a['project']  = 'sim'
00508         a['skymodel']  = ''
00509         a['inbright']  = ''
00510         a['indirection']  = ''
00511         a['incell']  = ''
00512         a['incenter']  = ''
00513         a['inwidth']  = ''
00514         a['complist']  = ''
00515         a['compwidth']  = '"8GHz"'
00516         a['setpointings']  = True
00517         a['ptgfile']  = '$project.ptg.txt'
00518         a['integration']  = '10s'
00519         a['direction']  = ['']
00520         a['mapsize']  = ['', '']
00521         a['antennalist']  = 'alma_cycle1_1.cfg'
00522         a['hourangle']  = 'transit'
00523         a['totaltime']  = '7200s'
00524         a['acaratio']  = 0.0
00525         a['acaconfig']  = ''
00526         a['pwv']  = 0.0
00527         a['image']  = True
00528         a['imsize']  = [128, 128]
00529         a['imdirection']  = ''
00530         a['cell']  = ''
00531         a['niter']  = 500
00532         a['threshold']  = '0.1mJy'
00533         a['graphics']  = 'both'
00534         a['verbose']  = False
00535         a['overwrite']  = False
00536 
00537         if a.has_key(paramname) :
00538               return a[paramname]
00539 simalma_pg = simalma_pg_()