casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
simobserve_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_simobserve import simobserve
00018 class simobserve_cli_:
00019     __name__ = "simobserve"
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__ = (simobserve_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'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, 'maptype':None, 'pointingspacing':None, 'caldirection':None, 'calflux':None, 'obsmode':None, 'refdate':None, 'hourangle':None, 'totaltime':None, 'antennalist':None, 'sdantlist':None, 'sdant':None, 'thermalnoise':None, 'user_pwv':None, 't_ground':None, 't_sky':None, 'tau0':None, 'seed':None, 'leakage':None, 'graphics':None, 'verbose':None, 'overwrite':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, 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, maptype=None, pointingspacing=None, caldirection=None, calflux=None, obsmode=None, refdate=None, hourangle=None, totaltime=None, antennalist=None, sdantlist=None, sdant=None, thermalnoise=None, user_pwv=None, t_ground=None, t_sky=None, tau0=None, seed=None, leakage=None, graphics=None, verbose=None, overwrite=None,  async=None):
00047 
00048         """mosaic simulation task
00049 mosaic simulation task:
00050 
00051     This task simulates interferometric observations (currently 
00052     only ALMA can be done easily).  New functionality is actively 
00053     being added, so if you have changed versions of CASA, check 
00054     the inputs carefully.
00055     More information and examples are availible at 
00056      http://casaguides.nrao.edu/index.php?title=Simulating_Observations_in_CASA
00057     Please contact CASA experts with any questions, especially 
00058     about features noted below as *experimental*    
00059     -------------------------------
00060     project -- root filename for all output files.
00061     -------------------------------
00062     skymodel -- image model of the sky in FITS or CASA image, 
00063          with optional parameters that can be overridden
00064     inbright -- peak brightness in Jy/pixel, or "" for unchanged
00065        * NOTE: "unchanged" will take the numerical values in your image 
00066          and assume they are in Jy/pixel, even if it says some other unit 
00067          in the header. 
00068     indirection -- central direction, or "" for unchanged
00069     incell -- spatial pixel size, or "" for unchanged
00070     incenter -- frequency of center channel e.g. "89GHz", or "" for unchanged
00071     inwidth -- width of channels, or "" for unchanged - this should be a 
00072          string representing a quantity with units e.g. "10MHz"
00073        * NOTE: only works reliably with frequencies, not velocities
00074        * NOTE: it is not possible to change the number of spectral planes
00075          of the sky model, only to relabel them with different frequencies
00076          That kind of regridding can be accomplished with the CASA toolkit.
00077     -------------------------------
00078     complist -- component list model of the sky, added to or instead of skymodel
00079     compwidth -- bandwidth of components; if simulating from components only, 
00080          this defines the bandwidth of the MS and output images
00081     -------------------------------
00082     setpointings -- calculate a map of pointings, or if false, provide ptgfile
00083        * if graphics are on, display the pointings shown on the model image
00084     ptgfile -- a text file specifying directions in the following
00085          format, with optional integration times, e.g.
00086          #Epoch     RA          DEC      TIME(optional)
00087          J2000 23h59m28.10 -019d52m12.35 10.0
00088        * if the time column is not present in the file, it will use
00089          "integration" for all pointings.
00090        * NOTE: at this time the file should contain only science pointings:
00091          simobserve will observe these, then optionally the calibrator, 
00092          then the list of science pointings again, etc, until totaltime
00093          is used up. 
00094     integration --- Time interval for each integration e.g '10s'
00095        * NOTE: to simulate a "scan" longer than one integration, use 
00096          setpointings to generate a pointing file, and then edit the 
00097          file to increase the time at each point to be larger than 
00098          the parameter integration time.
00099     direction -- mosaic center direction e.g 'J2000 19h00m00 -40d00m00'
00100        * can optionally be a list of pointings
00101        * otherwise simobserve will pack mapsize according to maptype
00102     mapsize -- angular size of map 
00103        * set to "" to span the model image
00104     maptype -- hexagonal, square (rectangular raster), 
00105          "ALMA" for the same hex algorithm as the ALMA OT 
00106          or "ALMA2012" for the algorithm used in the Cycle 0 OT
00107     pointingspacing -- spacing in between beams e.g '1arcsec'
00108          or "0.25PB" to use 1/4 of the primary beam FWHM, or 
00109          "" will use Nyquist spacing, lambda/d/sqrt(3).
00110     -------------------------------
00111     obsmode -- observation mode to calculate visibilities from skymodel (which
00112          may have been modified above, (optionally) complist, and $ptgfile (which 
00113          may have been generated above)
00114        * this parameter takes two possible values:
00115        - interferometer (or i)
00116        - singledish (or s)
00117        * if graphics are on, display the array (like plotants), the uv 
00118          coverage, the synthesized (dirty) beam, and ephemeris information
00119        * if simulating from component list, you should specify
00120          compwidth, the desired bandwidth - 
00121          there is not currently a way to specify the spectrum of a component, 
00122          so simulations from a componentlist only will be continuum (1 chan)
00123     refdate -- date of simulated observation eg: '2014/05/21'
00124     hourangle -- hour angle of observation e.g. '-3h'
00125     totaltime --- total time of observation e.g '7200s' or if a number without
00126          units, interpreted as the number of times to repeat the map
00127     antennalist -- ascii file containing antenna positions.
00128          each row has x y z coordinates and antenna diameter; 
00129          header lines are required to specify the observatory name
00130          and coordinate system e.g. 
00131            # observatory=ALMA
00132            # coordsys=UTM
00133            # datum=WGS84
00134            # zone=19
00135        * standard arrays are found in your CASA data repository, 
00136          os.getenv("CASAPATH").split()[0]+"/data/alma/simmos/"        
00137        * if "", will not not produce an interferometric MS
00138        * a string of the form "alma;0.5arcsec" will be parsed into a full 12m ALMA
00139          configuration.  This only works for full ALMA and may fail to find the 
00140          standard configuration files on some systems - see casaguides.nrao.edu
00141     caldirection -- *NEW* an unresolved calibrator can be observed 
00142          interleaved with the science pointings.  This feature is 
00143          experimental, so please contact us with any questions.
00144        * The calibrator is implemented as a point source clean component 
00145          with this direction and flux=calflux
00146     sdant -- the index of the antenna in the list to use for total 
00147          power.  defaults to the first antenna on the list. 
00148     -------------------------------
00149     thermalnoise -- add thermal noise 
00150        * this parameter takes two possible values:
00151        - tsys-atm: J. Pardo's ATM library will be used to construct an
00152            atmospheric profile for the ALMA site:
00153            altitude 5000m, ground pressure 650mbar, relhum=20%, 
00154            a water layer of user_pwv at altitude of 2km,
00155            the sky brightness temperature returned by ATM, 
00156            and internally tabulated receiver temperatures
00157        - tsys-manual: instead of using the ATM model, specify the zenith 
00158            sky brightness and opacity manually.  Noise is added and then
00159            the visibility flux scale is referenced above the atmosphere. 
00160        * In either mode, noise is calculated using an antenna spillover 
00161            efficiency of 0.96, taper of 0.86, 
00162            surface accuracy of 25 and 300 microns for ALMA and EVLA
00163            respectively (using the Ruze formula for surface efficiency),
00164            correlator efficiencies of 0.95 and 0.91 for ALMA and EVLA, 
00165            receiver temperatures for ALMA of 
00166                17, 30, 37, 51, 65, 83,147,196,175,230 K interpolated between
00167                35, 75,110,145,185,230,345,409,675,867 GHz,
00168            for EVLA of 
00169                500, 70,  60,  55,  100, 130, 350 K interpolated between
00170                0.33,1.47,4.89,8.44,22.5,33.5,43.3 GHz,
00171            for SMA of
00172                67,  116, 134, 500 K interpolated between
00173                212.,310.,383.,660. GHz
00174        * These are only approximate numbers and do not take into account 
00175          performance at edges of receiver bands, neither are they guaranteed
00176          to reflect the most recent measurements.  Caveat emptor and use the 
00177          sm tool to add noise if you want more precise control.
00178     t_ground -- ground/spillover temperature in K 
00179     user_pwv -- precipitable water vapor if constructing an atmospheric model
00180     t_sky -- atmospheric temperature in K [for tsys-manual]
00181     tau0 -- zenith opacity at observing frequency [for tsys-manual]
00182        * see casaguides.nrao.edu for more information on noise, 
00183          in particular how to add a phase screen using the toolkit
00184     seed -- random number seed for noise generation
00185     -------------------------------
00186     leakage -- add cross polarization corruption of this fractional magnitude
00187     
00188     graphics -- view plots on the screen, saved to file, both, or neither
00189     verbose -- print extra information to the logger and terminal
00190     overwrite -- overwrite existing files in the project subdirectory
00191 
00192 
00193 
00194     -------------------------------
00195     How to specify a model image:
00196     -------------------------------
00197     * simobserve requires a CASA or fits image. If you merely have a grid of 
00198       numbers, you will need to write them out as fits or write a CASA script to
00199       read them in and use the ia tool to create an image and insert the data.
00200     
00201     * simobserve does NOT require a coordinate system in the header. If the
00202       coordinate information is incomplete, missing, or you would like to
00203       override it, set the appropriate "in" paremeters.  
00204       In the absence of other information, simobserve will assume that the axes of 
00205       your input correspond to RA, Dec, and (optionally) frequency and 
00206       (optionally) Stokes parameter.  
00207 
00208     * If you have a proper Coordinate System, simobserve will do its best to
00209       generate visibilities from that, and then create a synthesis image
00210       according to the specified user parameters.  Regridding the
00211       spectral dimension may not have complete flexibility yet.
00212 
00213     * You can manipulate an image header with the "imhead" task, or you can
00214       delve deeper with the ia and cs tools.  If you use the tools, you should
00215       be aware that a CoordinateSystem in CASA can exist independently of an
00216       Image.  Once the CoordinateSystem is detached from the image, it is the
00217       user's responsibility to do any manipulation e.g. axis reordering on
00218       both. Example:
00219         ia.open("myimage_filename")
00220         ia.summary() # see header as attached to the image
00221         csys=ia.coordsys() # detach the CoordinateSystem
00222         csys.summary() # examine it
00223         csys.setreferencepixel([100,100]) 
00224         arr=ia.getchunk() # get the data from the Image
00225         ia.done()
00226         csys.reorder([0,2,1])  # reorder the CoordinateSystem
00227         arr=arr.reorder([0,2,1])  # reorder the data         
00228         ia.fromshape(outfile="mynewimage_file",shape=[32,32,256],csys=csys.torecord(),overwrite=True)
00229             # make a new image, with the right shape and CoordinateSystem
00230         ia.putchunk(arr)   # put the data into the new image.
00231         csys.done()
00232         ia.done()
00233 
00234     -------------------------------
00235     Output produced: (not all will always exist, depending on input parameters)
00236     To support different runs with different arrays, the names have the
00237     configuration name from antennalist appended.
00238     -------------------------------
00239 
00240     project.[cfg].skymodel = 4d input sky model image (optionally) scaled
00241     project.[cfg].skymodel.flat.regrid.conv = input sky regridded to match the
00242         output image, and convolved with the output clean beam
00243     project.[cfg].skymodel.png = diagnostic figure of sky model with pointings
00244 
00245     project.[cfg].ptg.txt = list of mosaic pointings
00246     project.[cfg].quick.psf = psf calculated from uv coverage
00247     project.[cfg].ms = noise-free measurement set
00248     project.[cfg].noisy.ms = corrupted measurement set 
00249     project.[cfg].observe.png = diagnostic figure of uv coverage and 
00250          visibilities
00251             
00252     project.[cfg].simobserve.last = saved input parameters for simobserve task
00253 
00254 
00255         """
00256         if not hasattr(self, "__globals__") or self.__globals__ == None :
00257            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00258         #casac = self.__globals__['casac']
00259         casalog = self.__globals__['casalog']
00260         #casalog = casac.casac.logsink()
00261         self.__globals__['__last_task'] = 'simobserve'
00262         self.__globals__['taskname'] = 'simobserve'
00263         ###
00264         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00265         ###
00266         ###
00267         #Handle globals or user over-ride of arguments
00268         #
00269         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00270         useLocalDefaults = False
00271 
00272         for item in function_signature_defaults.iteritems():
00273                 key,val = item
00274                 keyVal = eval(key)
00275                 if (keyVal == None):
00276                         #user hasn't set it - use global/default
00277                         pass
00278                 else:
00279                         #user has set it - use over-ride
00280                         if (key != 'self') :
00281                            useLocalDefaults = True
00282 
00283         myparams = {}
00284         if useLocalDefaults :
00285            for item in function_signature_defaults.iteritems():
00286                key,val = item
00287                keyVal = eval(key)
00288                exec('myparams[key] = keyVal')
00289                self.parameters[key] = keyVal
00290                if (keyVal == None):
00291                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00292                    keyVal = eval(key)
00293                    if(type(keyVal) == dict) :
00294                       if len(keyVal) > 0 :
00295                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00296                       else :
00297                          exec('myparams[key] = ' + key + ' = {}')
00298 
00299         else :
00300             async = self.parameters['async']
00301             myparams['project'] = project = self.parameters['project']
00302             myparams['skymodel'] = skymodel = self.parameters['skymodel']
00303             myparams['inbright'] = inbright = self.parameters['inbright']
00304             myparams['indirection'] = indirection = self.parameters['indirection']
00305             myparams['incell'] = incell = self.parameters['incell']
00306             myparams['incenter'] = incenter = self.parameters['incenter']
00307             myparams['inwidth'] = inwidth = self.parameters['inwidth']
00308             myparams['complist'] = complist = self.parameters['complist']
00309             myparams['compwidth'] = compwidth = self.parameters['compwidth']
00310             myparams['setpointings'] = setpointings = self.parameters['setpointings']
00311             myparams['ptgfile'] = ptgfile = self.parameters['ptgfile']
00312             myparams['integration'] = integration = self.parameters['integration']
00313             myparams['direction'] = direction = self.parameters['direction']
00314             myparams['mapsize'] = mapsize = self.parameters['mapsize']
00315             myparams['maptype'] = maptype = self.parameters['maptype']
00316             myparams['pointingspacing'] = pointingspacing = self.parameters['pointingspacing']
00317             myparams['caldirection'] = caldirection = self.parameters['caldirection']
00318             myparams['calflux'] = calflux = self.parameters['calflux']
00319             myparams['obsmode'] = obsmode = self.parameters['obsmode']
00320             myparams['refdate'] = refdate = self.parameters['refdate']
00321             myparams['hourangle'] = hourangle = self.parameters['hourangle']
00322             myparams['totaltime'] = totaltime = self.parameters['totaltime']
00323             myparams['antennalist'] = antennalist = self.parameters['antennalist']
00324             myparams['sdantlist'] = sdantlist = self.parameters['sdantlist']
00325             myparams['sdant'] = sdant = self.parameters['sdant']
00326             myparams['thermalnoise'] = thermalnoise = self.parameters['thermalnoise']
00327             myparams['user_pwv'] = user_pwv = self.parameters['user_pwv']
00328             myparams['t_ground'] = t_ground = self.parameters['t_ground']
00329             myparams['t_sky'] = t_sky = self.parameters['t_sky']
00330             myparams['tau0'] = tau0 = self.parameters['tau0']
00331             myparams['seed'] = seed = self.parameters['seed']
00332             myparams['leakage'] = leakage = self.parameters['leakage']
00333             myparams['graphics'] = graphics = self.parameters['graphics']
00334             myparams['verbose'] = verbose = self.parameters['verbose']
00335             myparams['overwrite'] = overwrite = self.parameters['overwrite']
00336 
00337         if type(direction)==str: direction=[direction]
00338         if type(mapsize)==str: mapsize=[mapsize]
00339 
00340         result = None
00341 
00342 #
00343 #    The following is work around to avoid a bug with current python translation
00344 #
00345         mytmp = {}
00346 
00347         mytmp['project'] = project
00348         mytmp['skymodel'] = skymodel
00349         mytmp['inbright'] = inbright
00350         mytmp['indirection'] = indirection
00351         mytmp['incell'] = incell
00352         mytmp['incenter'] = incenter
00353         mytmp['inwidth'] = inwidth
00354         mytmp['complist'] = complist
00355         mytmp['compwidth'] = compwidth
00356         mytmp['setpointings'] = setpointings
00357         mytmp['ptgfile'] = ptgfile
00358         mytmp['integration'] = integration
00359         mytmp['direction'] = direction
00360         mytmp['mapsize'] = mapsize
00361         mytmp['maptype'] = maptype
00362         mytmp['pointingspacing'] = pointingspacing
00363         mytmp['caldirection'] = caldirection
00364         mytmp['calflux'] = calflux
00365         mytmp['obsmode'] = obsmode
00366         mytmp['refdate'] = refdate
00367         mytmp['hourangle'] = hourangle
00368         mytmp['totaltime'] = totaltime
00369         mytmp['antennalist'] = antennalist
00370         mytmp['sdantlist'] = sdantlist
00371         mytmp['sdant'] = sdant
00372         mytmp['thermalnoise'] = thermalnoise
00373         mytmp['user_pwv'] = user_pwv
00374         mytmp['t_ground'] = t_ground
00375         mytmp['t_sky'] = t_sky
00376         mytmp['tau0'] = tau0
00377         mytmp['seed'] = seed
00378         mytmp['leakage'] = leakage
00379         mytmp['graphics'] = graphics
00380         mytmp['verbose'] = verbose
00381         mytmp['overwrite'] = overwrite
00382         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00383         trec = casac.casac.utils().torecord(pathname+'simobserve.xml')
00384 
00385         casalog.origin('simobserve')
00386         try :
00387           #if not trec.has_key('simobserve') or not casac.casac.utils().verify(mytmp, trec['simobserve']) :
00388             #return False
00389 
00390           casac.casac.utils().verify(mytmp, trec['simobserve'], True)
00391           scriptstr=['']
00392           saveinputs = self.__globals__['saveinputs']
00393           saveinputs('simobserve', 'simobserve.last', myparams, self.__globals__,scriptstr=scriptstr)
00394           if async :
00395             count = 0
00396             keybase =  time.strftime("%y%m%d.%H%M%S")
00397             key = keybase + "_" + str(count)
00398             while self.__async__.has_key(key) :
00399                count += 1
00400                key = keybase + "_" + str(count)
00401             result = tm.execute('simobserve', project, skymodel, inbright, indirection, incell, incenter, inwidth, complist, compwidth, setpointings, ptgfile, integration, direction, mapsize, maptype, pointingspacing, caldirection, calflux, obsmode, refdate, hourangle, totaltime, antennalist, sdantlist, sdant, thermalnoise, user_pwv, t_ground, t_sky, tau0, seed, leakage, graphics, verbose, overwrite)
00402             print "Use: "
00403             print "      tm.retrieve(return_value) # to retrieve the status"
00404             print 
00405             self.rkey = key
00406             self.__async__[key] = result
00407           else :
00408               tname = 'simobserve'
00409               spaces = ' '*(18-len(tname))
00410               casalog.post('\n##########################################'+
00411                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00412               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00413               result = simobserve(project, skymodel, inbright, indirection, incell, incenter, inwidth, complist, compwidth, setpointings, ptgfile, integration, direction, mapsize, maptype, pointingspacing, caldirection, calflux, obsmode, refdate, hourangle, totaltime, antennalist, sdantlist, sdant, thermalnoise, user_pwv, t_ground, t_sky, tau0, seed, leakage, graphics, verbose, overwrite)
00414               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00415                            '\n##########################################')
00416 
00417         except Exception, instance:
00418           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00419              raise
00420           else :
00421              #print '**** Error **** ',instance
00422              tname = 'simobserve'
00423              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00424              pass
00425 
00426         gc.collect()
00427         return result
00428 #
00429 #
00430 #
00431     def paramgui(self, useGlobals=True, ipython_globals=None):
00432         """
00433         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00434         """
00435         import paramgui
00436         if not hasattr(self, "__globals__") or self.__globals__ == None :
00437            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00438 
00439         if useGlobals:
00440             if ipython_globals == None:
00441                 myf=self.__globals__
00442             else:
00443                 myf=ipython_globals
00444 
00445             paramgui.setGlobals(myf)
00446         else:
00447             paramgui.setGlobals({})
00448 
00449         paramgui.runTask('simobserve', myf['_ip'])
00450         paramgui.setGlobals({})
00451 
00452 #
00453 #
00454 #
00455     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00456         if not hasattr(self, "__globals__") or self.__globals__ == None :
00457            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00458         if ipython_globals == None:
00459             myf=self.__globals__
00460         else:
00461             myf=ipython_globals
00462 
00463         a = odict()
00464         a['project']  = 'sim'
00465         a['skymodel']  = ''
00466         a['complist']  = ''
00467         a['setpointings']  = True
00468         a['obsmode']  = 'int'
00469         a['thermalnoise']  = ''
00470         a['leakage']  = 0.0
00471         a['graphics']  = 'both'
00472         a['verbose']  = False
00473         a['overwrite']  = True
00474 
00475         a['async']=False
00476         a['skymodel'] = {
00477                     0:odict([{'notvalue':''}, {'inbright':''}, {'indirection':''}, {'incell':''}, {'incenter':''}, {'inwidth':''}])}
00478         a['complist'] = {
00479                     0:odict([{'notvalue':''}, {'compwidth':'8GHz'}])}
00480         a['setpointings'] = {
00481                     0:odict([{'value':True}, {'integration':'10s'}, {'direction':''}, {'mapsize':['', '']}, {'maptype':'ALMA'}, {'pointingspacing':''}]), 
00482                     1:odict([{'value':False}, {'ptgfile':'$project.ptg.txt'}, {'integration':'10s'}])}
00483         a['obsmode'] = {
00484                     0:odict([{'value':'int'}, {'antennalist':'alma.out10.cfg'}, {'refdate':'2014/05/21'}, {'hourangle':'transit'}, {'totaltime':"7200s"}, {'caldirection':''}, {'calflux':'1Jy'}]), 
00485                     1:odict([{'value':'sd'}, {'sdantlist':'aca.tp.cfg'}, {'sdant':0}, {'refdate':'2014/05/21'}, {'hourangle':'transit'}, {'totaltime':"7200s"}]), 
00486                     2:odict([{'value':''}, {'antennalist':''}, {'sdantlist':''}, {'sdant':0}])}
00487         a['thermalnoise'] = {
00488                     0:{'value':''}, 
00489                     1:{'value':'False'}, 
00490                     2:{'value':'F'}, 
00491                     3:odict([{'value':'tsys-atm'}, {'user_pwv':1.}, {'t_ground':269.}, {'seed':11111}]), 
00492                     4:odict([{'value':'tsys-manual'}, {'t_ground':269.}, {'t_sky':263.}, {'tau0':0.1}, {'seed':11111}])}
00493 
00494 ### This function sets the default values but also will return the list of
00495 ### parameters or the default value of a given parameter
00496         if(param == None):
00497                 myf['__set_default_parameters'](a)
00498         elif(param == 'paramkeys'):
00499                 return a.keys()
00500         else:
00501             if(paramvalue==None and subparam==None):
00502                if(a.has_key(param)):
00503                   return a[param]
00504                else:
00505                   return self.itsdefault(param)
00506             else:
00507                retval=a[param]
00508                if(type(a[param])==dict):
00509                   for k in range(len(a[param])):
00510                      valornotval='value'
00511                      if(a[param][k].has_key('notvalue')):
00512                         valornotval='notvalue'
00513                      if((a[param][k][valornotval])==paramvalue):
00514                         retval=a[param][k].copy()
00515                         retval.pop(valornotval)
00516                         if(subparam != None):
00517                            if(retval.has_key(subparam)):
00518                               retval=retval[subparam]
00519                            else:
00520                               retval=self.itsdefault(subparam)
00521                      else:
00522                         retval=self.itsdefault(subparam)
00523                return retval
00524 
00525 
00526 #
00527 #
00528     def check_params(self, param=None, value=None, ipython_globals=None):
00529       if ipython_globals == None:
00530           myf=self.__globals__
00531       else:
00532           myf=ipython_globals
00533 #      print 'param:', param, 'value:', value
00534       try :
00535          if str(type(value)) != "<type 'instance'>" :
00536             value0 = value
00537             value = myf['cu'].expandparam(param, value)
00538             matchtype = False
00539             if(type(value) == numpy.ndarray):
00540                if(type(value) == type(value0)):
00541                   myf[param] = value.tolist()
00542                else:
00543                   #print 'value:', value, 'value0:', value0
00544                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00545                   myf[param] = value0
00546                   if type(value0) != list :
00547                      matchtype = True
00548             else :
00549                myf[param] = value
00550             value = myf['cu'].verifyparam({param:value})
00551             if matchtype:
00552                value = False
00553       except Exception, instance:
00554          #ignore the exception and just return it unchecked
00555          myf[param] = value
00556       return value
00557 #
00558 #
00559     def description(self, key='simobserve', subkey=None):
00560         desc={'simobserve': 'mosaic simulation task',
00561                'project': 'root prefix for output file names',
00562                'skymodel': 'model image to observe',
00563                'inbright': 'scale surface brightness of brightest pixel e.g. "1.2Jy/pixel"',
00564                'indirection': 'set new direction e.g. "J2000 19h00m00 -40d00m00"',
00565                'incell': 'set new cell/pixel size e.g. "0.1arcsec"',
00566                'incenter': 'set new frequency of center channel e.g. "89GHz" (required even for 2D model)',
00567                'inwidth': 'set new channel width e.g. "10MHz" (required even for 2D model)',
00568                'complist': 'componentlist to observe',
00569                'compwidth': 'bandwidth of components',
00570                'setpointings': '',
00571                'ptgfile': 'list of pointing positions',
00572                'integration': 'integration (sampling) time',
00573                'direction': '"J2000 19h00m00 -40d00m00" or "" to center on model',
00574                'mapsize': 'angular size of map or "" to cover model',
00575                'maptype': 'hexagonal, square (raster), ALMA, ALMA2012',
00576                'pointingspacing': 'spacing in between pointings or "0.25PB" or "" for Nyquist',
00577                'caldirection': 'pt source calibrator [experimental]',
00578                'calflux': '',
00579                'obsmode': 'observation mode to simulate [int(interferometer)|sd(singledish)|""(none)]',
00580                'refdate': 'date of observation - not critical unless concatting simulations',
00581                'hourangle': 'hour angle of observation center e.g. -3:00:00, or "transit"',
00582                'totaltime': 'total time of observation or number of repetitions',
00583                'antennalist': 'interferometer antenna position file',
00584                'sdantlist': 'single dish antenna position file',
00585                'sdant': 'single dish antenna index in file',
00586                'thermalnoise': 'add thermal noise: [tsys-atm|tsys-manual|""]',
00587                'user_pwv': 'Precipitable Water Vapor in mm',
00588                't_ground': 'ambient temperature',
00589                't_sky': 'atmospheric temperature',
00590                'tau0': 'zenith opacity',
00591                'seed': 'random number seed',
00592                'leakage': 'cross polarization (interferometer only)',
00593                'graphics': 'display graphics at each stage to [screen|file|both|none]',
00594                'verbose': '',
00595                'overwrite': 'overwrite files starting with $project',
00596 
00597                'async': 'If true the taskname must be started using simobserve(...)'
00598               }
00599 
00600 #
00601 # Set subfields defaults if needed
00602 #
00603         if(subkey == 'True'):
00604           desc['direction'] = 'center of map or "" to center on the model'
00605         if(subkey == 'False'):
00606           desc['integration'] = 'integration time (see below)'
00607         if(subkey == ''):
00608           desc['antennalist'] = 'antenna info can be used to calculate the primary beam'
00609         if(subkey == ''):
00610           desc['sdantlist'] = 'antenna info can be used to calculate the primary beam'
00611 
00612         if(desc.has_key(key)) :
00613            return desc[key]
00614 
00615     def itsdefault(self, paramname) :
00616         a = {}
00617         a['project']  = 'sim'
00618         a['skymodel']  = ''
00619         a['inbright']  = ''
00620         a['indirection']  = ''
00621         a['incell']  = ''
00622         a['incenter']  = ''
00623         a['inwidth']  = ''
00624         a['complist']  = ''
00625         a['compwidth']  = '"8GHz"'
00626         a['setpointings']  = True
00627         a['ptgfile']  = '$project.ptg.txt'
00628         a['integration']  = '10s'
00629         a['direction']  = ['']
00630         a['mapsize']  = ['', '']
00631         a['maptype']  = 'hexagonal'
00632         a['pointingspacing']  = ''
00633         a['caldirection']  = ''
00634         a['calflux']  = '1Jy'
00635         a['obsmode']  = 'int'
00636         a['refdate']  = '2014/01/01'
00637         a['hourangle']  = 'transit'
00638         a['totaltime']  = '7200s'
00639         a['antennalist']  = ''
00640         a['sdantlist']  = ''
00641         a['sdant']  = 0
00642         a['thermalnoise']  = ''
00643         a['user_pwv']  = 1.
00644         a['t_ground']  = 270.
00645         a['t_sky']  = 260.
00646         a['tau0']  = 0.1
00647         a['seed']  = 11111
00648         a['leakage']  = 0.0
00649         a['graphics']  = 'both'
00650         a['verbose']  = False
00651         a['overwrite']  = True
00652 
00653         #a = sys._getframe(len(inspect.stack())-1).f_globals
00654 
00655         if self.parameters['skymodel']  != '':
00656             a['inbright'] = ''
00657             a['indirection'] = ''
00658             a['incell'] = ''
00659             a['incenter'] = ''
00660             a['inwidth'] = ''
00661 
00662         if self.parameters['complist']  != '':
00663             a['compwidth'] = '8GHz'
00664 
00665         if self.parameters['setpointings']  == True:
00666             a['integration'] = '10s'
00667             a['direction'] = ''
00668             a['mapsize'] = ['', '']
00669             a['maptype'] = 'ALMA'
00670             a['pointingspacing'] = ''
00671 
00672         if self.parameters['setpointings']  == False:
00673             a['ptgfile'] = '$project.ptg.txt'
00674             a['integration'] = '10s'
00675 
00676         if self.parameters['obsmode']  == 'int':
00677             a['antennalist'] = 'alma.out10.cfg'
00678             a['refdate'] = '2014/05/21'
00679             a['hourangle'] = 'transit'
00680             a['totaltime'] = "7200s"
00681             a['caldirection'] = ''
00682             a['calflux'] = '1Jy'
00683 
00684         if self.parameters['obsmode']  == 'sd':
00685             a['sdantlist'] = 'aca.tp.cfg'
00686             a['sdant'] = 0
00687             a['refdate'] = '2014/05/21'
00688             a['hourangle'] = 'transit'
00689             a['totaltime'] = "7200s"
00690 
00691         if self.parameters['obsmode']  == '':
00692             a['antennalist'] = ''
00693             a['sdantlist'] = ''
00694             a['sdant'] = 0
00695 
00696         if self.parameters['thermalnoise']  == 'tsys-atm':
00697             a['user_pwv'] = 1.
00698             a['t_ground'] = 269.
00699             a['seed'] = 11111
00700 
00701         if self.parameters['thermalnoise']  == 'tsys-manual':
00702             a['t_ground'] = 269.
00703             a['t_sky'] = 263.
00704             a['tau0'] = 0.1
00705             a['seed'] = 11111
00706 
00707         if a.has_key(paramname) :
00708               return a[paramname]
00709 simobserve_cli = simobserve_cli_()