casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
imtrans_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_imtrans import imtrans
00018 class imtrans_cli_:
00019     __name__ = "imtrans"
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__ = (imtrans_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'imagename':None, 'outfile':None, 'order':None, 'wantreturn':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, imagename=None, outfile=None, order=None, wantreturn=None,  async=None):
00047 
00048         """Reorder image axes
00049 PARAMETER SUMMARY
00050 imagename        Name of the input image
00051 outfile          Name of output CASA image. If blank, no disk image is written.
00052 order            Output axes mapping
00053 wantreturn       Return an image tool referencing the transposed image?
00054 
00055 This task reorders (transposes) the axes in the input image to the specified
00056 order. The associated pixel values and coordinate system are transposed.
00057 
00058 If the outfile parameter is empty, only a temporary image is created; no output image
00059 is written to disk. The temporary image can be captured in the returned value (assuming
00060 wantreturn is true).
00061 
00062 The order parameter describes the mapping of the input axes to the output axes.
00063 It can be one of three types: a non-negative integer, a string, or a list of
00064 strings. If a string or non-negative integer, it should contain
00065 zero-based digits describing the new order of the input axes. It must
00066 contain the same number of (unique) digits as the number of input axes. For example,
00067 specifying reorder="1032" or reorder=1032 for a four axes image maps input axes
00068 1, 0, 3, 2 to output axes 0, 1, 2, 3. In the case of order being a nonnegative integer
00069 and the zeroth axis in the input being mapped to zeroth axis in the output, the zeroth
00070 digit is implicitly understood to be 0 so that to transpose an image where one would
00071 use a string order="0321", one could equivalently specify an int order=321.
00072 Because of ambiguity for axes numbers greater than nine, using string or integer order
00073 specifications cannot handle images containing more than 10 axes.
00074 The order parameter can also be specified as a list of strings which uniquely match,
00075 ignoring case, the first characters of the image axis names (ia.coordsys().names()).
00076 So to reorder an image with right ascension, declination, and frequency axes, one could
00077 specify order=["d", "f", "r"] or equivalently ["decl", "frequ", "right a"]. Note that
00078 specifying "ra" for the right ascension axis will result in an error because "ra" does
00079 not match the first two characters of right ascension.
00080 Axes can be simultaneously inverted in cases where order is a string or an array of
00081 strings by specifying negative signs in front of the axis/axes to be inverted. So,
00082 in a 4-D image, order="-10-3-2" maps input axes 1, 0, 3, 2 to output axes 0, 1, 2, 3 
00083 and reverses the direction and values of input axes 1, 3, and 2.   
00084 EXAMPLE: 
00085 # Swap the stokes and spectral axes in an RA-Dec-Stokes-Frequency image
00086 imagename = "myim.im"
00087 outfile = "outim.im"
00088 order = "0132"
00089 imtrans()
00090 
00091 # or
00092 
00093 outfile = "myim_2.im"
00094 order = 132
00095 imtrans()
00096 
00097 # or
00098 
00099 outfile = "myim_3.im"
00100 order = ["r", "d", "f", "s"]
00101 imtrans()
00102 
00103 # or
00104 
00105 utfile = "myim_4.im"
00106 order = ["rig", "declin", "frequ", "stok"]
00107 imtrans()
00108 
00109 
00110         """
00111         if not hasattr(self, "__globals__") or self.__globals__ == None :
00112            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00113         #casac = self.__globals__['casac']
00114         casalog = self.__globals__['casalog']
00115         #casalog = casac.casac.logsink()
00116         self.__globals__['__last_task'] = 'imtrans'
00117         self.__globals__['taskname'] = 'imtrans'
00118         ###
00119         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00120         ###
00121         ###
00122         #Handle globals or user over-ride of arguments
00123         #
00124         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00125         useLocalDefaults = False
00126 
00127         for item in function_signature_defaults.iteritems():
00128                 key,val = item
00129                 keyVal = eval(key)
00130                 if (keyVal == None):
00131                         #user hasn't set it - use global/default
00132                         pass
00133                 else:
00134                         #user has set it - use over-ride
00135                         if (key != 'self') :
00136                            useLocalDefaults = True
00137 
00138         myparams = {}
00139         if useLocalDefaults :
00140            for item in function_signature_defaults.iteritems():
00141                key,val = item
00142                keyVal = eval(key)
00143                exec('myparams[key] = keyVal')
00144                self.parameters[key] = keyVal
00145                if (keyVal == None):
00146                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00147                    keyVal = eval(key)
00148                    if(type(keyVal) == dict) :
00149                       if len(keyVal) > 0 :
00150                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00151                       else :
00152                          exec('myparams[key] = ' + key + ' = {}')
00153 
00154         else :
00155             async = self.parameters['async']
00156             myparams['imagename'] = imagename = self.parameters['imagename']
00157             myparams['outfile'] = outfile = self.parameters['outfile']
00158             myparams['order'] = order = self.parameters['order']
00159             myparams['wantreturn'] = wantreturn = self.parameters['wantreturn']
00160 
00161 
00162         result = None
00163 
00164 #
00165 #    The following is work around to avoid a bug with current python translation
00166 #
00167         mytmp = {}
00168 
00169         mytmp['imagename'] = imagename
00170         mytmp['outfile'] = outfile
00171         mytmp['order'] = order
00172         mytmp['wantreturn'] = wantreturn
00173         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00174         trec = casac.casac.utils().torecord(pathname+'imtrans.xml')
00175 
00176         casalog.origin('imtrans')
00177         try :
00178           #if not trec.has_key('imtrans') or not casac.casac.utils().verify(mytmp, trec['imtrans']) :
00179             #return False
00180 
00181           casac.casac.utils().verify(mytmp, trec['imtrans'], True)
00182           scriptstr=['']
00183           saveinputs = self.__globals__['saveinputs']
00184           saveinputs('imtrans', 'imtrans.last', myparams, self.__globals__,scriptstr=scriptstr)
00185           if async :
00186             count = 0
00187             keybase =  time.strftime("%y%m%d.%H%M%S")
00188             key = keybase + "_" + str(count)
00189             while self.__async__.has_key(key) :
00190                count += 1
00191                key = keybase + "_" + str(count)
00192             result = tm.execute('imtrans', imagename, outfile, order, wantreturn)
00193             print "Use: "
00194             print "      tm.retrieve(return_value) # to retrieve the status"
00195             print 
00196             self.rkey = key
00197             self.__async__[key] = result
00198           else :
00199               tname = 'imtrans'
00200               spaces = ' '*(18-len(tname))
00201               casalog.post('\n##########################################'+
00202                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00203               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00204               result = imtrans(imagename, outfile, order, wantreturn)
00205               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00206                            '\n##########################################')
00207 
00208         except Exception, instance:
00209           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00210              raise
00211           else :
00212              #print '**** Error **** ',instance
00213              tname = 'imtrans'
00214              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00215              pass
00216 
00217         gc.collect()
00218         return result
00219 #
00220 #
00221 #
00222     def paramgui(self, useGlobals=True, ipython_globals=None):
00223         """
00224         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00225         """
00226         import paramgui
00227         if not hasattr(self, "__globals__") or self.__globals__ == None :
00228            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00229 
00230         if useGlobals:
00231             if ipython_globals == None:
00232                 myf=self.__globals__
00233             else:
00234                 myf=ipython_globals
00235 
00236             paramgui.setGlobals(myf)
00237         else:
00238             paramgui.setGlobals({})
00239 
00240         paramgui.runTask('imtrans', myf['_ip'])
00241         paramgui.setGlobals({})
00242 
00243 #
00244 #
00245 #
00246     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00247         if not hasattr(self, "__globals__") or self.__globals__ == None :
00248            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00249         if ipython_globals == None:
00250             myf=self.__globals__
00251         else:
00252             myf=ipython_globals
00253 
00254         a = odict()
00255         a['imagename']  = ''
00256         a['outfile']  = ''
00257         a['order']  = ''
00258         a['wantreturn']  = True
00259 
00260         a['async']=False
00261 
00262 ### This function sets the default values but also will return the list of
00263 ### parameters or the default value of a given parameter
00264         if(param == None):
00265                 myf['__set_default_parameters'](a)
00266         elif(param == 'paramkeys'):
00267                 return a.keys()
00268         else:
00269             if(paramvalue==None and subparam==None):
00270                if(a.has_key(param)):
00271                   return a[param]
00272                else:
00273                   return self.itsdefault(param)
00274             else:
00275                retval=a[param]
00276                if(type(a[param])==dict):
00277                   for k in range(len(a[param])):
00278                      valornotval='value'
00279                      if(a[param][k].has_key('notvalue')):
00280                         valornotval='notvalue'
00281                      if((a[param][k][valornotval])==paramvalue):
00282                         retval=a[param][k].copy()
00283                         retval.pop(valornotval)
00284                         if(subparam != None):
00285                            if(retval.has_key(subparam)):
00286                               retval=retval[subparam]
00287                            else:
00288                               retval=self.itsdefault(subparam)
00289                      else:
00290                         retval=self.itsdefault(subparam)
00291                return retval
00292 
00293 
00294 #
00295 #
00296     def check_params(self, param=None, value=None, ipython_globals=None):
00297       if ipython_globals == None:
00298           myf=self.__globals__
00299       else:
00300           myf=ipython_globals
00301 #      print 'param:', param, 'value:', value
00302       try :
00303          if str(type(value)) != "<type 'instance'>" :
00304             value0 = value
00305             value = myf['cu'].expandparam(param, value)
00306             matchtype = False
00307             if(type(value) == numpy.ndarray):
00308                if(type(value) == type(value0)):
00309                   myf[param] = value.tolist()
00310                else:
00311                   #print 'value:', value, 'value0:', value0
00312                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00313                   myf[param] = value0
00314                   if type(value0) != list :
00315                      matchtype = True
00316             else :
00317                myf[param] = value
00318             value = myf['cu'].verifyparam({param:value})
00319             if matchtype:
00320                value = False
00321       except Exception, instance:
00322          #ignore the exception and just return it unchecked
00323          myf[param] = value
00324       return value
00325 #
00326 #
00327     def description(self, key='imtrans', subkey=None):
00328         desc={'imtrans': 'Reorder image axes',
00329                'imagename': 'Name of the input image',
00330                'outfile': 'Name of output CASA image.',
00331                'order': 'New zero-based axes order.',
00332                'wantreturn': 'Return an image tool referencing the transposed image',
00333 
00334                'async': 'If true the taskname must be started using imtrans(...)'
00335               }
00336 
00337         if(desc.has_key(key)) :
00338            return desc[key]
00339 
00340     def itsdefault(self, paramname) :
00341         a = {}
00342         a['imagename']  = ''
00343         a['outfile']  = ''
00344         a['order']  = ''
00345         a['wantreturn']  = True
00346 
00347         #a = sys._getframe(len(inspect.stack())-1).f_globals
00348 
00349         if a.has_key(paramname) :
00350               return a[paramname]
00351 imtrans_cli = imtrans_cli_()