casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
taskinit.py
Go to the documentation of this file.
00001 import pCASA
00002 from casac import *
00003 import viewertool
00004 import inspect
00005 import string
00006 import sys
00007 import os
00008 
00009 
00010 def __taskinit_setlogfile( logger ) :
00011         ####
00012         #### needed to allow pushing of the global 'casa' state dictionary
00013         ####
00014         a=inspect.stack()
00015         stacklevel=0
00016         for k in range(len(a)):
00017                 if a[k][1] == "<string>":
00018                         stacklevel=k
00019 
00020         myf=sys._getframe(stacklevel).f_globals
00021 
00022         if myf.has_key('casa') and myf['casa'].has_key('files') and myf['casa']['files'].has_key('logfile') :
00023                 logger.setlogfile(myf['casa']['files']['logfile'])
00024 
00025 
00026 def __taskinit_casa( ) :
00027         a=inspect.stack()
00028         stacklevel=0
00029         for k in range(len(a)):
00030                 if a[k][1] == "<string>" or (string.find(a[k][1], 'ipython console') > 0 or string.find(a[k][1],"casapy.py") > 0):
00031                         stacklevel=k
00032 
00033         myf=sys._getframe(stacklevel).f_globals
00034 
00035         if myf.has_key('casa') :
00036                 return myf['casa']
00037         else:
00038                 return { }
00039 
00040 #
00041 ##casa state...
00042 casa = __taskinit_casa( )
00043 
00044 #
00045 ##allow globals for taskby default
00046 casaglobals=True
00047 # setup available tools
00048 imager = casac.imager
00049 imtool=imager
00050 calibrater = casac.calibrater
00051 cbtool=calibrater
00052 mstool = casac.ms
00053 tptool = casac.tableplot
00054 tp = tptool()
00055 mptool = casac.msplot
00056 mp = mptool()
00057 pmtool = casac.plotms
00058 pm = pmtool()
00059 cptool = casac.calplot
00060 cp = cptool()
00061 qatool = casac.quanta
00062 qa = casac.qa =  qatool()
00063 tbtool = casac.table
00064 fgtool = casac.flagger
00065 aftool = casac.agentflagger
00066 af = aftool()
00067 metool = casac.measures
00068 iatool = casac.image
00069 potool = casac.imagepol
00070 smtool = casac.simulator
00071 cltool = casac.componentlist
00072 coordsystool = casac.coordsys
00073 rgtool = casac.regionmanager
00074 sltool = casac.spectralline
00075 dctool = casac.deconvolver
00076 vptool = casac.vpmanager
00077 msmdtool = casac.msmetadata
00078 fitool = casac.fitter
00079 fntool = casac.functional
00080 utilstool = casac.utils
00081 cu = casac.cu = utilstool()
00082 vftask = casac.vlafillertask()
00083 vlafiller=vftask.fill
00084 casalog =  casac.logsink()
00085 __taskinit_setlogfile(casalog)
00086 casalog.setglobal(True)
00087 at = casac.atmosphere()
00088 ca = casac.calanalysis()
00089 
00090 def gentools(tools=None):
00091         """
00092         Generate a fresh set of tools the ones who's
00093         state can be funny
00094         im,cb,ms,tb,fg,me,ia,po,sm,cl,cs,rg,sl,dc,vp,msmd,fi=gentools() 
00095         or if you want specific set of tools
00096         im, ia, cb=gentools(['im', 'ia', 'cb'])
00097 
00098         """
00099         tooldic={'im':'imager()', 'cb' :'calibrater()', 'ms':'mstool()',
00100                  'tb':'tbtool()', 'fg':'fgtool()', 'me' :'metool()', 
00101                  'ia': 'iatool()', 'po':'potool()', 'sm' :'smtool()', 
00102                  'cl': 'cltool()', 'cs' :'coordsystool()', 'rg':'rgtool()',
00103                  'sl':'sltool()', 'dc':'dctool()', 'vp':'vptool()',
00104          'msmd':'msmdtool()','fi':'fitool()','fn':'fntool()'}
00105         reqtools=[]
00106         if (not tools) or not hasattr(tools, '__iter__'):
00107                 reqtools=['im', 'cb', 'ms','tb', 'fg', 'me', 'ia', 'po',
00108                           'sm', 'cl', 'cs', 'rg','sl', 'dc', 'vp', 'msmd', 'fi', 'fn']
00109         else:
00110                 reqtools=tools
00111         return tuple([eval(tooldic[reqtool]) for reqtool in reqtools])
00112 
00113 im,cb,ms,tb,fg,me,ia,po,sm,cl,cs,rg,sl,dc,vp,msmd,fi,fn=gentools()
00114 
00115 def write_history(myms, vis, tname, param_names, param_vals, myclog=None, debug=False):
00116         """
00117         Update vis with the parameters that task tname was called with.
00118 
00119         myms - an ms tool instance
00120         vis  - the MS to write to.
00121         tname - name of the calling task.
00122         param_names - list of parameter names.
00123         param_vals - list of parameter values (in the same order as param_names).
00124         myclog - a casalog instance (optional)
00125         debug - Turns on debugging print statements on errors if True.
00126 
00127         Example:
00128         The end of split does
00129         param_names = split.func_code.co_varnames[:split.func_code.co_argcount]
00130         param_vals = [eval(p) for p in param_names]  # Must be done in the task.
00131         write_history(myms, outputvis, 'split', param_names, param_vals,
00132                       casalog),
00133         which appends, e.g.,
00134         
00135         vis = 'TWHydra_CO3_2.ms'
00136         outputvis   = 'scan9.ms'
00137         datacolumn  = 'data'
00138         field       = ''
00139         spw         = ''
00140         width       = 1
00141         antenna     = ''
00142         timebin     = '0s'
00143         timerange   = ''
00144         scan        = '9'
00145         intent      = ''
00146         array       = ''
00147         uvrange     = ''
00148         correlation = ''
00149         keepflags   = True
00150         async       = False
00151 
00152         to the HISTORY of outputvis.
00153         """
00154         if not hasattr(myms, 'writehistory'):
00155                 if debug:
00156                         print "write_history(myms, %s, %s): myms is not an ms tool" % (vis, tname)
00157                 return False
00158         retval = True
00159         isopen = False
00160         try:
00161                 if not myclog and hasattr(casalog, 'post'):
00162                         myclog = casalog
00163         except Exception, instance:
00164                 # There's no logger to complain to, and I don't want to exit
00165                 # just because of that.
00166                 pass
00167         try:
00168                 myms.open(vis, nomodify=False)
00169                 isopen = True
00170                 myms.writehistory(message='taskname=%s' % tname, origin=tname)
00171                 vestr = 'version: '
00172                 try:
00173                         # Don't use myclog.version(); it also prints to the
00174                         # logger, which is confusing.
00175                         vestr += casa['build']['version'] + ' '
00176                         vestr += casa['source']['url'].split('/')[-2]
00177                         vestr += ' rev. ' + casa['source']['revision']
00178                         vestr += ' ' + casa['build']['time']
00179                 except Exception, instance:
00180                         if hasattr(myclog, 'version'):
00181                                 # Now give it a try.
00182                                 vestr += myclog.version()
00183                         else:
00184                                 vestr += ' could not be determined' # We tried.
00185                 myms.writehistory(message=vestr, origin=tname)
00186 
00187                 # Write the arguments.
00188                 for argnum in xrange(len(param_names)):
00189                         msg = "%-11s = " % param_names[argnum]
00190                         val = param_vals[argnum]
00191                         if type(val) == str:
00192                                 msg += '"'
00193                         msg += str(val)
00194                         if type(val) == str:
00195                                 msg += '"'
00196                         myms.writehistory(message=msg, origin=tname)
00197         except Exception, instance:
00198                 if hasattr(myclog, 'post'):
00199                         myclog.post("*** Error \"%s\" updating HISTORY of %s" % (instance, vis),
00200                                     'SEVERE')
00201                 retval = False
00202         finally:
00203                 if isopen:
00204                         myms.close()
00205         return retval        
00206 
00207 ###done with common tools
00208 
00209 # setup viewer tool
00210 # jagonzal (CAS-4322): Don't load task manager at the engine level
00211 if not os.environ.has_key('CASA_ENGINE'):
00212         try : 
00213                 if casa.has_key('state') and casa['state'].has_key('startup') :
00214                         ving = viewertool.viewertool( False, pre_launch=casa['state']['startup'] )
00215                         if casa['flags'].has_key('--nogui') :
00216                                 vi = ving
00217                         else:
00218                                 vi = viewertool.viewertool( True, pre_launch=casa['state']['startup'] )
00219         except :
00220                 print "Unable to start viewer, maybe no dbus available?"
00221 
00222 defaultsdir = {}
00223 defaultsdir['alma'] = 'file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/almadefaults.xml'
00224 defaultsdir['evla'] = 'file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/evladefaults.xml'
00225 
00226 
00227 def selectfield(vis,minstring):
00228         """Derive the fieldid from  minimum matched string(s): """
00229 
00230         tb.open(vis+'/FIELD')
00231         fields=list(tb.getcol('NAME'))#get fieldname list
00232         tb.close()              #close table
00233         indexlist=list()        #initialize list
00234         stringlist=list()
00235 
00236         fldlist=minstring.split()#split string into elements
00237         print 'fldlist is ',fldlist
00238         for fld in fldlist:     #loop over fields
00239                 _iter=fields.__iter__() #create iterator for fieldnames
00240                 while 1:
00241                         try:
00242                                 x=_iter.next() # has first value of field name
00243                         except StopIteration:
00244                                 break
00245                         #
00246                         if (x.find(fld)!=-1): 
00247                                 indexlist.append(fields.index(x))
00248                                 stringlist.append(x)
00249 
00250         print 'Selected fields are: ',stringlist
00251         return indexlist
00252 
00253 def selectantenna(vis,minstring):
00254         """Derive the antennaid from matched string(s): """
00255 
00256         tb.open(vis+'/ANTENNA')
00257         ants=list(tb.getcol('NAME'))#get fieldname list
00258         tb.close()              #close table
00259         indexlist=list()        #initialize list
00260         stringlist=list()
00261 
00262         antlist=minstring.split()#split string into elements
00263         for ant in antlist:     #loop over fields
00264                 try:
00265                         ind=ants.index(ant)
00266                         indexlist.append(ind)
00267                         stringlist.append(ant)
00268                 except ValueError:
00269                         pass
00270 
00271         print 'Selected reference antenna: ',stringlist
00272         print 'indexlist: ',indexlist
00273         return indexlist[0]
00274 
00275 def readboxfile(boxfile):
00276         """ Read a file containing clean boxes (compliant with AIPS BOXFILE)
00277 
00278         Format is:
00279         #FIELDID BLC-X BLC-Y TRC-X TRC-Y
00280         0       110   110   150   150 
00281         or
00282         0       hh:mm:ss.s dd.mm.ss.s hh:mm:ss.s dd.mm.ss.s
00283 
00284         Note all lines beginning with '#' are ignored.
00285 
00286         """
00287         union=[]
00288         f=open(boxfile)
00289         while 1:
00290                 try: 
00291                         line=f.readline()
00292                         if (line.find('#')!=0): 
00293                                 splitline=line.split('\n')
00294                                 splitline2=splitline[0].split()
00295                                 if (len(splitline2[1])<6): 
00296                                         boxlist=[int(splitline2[1]),int(splitline2[2]),
00297                                         int(splitline2[3]),int(splitline2[4])]
00298                                 else:
00299                                         boxlist=[splitline2[1],splitline2[2],splitline2[3],
00300                                         splitline2[4]]
00301         
00302                                 union.append(boxlist)
00303         
00304                 except:
00305                         break
00306 
00307         f.close()
00308         return union
00309 
00310 
00311 # AUTHOR: S. Jaeger
00312 #
00313 # NAME: getimaxes
00314 #
00315 # DESCRIPTION:
00316 # This function uses the coordinate information associated
00317 # with an image to find where the directional (sky) axes are,
00318 # the spectral axes, and the stokes axes.
00319 #
00320 # INPUT:
00321 #    imagename   string   path to a file on disk.
00322 #
00323 # RETURN
00324 #    list of four lists, [list1, list2, list3, list4 ], as follows :
00325 #       list1: ['axis num of 1st sky axis', 'Name of axis' ]
00326 #       list2: ['axis num of 2nd sky axis', 'Name of axis' ]
00327 #       list3: ['axis num of spectral axis', 'Spectral' ]
00328 #       list4: ['axis num of stokes axis', 'Stokes' ]
00329 
00330 def getimaxes(imagename):
00331         """
00332         Open an image file, looking at its coordinate system information
00333         to determine which axes are directional, linear, spectral, and
00334         the stokes axies.
00335 
00336         The return list or lists contains the axis numbers and names in
00337         the following order:
00338              1. Directional or Linear
00339              2. Directional or Linear
00340              3. Spectral
00341              4. Stokes
00342 
00343         Note that if an axis type is not found an empty list is returned
00344         for that axis.
00345         """
00346 
00347         # Get the images coord. sys.
00348         csys=None
00349         ia.open( imagename )
00350         csys=ia.coordsys()
00351 
00352         # Find where the directional and channel axies are
00353         # Save the internal placement of the axies in a list
00354         # (which will be in the following order:
00355         #    direction1: RA, Longitude, Linear, el, ..
00356         #    direction2: DEC, Lattitude, Linear, az, ..
00357         #    spectral:
00358         #    stokes: I or V
00359         axisTypes=csys.axiscoordinatetypes()
00360         axisNames=csys.names()
00361         
00362         # Note that we make a potentially dangerous assumption here
00363         # that the first directional access is always RA, but it
00364         # may not be.  The names given to the axies are completely
00365         # arbitrary and can not be used to determine one axis from
00366         # another.
00367         # TODO throw exception??? if we find extra axies or
00368         #      unrecognized axies.
00369         retValue=[['',''],['',''],['',''],['','']]
00370         foundFirstDir=False
00371         for i in range( len( axisTypes ) ):
00372                 if ( axisTypes[i]=='Direction' or axisTypes[i]=='Linear' ):
00373                         if ( not foundFirstDir ) :
00374                                 retValue[0]=[i,axisNames[i]]
00375                                 foundFirstDir=True
00376                         else:
00377                                 retValue[1]=[i,axisNames[i]]
00378                 elif ( axisTypes[i]=='Spectral' ) :
00379                         retValue[2]=[i,axisNames[i]]
00380                 elif ( axisTypes[i]=='Stokes' ) :
00381                         retValue[3]=[i,axisNames[i]]
00382 
00383         if ( csys != None ):
00384             del csys
00385         if ( ia.isopen() ):
00386             ia.close()
00387         return retValue
00388 
00389 
00390 # from RR
00391 def announce_async_task(taskname):
00392         """Use the logger to herald the beginning of an asynchronous task."""
00393         casalog.origin(taskname)
00394         casalog.post('')
00395         casalog.post('###############################################')
00396         casalog.post('###  Begin Task: ' + taskname + ' ' * (27 - len(taskname)) + '###')
00397         casalog.post("")
00398         casalog.post("Use: ")
00399         casalog.post("      tm.retrieve(return_value) # to retrieve the status")
00400         casalog.post("")
00401         
00402 def write_task_obit(taskname):
00403         """Eulogize the task in the logger."""
00404         casalog.post('###  End Task: ' + taskname + ' ' * (29 - len(taskname)) + '###')
00405         casalog.post('###############################################')
00406         casalog.post('')
00407 
00408 
00409 def array2string( array ):
00410         returnValue=""
00411         for i in range( len(array) ):
00412                 if ( i > 1 ):
00413                         returnValue+=","
00414                 if ( isinstance( array[i], str ) ):
00415                         returnValue+=array[i]
00416                 else:
00417                         returnValue+=str(array[i])
00418         return returnValue
00419 
00420 def recursivermdir( top='' ):
00421         # Delete everything from the directory named in 'top',
00422         # assuming there are no symbolic links.
00423         for root, dirs, files in os.walk( top, topdown=False ):
00424                 for name in files:
00425                         os.remove( os.path.join( root, name ) )
00426                 for name in dirs:
00427                         os.rmdir( os.path.join( root, name ) )
00428         os.rmdir(top)