casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
predictcomp_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_predictcomp import predictcomp
00018 class predictcomp_cli_:
00019     __name__ = "predictcomp"
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__ = (predictcomp_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'objname':None, 'standard':None, 'epoch':None, 'minfreq':None, 'maxfreq':None, 'nfreqs':None, 'prefix':None, 'antennalist':None, 'showplot':None, 'savefig':None, 'symb':None, 'include0amp':None, 'include0bl':None, 'blunit':None, 'showbl0flux':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, objname=None, standard=None, epoch=None, minfreq=None, maxfreq=None, nfreqs=None, prefix=None, antennalist=None, showplot=None, savefig=None, symb=None, include0amp=None, include0bl=None, blunit=None, showbl0flux=None,  async=None):
00047 
00048         """Make a component list for a known calibrator
00049 
00050     Writes a component list to disk and returns a dict of
00051     {'clist': filename of the component list,
00052      'objname': objname,
00053      'angdiam': angular diameter in radians (if used in clist),
00054      'standard': standard,
00055      'epoch': epoch,
00056      'freqs': pl.array of frequencies, in GHz,
00057      'antennalist': pl.array of baseline lengths, in m,
00058      'amps':  pl.array of predicted visibility amplitudes, in Jy,
00059      'savedfig': False or, if made, the filename of a plot.}
00060     or False on error.
00061 
00062     objname: An object supported by standard.
00063     standard: A standard for calculating flux densities, as in setjy.
00064               Default: 'Butler-JPL-Horizons 2010'
00065     epoch: The epoch to use for the calculations.   Irrelevant for
00066            extrasolar standards. (Uses UTC)
00067            Examples: '2011-12-31/5:34:12', '2011-12-31-5:34:12'
00068     minfreq: The minimum frequency to use.
00069              Example: '342.0GHz'
00070     maxfreq: The maximum frequency to use.
00071              Default: minfreq
00072              Example: '346.0GHz'
00073              Example: '', anything <= 0, or None: use minfreq.
00074     nfreqs:  The number of frequencies to use.
00075              Default: 1 if minfreq == maxfreq,
00076                       2 otherwise.
00077     prefix: The component list will be saved to
00078                prefix + 'spw0_<objname>_<minfreq><epoch>.cl'
00079             Default: '' 
00080             Example: "Bands3to7_"
00081                      (which could produce 'Bands3to7_spw0_Uranus_100GHz55877d.cl',
00082                       depending on the other parameters)
00083     antennalist: 'Observe' and plot the visibility amplitudes for this
00084                  antenna configuration.  The file should be in a format usable
00085                  by simdata.  The search path is:
00086                      .:casa['dirs']['data'] + '/alma/simmos/'
00087              Default: '' (None, just make clist.)
00088              Example: 'alma.cycle0.extended.cfg'
00089 
00090     Subparameters of antennalist:
00091     showplot: Whether or not to show a plot of S vs. |u| on screen.
00092               Subparameter of antennalist.
00093               Default: Necessarily False if antennalist is not specified.
00094                        True otherwise.
00095     savefig: Filename for saving a plot of S vs. |u|.
00096              Subparameter of antennalist.
00097              Default: False (necessarily if antennalist is not specified)
00098              Examples: ''           (do not save the plot)
00099                        'myplot.png' (save to myplot.png)
00100     symb: One of matplotlib's codes for plot symbols: .:,o^v<>s+xDd234hH|_
00101           Default: ',':  The smallest points I could find.
00102     include0amp: Force the amplitude axis to start at 0?
00103                  Default: False
00104     include0bl: Force the baseline axis to start at 0?
00105                 Default: False
00106     blunit: unit of the baseline axis ('' or 'klambda')
00107             Default:''=use a unit in the data
00108     showbl0flux: Print the zero baseline flux? 
00109                  Default: False 
00110 
00111      
00112 
00113         """
00114         if not hasattr(self, "__globals__") or self.__globals__ == None :
00115            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00116         #casac = self.__globals__['casac']
00117         casalog = self.__globals__['casalog']
00118         #casalog = casac.casac.logsink()
00119         self.__globals__['__last_task'] = 'predictcomp'
00120         self.__globals__['taskname'] = 'predictcomp'
00121         ###
00122         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00123         ###
00124         ###
00125         #Handle globals or user over-ride of arguments
00126         #
00127         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00128         useLocalDefaults = False
00129 
00130         for item in function_signature_defaults.iteritems():
00131                 key,val = item
00132                 keyVal = eval(key)
00133                 if (keyVal == None):
00134                         #user hasn't set it - use global/default
00135                         pass
00136                 else:
00137                         #user has set it - use over-ride
00138                         if (key != 'self') :
00139                            useLocalDefaults = True
00140 
00141         myparams = {}
00142         if useLocalDefaults :
00143            for item in function_signature_defaults.iteritems():
00144                key,val = item
00145                keyVal = eval(key)
00146                exec('myparams[key] = keyVal')
00147                self.parameters[key] = keyVal
00148                if (keyVal == None):
00149                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00150                    keyVal = eval(key)
00151                    if(type(keyVal) == dict) :
00152                       if len(keyVal) > 0 :
00153                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00154                       else :
00155                          exec('myparams[key] = ' + key + ' = {}')
00156 
00157         else :
00158             async = self.parameters['async']
00159             myparams['objname'] = objname = self.parameters['objname']
00160             myparams['standard'] = standard = self.parameters['standard']
00161             myparams['epoch'] = epoch = self.parameters['epoch']
00162             myparams['minfreq'] = minfreq = self.parameters['minfreq']
00163             myparams['maxfreq'] = maxfreq = self.parameters['maxfreq']
00164             myparams['nfreqs'] = nfreqs = self.parameters['nfreqs']
00165             myparams['prefix'] = prefix = self.parameters['prefix']
00166             myparams['antennalist'] = antennalist = self.parameters['antennalist']
00167             myparams['showplot'] = showplot = self.parameters['showplot']
00168             myparams['savefig'] = savefig = self.parameters['savefig']
00169             myparams['symb'] = symb = self.parameters['symb']
00170             myparams['include0amp'] = include0amp = self.parameters['include0amp']
00171             myparams['include0bl'] = include0bl = self.parameters['include0bl']
00172             myparams['blunit'] = blunit = self.parameters['blunit']
00173             myparams['showbl0flux'] = showbl0flux = self.parameters['showbl0flux']
00174 
00175 
00176         result = None
00177 
00178 #
00179 #    The following is work around to avoid a bug with current python translation
00180 #
00181         mytmp = {}
00182 
00183         mytmp['objname'] = objname
00184         mytmp['standard'] = standard
00185         mytmp['epoch'] = epoch
00186         mytmp['minfreq'] = minfreq
00187         mytmp['maxfreq'] = maxfreq
00188         mytmp['nfreqs'] = nfreqs
00189         mytmp['prefix'] = prefix
00190         mytmp['antennalist'] = antennalist
00191         mytmp['showplot'] = showplot
00192         mytmp['savefig'] = savefig
00193         mytmp['symb'] = symb
00194         mytmp['include0amp'] = include0amp
00195         mytmp['include0bl'] = include0bl
00196         mytmp['blunit'] = blunit
00197         mytmp['showbl0flux'] = showbl0flux
00198         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00199         trec = casac.casac.utils().torecord(pathname+'predictcomp.xml')
00200 
00201         casalog.origin('predictcomp')
00202         try :
00203           #if not trec.has_key('predictcomp') or not casac.casac.utils().verify(mytmp, trec['predictcomp']) :
00204             #return False
00205 
00206           casac.casac.utils().verify(mytmp, trec['predictcomp'], True)
00207           scriptstr=['']
00208           saveinputs = self.__globals__['saveinputs']
00209           saveinputs('predictcomp', 'predictcomp.last', myparams, self.__globals__,scriptstr=scriptstr)
00210           if async :
00211             count = 0
00212             keybase =  time.strftime("%y%m%d.%H%M%S")
00213             key = keybase + "_" + str(count)
00214             while self.__async__.has_key(key) :
00215                count += 1
00216                key = keybase + "_" + str(count)
00217             result = tm.execute('predictcomp', objname, standard, epoch, minfreq, maxfreq, nfreqs, prefix, antennalist, showplot, savefig, symb, include0amp, include0bl, blunit, showbl0flux)
00218             print "Use: "
00219             print "      tm.retrieve(return_value) # to retrieve the status"
00220             print 
00221             self.rkey = key
00222             self.__async__[key] = result
00223           else :
00224               tname = 'predictcomp'
00225               spaces = ' '*(18-len(tname))
00226               casalog.post('\n##########################################'+
00227                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00228               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00229               result = predictcomp(objname, standard, epoch, minfreq, maxfreq, nfreqs, prefix, antennalist, showplot, savefig, symb, include0amp, include0bl, blunit, showbl0flux)
00230               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00231                            '\n##########################################')
00232 
00233         except Exception, instance:
00234           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00235              raise
00236           else :
00237              #print '**** Error **** ',instance
00238              tname = 'predictcomp'
00239              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00240              pass
00241 
00242         gc.collect()
00243         return result
00244 #
00245 #
00246 #
00247     def paramgui(self, useGlobals=True, ipython_globals=None):
00248         """
00249         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00250         """
00251         import paramgui
00252         if not hasattr(self, "__globals__") or self.__globals__ == None :
00253            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00254 
00255         if useGlobals:
00256             if ipython_globals == None:
00257                 myf=self.__globals__
00258             else:
00259                 myf=ipython_globals
00260 
00261             paramgui.setGlobals(myf)
00262         else:
00263             paramgui.setGlobals({})
00264 
00265         paramgui.runTask('predictcomp', myf['_ip'])
00266         paramgui.setGlobals({})
00267 
00268 #
00269 #
00270 #
00271     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00272         if not hasattr(self, "__globals__") or self.__globals__ == None :
00273            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00274         if ipython_globals == None:
00275             myf=self.__globals__
00276         else:
00277             myf=ipython_globals
00278 
00279         a = odict()
00280         a['objname']  = ''
00281         a['standard']  = 'Butler-JPL-Horizons 2010'
00282         a['epoch']  = ''
00283         a['minfreq']  = ''
00284         a['maxfreq']  = ''
00285         a['nfreqs']  = 2
00286         a['prefix']  = ''
00287         a['antennalist']  = ''
00288         a['symb']  = ','
00289 
00290         a['async']=False
00291         a['antennalist'] = {
00292                     0:odict([{'notvalue':''}, {'showplot':True}, {'savefig':''}, {'symb':','}, {'include0amp':False}, {'include0bl':False}, {'blunit':''}, {'showbl0flux':False}])}
00293 
00294 ### This function sets the default values but also will return the list of
00295 ### parameters or the default value of a given parameter
00296         if(param == None):
00297                 myf['__set_default_parameters'](a)
00298         elif(param == 'paramkeys'):
00299                 return a.keys()
00300         else:
00301             if(paramvalue==None and subparam==None):
00302                if(a.has_key(param)):
00303                   return a[param]
00304                else:
00305                   return self.itsdefault(param)
00306             else:
00307                retval=a[param]
00308                if(type(a[param])==dict):
00309                   for k in range(len(a[param])):
00310                      valornotval='value'
00311                      if(a[param][k].has_key('notvalue')):
00312                         valornotval='notvalue'
00313                      if((a[param][k][valornotval])==paramvalue):
00314                         retval=a[param][k].copy()
00315                         retval.pop(valornotval)
00316                         if(subparam != None):
00317                            if(retval.has_key(subparam)):
00318                               retval=retval[subparam]
00319                            else:
00320                               retval=self.itsdefault(subparam)
00321                      else:
00322                         retval=self.itsdefault(subparam)
00323                return retval
00324 
00325 
00326 #
00327 #
00328     def check_params(self, param=None, value=None, ipython_globals=None):
00329       if ipython_globals == None:
00330           myf=self.__globals__
00331       else:
00332           myf=ipython_globals
00333 #      print 'param:', param, 'value:', value
00334       try :
00335          if str(type(value)) != "<type 'instance'>" :
00336             value0 = value
00337             value = myf['cu'].expandparam(param, value)
00338             matchtype = False
00339             if(type(value) == numpy.ndarray):
00340                if(type(value) == type(value0)):
00341                   myf[param] = value.tolist()
00342                else:
00343                   #print 'value:', value, 'value0:', value0
00344                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00345                   myf[param] = value0
00346                   if type(value0) != list :
00347                      matchtype = True
00348             else :
00349                myf[param] = value
00350             value = myf['cu'].verifyparam({param:value})
00351             if matchtype:
00352                value = False
00353       except Exception, instance:
00354          #ignore the exception and just return it unchecked
00355          myf[param] = value
00356       return value
00357 #
00358 #
00359     def description(self, key='predictcomp', subkey=None):
00360         desc={'predictcomp': 'Make a component list for a known calibrator',
00361                'objname': 'Object name',
00362                'standard': 'Flux density standard',
00363                'epoch': 'Epoch',
00364                'minfreq': 'Minimum frequency',
00365                'maxfreq': 'Maximum frequency',
00366                'nfreqs': 'Number of frequencies',
00367                'prefix': 'Prefix for the component list directory name.',
00368                'antennalist': 'Plot for this configuration',
00369                'showplot': 'Plot S vs |u| to the screen?',
00370                'savefig': 'Save a plot of S vs |u| to this filename',
00371                'symb': 'A matplotlib plot symbol code',
00372                'include0amp': 'Force the amplitude axis to start at 0?',
00373                'include0bl': 'Force the baseline axis to start at 0?',
00374                'blunit': 'unit of the baseline axis',
00375                'showbl0flux': 'Print the zero baseline flux ?',
00376 
00377                'async': 'If true the taskname must be started using predictcomp(...)'
00378               }
00379 
00380 #
00381 # Set subfields defaults if needed
00382 #
00383 
00384         if(desc.has_key(key)) :
00385            return desc[key]
00386 
00387     def itsdefault(self, paramname) :
00388         a = {}
00389         a['objname']  = ''
00390         a['standard']  = 'Butler-JPL-Horizons 2010'
00391         a['epoch']  = ''
00392         a['minfreq']  = ''
00393         a['maxfreq']  = ''
00394         a['nfreqs']  = 2
00395         a['prefix']  = ''
00396         a['antennalist']  = ''
00397         a['showplot']  = False
00398         a['savefig']  = ''
00399         a['symb']  = ','
00400         a['include0amp']  = False
00401         a['include0bl']  = False
00402         a['blunit']  = ''
00403         a['showbl0flux']  = False
00404 
00405         #a = sys._getframe(len(inspect.stack())-1).f_globals
00406 
00407         if self.parameters['antennalist']  != '':
00408             a['showplot'] = True
00409             a['savefig'] = ''
00410             a['symb'] = ','
00411             a['include0amp'] = False
00412             a['include0bl'] = False
00413             a['blunit'] = ''
00414             a['showbl0flux'] = False
00415 
00416         if a.has_key(paramname) :
00417               return a[paramname]
00418 predictcomp_cli = predictcomp_cli_()