casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
sdscale_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_sdscale import sdscale
00018 class sdscale_cli_:
00019     __name__ = "sdscale"
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__ = (sdscale_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'infile':None, 'antenna':None, 'factor':None, 'scaletsys':None, 'outfile':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, infile=None, antenna=None, factor=None, scaletsys=None, outfile=None, overwrite=None,  async=None):
00047 
00048         """ASAP SD task: scale the sd spectra
00049         Keyword arguments:
00050         infile -- name of input SD dataset
00051         antenna -- antenna name or id (only effective for MS input). 
00052         factor -- scaling factor. float or one- or two-dimensional float list.
00053                   default: 1 (no scaling)
00054         scaletsys -- scaling of associated Tsys
00055                     default: True
00056         outfile -- output file name 
00057                    outfile='' will write the data to a file named,
00058                    <infile>_scaled<factor>
00059                    default: ''
00060         overwrite -- overwrite the output file if already exists
00061                 options: (bool) True,False
00062                 default: False
00063 
00064 
00065         DESCRIPTION:
00066 
00067         Task sdscale performs scaling of single-dish spectra.
00068         By setting scaletsys = True, associated Tsys is also scaled.
00069         Tsys informations are written in the casalogger and they are 
00070         automatically stored in 'casapy.log'. 
00071         The infile can be any of ASAP, MS, SDFITS, or RPFITS format.
00072         If outfile name is given or outfile=''(default), the scaled data 
00073         is written to a new file with the same format as the input data 
00074         (Note: in case of the RPFITS format input data, it will be written 
00075         to SDFITS format).
00076 
00077         The scaling factor, factor, accepts both scalar type and list 
00078         type value. The list must be one or two dimensional. If factor is 
00079         one dimensional, its length must coincide with a number of spectral 
00080         channel. If factor is two dimensional, its shape must be 
00081         (n, 1) or (n, m), where n is a number of spectrum, while m is a 
00082         number of channel for each spcetum. m can be variable for each 
00083         spectrum. In addition, the factor can be an ASCII filename that 
00084         stores a space-separated list of scaling factor consisting of 
00085         adequate number of rows and columns. For example, if the contents 
00086         of input ASCII file is shown as, 
00087 
00088            0.5 0.3 0.2
00089            1.0 0.2 0.9
00090 
00091         it is interpreted as a list [[0.5, 0.3, 0.2],[1.0, 0.2, 0.9]]. 
00092 
00093         WARNING for the GBT raw SDFITS format data as input:
00094         SDtasks are able to handle GBT raw SDFITS format data since the 
00095         data filler is available. However, the functionality is not well 
00096         tested yet, so that there may be unknown bugs.  
00097 
00098   
00099         """
00100         if not hasattr(self, "__globals__") or self.__globals__ == None :
00101            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00102         #casac = self.__globals__['casac']
00103         casalog = self.__globals__['casalog']
00104         #casalog = casac.casac.logsink()
00105         self.__globals__['__last_task'] = 'sdscale'
00106         self.__globals__['taskname'] = 'sdscale'
00107         ###
00108         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00109         ###
00110         ###
00111         #Handle globals or user over-ride of arguments
00112         #
00113         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00114         useLocalDefaults = False
00115 
00116         for item in function_signature_defaults.iteritems():
00117                 key,val = item
00118                 keyVal = eval(key)
00119                 if (keyVal == None):
00120                         #user hasn't set it - use global/default
00121                         pass
00122                 else:
00123                         #user has set it - use over-ride
00124                         if (key != 'self') :
00125                            useLocalDefaults = True
00126 
00127         myparams = {}
00128         if useLocalDefaults :
00129            for item in function_signature_defaults.iteritems():
00130                key,val = item
00131                keyVal = eval(key)
00132                exec('myparams[key] = keyVal')
00133                self.parameters[key] = keyVal
00134                if (keyVal == None):
00135                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00136                    keyVal = eval(key)
00137                    if(type(keyVal) == dict) :
00138                       if len(keyVal) > 0 :
00139                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00140                       else :
00141                          exec('myparams[key] = ' + key + ' = {}')
00142 
00143         else :
00144             async = self.parameters['async']
00145             myparams['infile'] = infile = self.parameters['infile']
00146             myparams['antenna'] = antenna = self.parameters['antenna']
00147             myparams['factor'] = factor = self.parameters['factor']
00148             myparams['scaletsys'] = scaletsys = self.parameters['scaletsys']
00149             myparams['outfile'] = outfile = self.parameters['outfile']
00150             myparams['overwrite'] = overwrite = self.parameters['overwrite']
00151 
00152 
00153         result = None
00154 
00155 #
00156 #    The following is work around to avoid a bug with current python translation
00157 #
00158         mytmp = {}
00159 
00160         mytmp['infile'] = infile
00161         mytmp['antenna'] = antenna
00162         mytmp['factor'] = factor
00163         mytmp['scaletsys'] = scaletsys
00164         mytmp['outfile'] = outfile
00165         mytmp['overwrite'] = overwrite
00166         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00167         trec = casac.casac.utils().torecord(pathname+'sdscale.xml')
00168 
00169         casalog.origin('sdscale')
00170         try :
00171           #if not trec.has_key('sdscale') or not casac.casac.utils().verify(mytmp, trec['sdscale']) :
00172             #return False
00173 
00174           casac.casac.utils().verify(mytmp, trec['sdscale'], True)
00175           scriptstr=['']
00176           saveinputs = self.__globals__['saveinputs']
00177           saveinputs('sdscale', 'sdscale.last', myparams, self.__globals__,scriptstr=scriptstr)
00178           if async :
00179             count = 0
00180             keybase =  time.strftime("%y%m%d.%H%M%S")
00181             key = keybase + "_" + str(count)
00182             while self.__async__.has_key(key) :
00183                count += 1
00184                key = keybase + "_" + str(count)
00185             result = tm.execute('sdscale', infile, antenna, factor, scaletsys, outfile, overwrite)
00186             print "Use: "
00187             print "      tm.retrieve(return_value) # to retrieve the status"
00188             print 
00189             self.rkey = key
00190             self.__async__[key] = result
00191           else :
00192               tname = 'sdscale'
00193               spaces = ' '*(18-len(tname))
00194               casalog.post('\n##########################################'+
00195                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00196               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00197               result = sdscale(infile, antenna, factor, scaletsys, outfile, overwrite)
00198               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00199                            '\n##########################################')
00200 
00201         except Exception, instance:
00202           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00203              raise
00204           else :
00205              #print '**** Error **** ',instance
00206              tname = 'sdscale'
00207              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00208              pass
00209 
00210         gc.collect()
00211         return result
00212 #
00213 #
00214 #
00215     def paramgui(self, useGlobals=True, ipython_globals=None):
00216         """
00217         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00218         """
00219         import paramgui
00220         if not hasattr(self, "__globals__") or self.__globals__ == None :
00221            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00222 
00223         if useGlobals:
00224             if ipython_globals == None:
00225                 myf=self.__globals__
00226             else:
00227                 myf=ipython_globals
00228 
00229             paramgui.setGlobals(myf)
00230         else:
00231             paramgui.setGlobals({})
00232 
00233         paramgui.runTask('sdscale', myf['_ip'])
00234         paramgui.setGlobals({})
00235 
00236 #
00237 #
00238 #
00239     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00240         if not hasattr(self, "__globals__") or self.__globals__ == None :
00241            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00242         if ipython_globals == None:
00243             myf=self.__globals__
00244         else:
00245             myf=ipython_globals
00246 
00247         a = odict()
00248         a['infile']  = ''
00249         a['antenna']  = 0
00250         a['factor']  = 1.0
00251         a['scaletsys']  = True
00252         a['outfile']  = ''
00253         a['overwrite']  = False
00254 
00255         a['async']=False
00256 
00257 ### This function sets the default values but also will return the list of
00258 ### parameters or the default value of a given parameter
00259         if(param == None):
00260                 myf['__set_default_parameters'](a)
00261         elif(param == 'paramkeys'):
00262                 return a.keys()
00263         else:
00264             if(paramvalue==None and subparam==None):
00265                if(a.has_key(param)):
00266                   return a[param]
00267                else:
00268                   return self.itsdefault(param)
00269             else:
00270                retval=a[param]
00271                if(type(a[param])==dict):
00272                   for k in range(len(a[param])):
00273                      valornotval='value'
00274                      if(a[param][k].has_key('notvalue')):
00275                         valornotval='notvalue'
00276                      if((a[param][k][valornotval])==paramvalue):
00277                         retval=a[param][k].copy()
00278                         retval.pop(valornotval)
00279                         if(subparam != None):
00280                            if(retval.has_key(subparam)):
00281                               retval=retval[subparam]
00282                            else:
00283                               retval=self.itsdefault(subparam)
00284                      else:
00285                         retval=self.itsdefault(subparam)
00286                return retval
00287 
00288 
00289 #
00290 #
00291     def check_params(self, param=None, value=None, ipython_globals=None):
00292       if ipython_globals == None:
00293           myf=self.__globals__
00294       else:
00295           myf=ipython_globals
00296 #      print 'param:', param, 'value:', value
00297       try :
00298          if str(type(value)) != "<type 'instance'>" :
00299             value0 = value
00300             value = myf['cu'].expandparam(param, value)
00301             matchtype = False
00302             if(type(value) == numpy.ndarray):
00303                if(type(value) == type(value0)):
00304                   myf[param] = value.tolist()
00305                else:
00306                   #print 'value:', value, 'value0:', value0
00307                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00308                   myf[param] = value0
00309                   if type(value0) != list :
00310                      matchtype = True
00311             else :
00312                myf[param] = value
00313             value = myf['cu'].verifyparam({param:value})
00314             if matchtype:
00315                value = False
00316       except Exception, instance:
00317          #ignore the exception and just return it unchecked
00318          myf[param] = value
00319       return value
00320 #
00321 #
00322     def description(self, key='sdscale', subkey=None):
00323         desc={'sdscale': 'ASAP SD task: scale the sd spectra',
00324                'infile': 'name of input SD dataset',
00325                'antenna': 'antenna name or id (only effective for MS input)',
00326                'factor': 'scaling factor (float or float list)',
00327                'scaletsys': 'scaling of associated Tsys',
00328                'outfile': 'if specified write the scaled data to a separate scantable file',
00329                'overwrite': 'overwrite the output file if already exists',
00330 
00331                'async': 'If true the taskname must be started using sdscale(...)'
00332               }
00333 
00334         if(desc.has_key(key)) :
00335            return desc[key]
00336 
00337     def itsdefault(self, paramname) :
00338         a = {}
00339         a['infile']  = ''
00340         a['antenna']  = 0
00341         a['factor']  = 1.0
00342         a['scaletsys']  = True
00343         a['outfile']  = ''
00344         a['overwrite']  = False
00345 
00346         #a = sys._getframe(len(inspect.stack())-1).f_globals
00347 
00348         if a.has_key(paramname) :
00349               return a[paramname]
00350 sdscale_cli = sdscale_cli_()