casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
makemask_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_makemask import makemask
00016 from task_makemask import casalog
00017 
00018 class makemask_pg_:
00019     __name__ = "makemask"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (makemask_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, mode=None, inpimage=None, inpmask=None, output=None, overwrite=None, inpfreqs=None, outfreqs=None, async=None):
00027 
00028         """Makes and manipulates image masks
00029 
00030 Modes : 
00031 -------------
00032 
00033 copy :  Copy/merge masks and regrid if necessary to a new or existing mask
00034 expand : Expand a mask from one range of freqs to another range
00035 list : list internal masks in inpimage to the log
00036 delete : delete an internal mask from an image (if the deleted mask was a default mask,
00037          the task chooses the first one in the remaining internal mask list (as appears 
00038          in the log when do listing with mode='list') 
00039 setdefaultmask : set a specified internal mask as a defult internal mask 
00040 
00041 
00042 
00043 
00044 In all cases (for output mask is expected), if the output image has a different coordinate system from the
00045 result of input and processing, the mask will be regridded to the output
00046 coordinate system.  
00047 
00048 
00049 Parameter Descriptions and rules:
00050 ------------------------------
00051 inpimage : Name of input image to use as a reference for the output coordinates (if output does not exist). 
00052            Also used as a reference image when regions are specified in inpmask for copy mode
00053            default: none (must specify for list, copy, expand modes)
00054 
00055 Expandable parameters for mode='copy','expand','delete' and 'setdefaultmask':
00056 inpmask : Name(s) of input mask(s)
00057           default: none
00058          To specify an image (zero/non-zero) mask, just give a image name (e.g. myimage1.im)
00059          To specify an internal (T/F) mask, you must give a parent image name and the internal mask name
00060          seperated by a colon. (e.g. myimage1.im:mask0). The internal mask names can be found by running
00061          the makemask task in mode='list'. 
00062  
00063          (expand mode)
00064          'myimage:mask0' : use(true/false) internal mask 
00065          'myimage'  : use the inpimage values to make a mask (zero/non-zero).
00066                       Non-zero values are normalized to one in the process.
00067          (merge mode)
00068          Specify the image mask(s), T/F mask(s), and region(s) to be merged in a list of strings.
00069          The regions can be specified directly in the CASA region format or in the text file(s) contains
00070          the regions. 
00071 
00072          (delete and setdefaultmask mode)
00073          Specify the internal mask with the format, image:mask
00074          
00075  
00076 output : Name of output image. 
00077          default: none
00078          *The resultant mask is written as an image (zero/one) mask if the output is a plain image name
00079          *The resultant mask is written as an internal (T/F) mask if the output name is the form of 'imagename:maskname'
00080           The created mask is set as a default internal mask.
00081          *To re-grid a mask to a different coordinate system,  
00082           give an image with the target coordinate system in inpimage. Or make a copy an imge
00083           with the target coordinate system and specified the name of the copy in output. 
00084 
00085 
00086     - If output is specifield as a plain image, if it exists, it will regrid the mask to 
00087       the new coordinate system  and modify output (if overwrite=True).
00088     - If output is specifield as an image with an internal mask, if the internal mask exists,
00089       it will regrid the mask to the new coordinate system  and modify the internal mask only (if overwrite=True).
00090     - If output does not exist, it will only copy inpimage
00091     - If output == inpimage, do not regrid. Only modify in-place.
00092 
00093 overwrite : overwrite the mask specified in output? (see also the output rules above)
00094             default: False
00095 
00096 Additional expandable parameters for mode='expand':
00097   inpfreqs : input channel/frequency/velocity range
00098              Specify channels in a list of integers. for frequency/velocity, 
00099              a range is specified in a string with '~', e.g. '1.5MHz~1.6MHz'
00100              default: []  - all channels
00101   outfreqs : output channel/frequency/velocity range  
00102              Specify same way as inpfreqs
00103              default: []  - all channels
00104 
00105  
00106 Usage examples : 
00107 ---------------------------
00108 (1) (list mode):
00109      makemask(mode='list', inpimage='mymask.im')
00110      it prints out a list of the internal mask(s) exist in mymask.im to the log 
00111 
00112 (2) (copy mode):
00113      Regrid a boolean mask from one coordinate system to another and save as boolean mask 
00114      in the output image.   
00115 
00116      makemask(mode='copy', inpimage='oldmask.im', inpmask='oldmask.im:mask0', output='newmask.im:mask0')
00117   
00118 (3) (copy mode):
00119      Same as (1), but save as integer mask in the output image.
00120      
00121      makemask(mode='copy', inpimage='oldmask.im', inpmask='oldmask.im:mask0', output='newmask.im')
00122 
00123 
00124 (4) (copy mode):
00125      Convert a boolean(true/false) mask to integer(one/zero) mask in the same image
00126      
00127      makemask(mode='copy', inpimage='oldmask.im', inpmask='oldmask.im:mask0', output='', overwrite=True)
00128 
00129 
00130 (5) (copy mode):
00131      Convert an integer (one/zero) mask to boolean(true/false) mask in the same image
00132      
00133      makemask(mode='copy', inpimage='oldmask.im', inpmask='oldmask.im', output='oldmask.im:mask0')
00134 
00135 
00136 (6) (copy mode):
00137  
00138      Merge a one/zero mask and  T/F masks, using the input coordinate-sys of inpimage and
00139      saving in a new output file. Remember, if the image specified in output already exist and 
00140      has a different coordinate system from inpimage, the mask will be regridded to it.
00141      All masks to be merged are specified in a list in inpmask.
00142      The name of internal masks must be given in the format, 'parent_image_name:internal_mask_name', 
00143      as shown the example below.
00144   
00145      In the example below, image1.im (the 1/0 mask), the internal masks, mask0 from image1.im
00146      and mask1 from image2.im, and a region (on image1.im as defined in inpimage)  are combined. 
00147      The output, newmask.im is a new mask name which has not
00148      yet exist so image specified in inpimage, image1.im's coordinates are used as a target
00149      image coordinates. If image1.im and image2.im has different coordinates, image2.im:mask1 is
00150      regridded before it is combined to the other two masks.
00151 
00152      makemask(mode='copy',
00153               inpimage='image1.im', 
00154               inpmask=['image1.im', image1.im:mask0','image2.mask:mask1', 'circle[[15pix , 15pix] ,8pix ]'],
00155               output='newmask.im);
00156 
00157 (7) (expand mode):
00158      Expand a (one/zero) mask from continuum imaging to use as an input mask image for
00159      spectral line imaging. Use an existing spectral line clean image as a template by
00160      sepecified in inpimage. 
00161      The inpfreqs is left out as it uses a default (=[], means all channels).
00162 
00163      makemask(mode='expand', inpimage='spec.clean.image', inpmask='cont.clean.mask' 
00164               outfreqs=[4,5,6,7], output='spec.clean.mask')
00165 
00166 (8) (expand mode):
00167      Expand a boolean mask from one range of channels to another range 
00168      in the same image.
00169 
00170      makemask(mode='expand', inpimage='oldmask.im', inpmask='oldmask.im:mask0', inpfreqs=[5,6], outfreqs=[4,5,6,7],
00171               output='oldmask.im:mask0', overwrite=True)
00172 
00173 
00174 (9) (expand mode):
00175      Expand a boolean mask from a range of channels in the input image to another range
00176      of channels in a  different image with a different spectral-coordinate system.
00177      Save the mask as ones/zeros so that it can be used as an input mask in the clean task. 
00178 
00179      makemask(mode='expand', inpimage='bigmask.im', inpmask='smallmask.im:mask0', 
00180               inpfreqs='1.5MHz~1.6MHz', outfreqs='1.2MHz~1.8MHz', output='bigmask.im', overwrite=True)
00181 
00182 (10) (delete mode)
00183       Delete an internal mask from an image.
00184 
00185       makemask(mode='delete', inpmask='newmask.im:mask0')
00186 
00187 (11) (setdefaultmask mode)
00188       Set an internal mask as a default internal mask.
00189      
00190       makemask(mode='setdefaultmask', inpmask='newmask.im:mask1')
00191 
00192 
00193 
00194 
00195 
00196   
00197         """
00198         a=inspect.stack()
00199         stacklevel=0
00200         for k in range(len(a)):
00201           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00202                 stacklevel=k
00203                 break
00204         myf=sys._getframe(stacklevel).f_globals
00205         myf['__last_task'] = 'makemask'
00206         myf['taskname'] = 'makemask'
00207         ###
00208         myf['update_params'](func=myf['taskname'],printtext=False)
00209         ###
00210         ###
00211         #Handle globals or user over-ride of arguments
00212         #
00213         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00214         useLocalDefaults = False
00215 
00216         for item in function_signature_defaults.iteritems():
00217                 key,val = item
00218                 keyVal = eval(key)
00219                 if (keyVal == None):
00220                         #user hasn't set it - use global/default
00221                         pass
00222                 else:
00223                         #user has set it - use over-ride
00224                         if (key != 'self') :
00225                            useLocalDefaults = True
00226                         #myf[key]=keyVal
00227 
00228         myparams = {}
00229         if useLocalDefaults :
00230            for item in function_signature_defaults.iteritems():
00231                key,val = item
00232                keyVal = eval(key)
00233                exec('myparams[key] = keyVal')
00234                if (keyVal == None):
00235                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00236                    keyVal = eval(key)
00237                    if(type(keyVal) == dict) :
00238                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00239 
00240         else :
00241             uselessvariable = None 
00242             myparams['mode'] = mode = myf['mode']
00243             myparams['inpimage'] = inpimage = myf['inpimage']
00244             myparams['inpmask'] = inpmask = myf['inpmask']
00245             myparams['output'] = output = myf['output']
00246             myparams['overwrite'] = overwrite = myf['overwrite']
00247             myparams['inpfreqs'] = inpfreqs = myf['inpfreqs']
00248             myparams['outfreqs'] = outfreqs = myf['outfreqs']
00249 
00250 
00251         result = None
00252 
00253 #
00254 #    The following is work around to avoid a bug with current python translation
00255 #
00256         mytmp = {}
00257 
00258         mytmp['mode'] = mode
00259         mytmp['inpimage'] = inpimage
00260         mytmp['inpmask'] = inpmask
00261         mytmp['output'] = output
00262         mytmp['overwrite'] = overwrite
00263         mytmp['inpfreqs'] = inpfreqs
00264         mytmp['outfreqs'] = outfreqs
00265         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00266         trec = casac.utils().torecord(pathname+'makemask.xml')
00267 
00268         casalog.origin('makemask')
00269         if not trec.has_key('makemask') or not casac.utils().verify(mytmp, trec['makemask']) :
00270             return False
00271 
00272 
00273         try :
00274           casalog.post('')
00275           casalog.post('##########################################')
00276           casalog.post('##### Begin Task: makemask           #####')
00277           casalog.post('')
00278           result = makemask(mode, inpimage, inpmask, output, overwrite, inpfreqs, outfreqs)
00279           casalog.post('')
00280           casalog.post('##### End Task: makemask           #####')
00281           casalog.post('##########################################')
00282 
00283 
00284 # saveinputs for individule engine has no use
00285 # saveinputs should alos be removed from casa_in_py.py
00286 #
00287 #
00288 #          saveinputs = myf['saveinputs']
00289 #          saveinputs('makemask', 'makemask.last', myparams)
00290 #
00291 #
00292         except Exception, instance:
00293           #print '**** Error **** ',instance
00294           pass
00295 
00296         gc.collect()
00297         return result
00298 #
00299 #
00300 ##
00301 #    def paramgui(self, useGlobals=True):
00302 #        """
00303 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00304 #        """
00305 #        import paramgui
00306 #
00307 #        a=inspect.stack()
00308 #        stacklevel=0
00309 #        for k in range(len(a)):
00310 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00311 #            stacklevel=k
00312 #            break
00313 #        myf = sys._getframe(stacklevel).f_globals
00314 #
00315 #        if useGlobals:
00316 #            paramgui.setGlobals(myf)
00317 #        else:
00318 #            paramgui.setGlobals({})
00319 #
00320 #        paramgui.runTask('makemask', myf['_ip'])
00321 #        paramgui.setGlobals({})
00322 #
00323 #
00324 #
00325 #
00326     def defaults(self, param=None):
00327         a=inspect.stack()
00328         stacklevel=0
00329         for k in range(len(a)):
00330           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00331                 stacklevel=k
00332                 break
00333         myf=sys._getframe(stacklevel).f_globals
00334         a = odict()
00335         a['mode']  = 'list'
00336 
00337         a['async']=False
00338         a['mode'] = {
00339                     0:odict([{'value':'list'}, {'inpimage':''}]), 
00340                     1:odict([{'value':'copy'}, {'inpimage':''}, {'inpmask':''}, {'output':''}, {'overwrite':False}]), 
00341                     2:odict([{'value':'expand'}, {'inpimage':''}, {'inpmask':''}, {'inpfreqs':[]}, {'outfreqs':[]}, {'output':''}, {'overwrite':False}]), 
00342                     3:odict([{'value':'delete'}, {'inpmask':''}]), 
00343                     4:odict([{'value':'setdefaultmask'}, {'inpmask':''}])}
00344 
00345 ### This function sets the default values but also will return the list of
00346 ### parameters or the default value of a given parameter
00347         if(param == None):
00348                 myf['__set_default_parameters'](a)
00349         elif(param == 'paramkeys'):
00350                 return a.keys()
00351         else:
00352                 if(a.has_key(param)):
00353                    #if(type(a[param]) == dict) :
00354                    #   return a[param][len(a[param])-1]['value']
00355                    #else :
00356                       return a[param]
00357 
00358 
00359 #
00360 #
00361     def check_params(self, param=None, value=None):
00362       a=inspect.stack() 
00363       stacklevel=0
00364       for k in range(len(a)):
00365         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00366             stacklevel=k
00367             break
00368       myf=sys._getframe(stacklevel).f_globals
00369 
00370 #      print 'param:', param, 'value:', value
00371       try :
00372          if str(type(value)) != "<type 'instance'>" :
00373             value0 = value
00374             value = myf['cu'].expandparam(param, value)
00375             matchtype = False
00376             if(type(value) == numpy.ndarray):
00377                if(type(value) == type(value0)):
00378                   myf[param] = value.tolist()
00379                else:
00380                   #print 'value:', value, 'value0:', value0
00381                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00382                   myf[param] = value0
00383                   if type(value0) != list :
00384                      matchtype = True
00385             else :
00386                myf[param] = value
00387             value = myf['cu'].verifyparam({param:value})
00388             if matchtype:
00389                value = False
00390       except Exception, instance:
00391          #ignore the exception and just return it unchecked
00392          myf[param] = value
00393       return value
00394 
00395 #
00396 #
00397     def description(self, key='makemask', subkey=None):
00398         desc={'makemask': 'Makes and manipulates image masks',
00399                'mode': 'Mask method (copy,expand,merge,delete,setdefaultmask)',
00400                'inpimage': 'Name of input image.',
00401                'inpmask': 'mask(s) to be processed: image masks,T/F internal masks(Need to include parent image names)',
00402                'output': 'Name of output mask (imagename or imagename:internal_maskname)',
00403                'overwrite': 'overwrite output if exists?',
00404                'inpfreqs': 'List of chans/freqs (in inpmask) to read masks from ',
00405                'outfreqs': 'List of chans/freqs (in output) on which to expand the mask',
00406 
00407                'async': 'If true the taskname must be started using makemask(...)'
00408               }
00409 
00410 #
00411 # Set subfields defaults if needed
00412 #
00413 
00414         if(desc.has_key(key)) :
00415            return desc[key]
00416 
00417     def itsdefault(self, paramname) :
00418         a = {}
00419         a['mode']  = 'list'
00420         a['inpimage']  = ''
00421         a['inpmask']  = ''
00422         a['output']  = ''
00423         a['overwrite']  = False
00424         a['inpfreqs']  = []
00425         a['outfreqs']  = []
00426 
00427         if a.has_key(paramname) :
00428               return a[paramname]
00429 makemask_pg = makemask_pg_()