casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
casa_in_py.py
Go to the documentation of this file.
00001 #
00002 import os
00003 import re
00004 import sys
00005 import time
00006 import string
00007 import commands
00008 
00009 from get_user import get_user
00010 
00011 try:
00012     from casac import casac
00013 except ImportError, e:
00014     print "failed to load casa:\n", e
00015     exit(1)
00016 try:
00017     import asap as sd
00018 except ImportError, e:
00019     print "failed to load asap:\n", e
00020     
00021 # jagonzal: Create CASA dictionary (some tasks like setjy need it)
00022 homedir = os.getenv('HOME')
00023 if homedir == None :
00024    print "Environment variable HOME is not set, please set it"
00025    sys.exit(1)
00026 home=os.environ['HOME']
00027 
00028 import casadef
00029 casa = { 'build': {
00030              'time': casadef.build_time,
00031              'version': casadef.casa_version,
00032              'number': casadef.subversion_revision
00033          },
00034          'source': {
00035              'url': casadef.subversion_url,
00036              'revision': casadef.subversion_revision
00037          },
00038          'helpers': {
00039              'logger': 'casalogger',
00040              'viewer': 'casaviewer',
00041              'info': None,
00042              'dbus': None,
00043              'ipcontroller': None,
00044              'ipengine': None
00045          },
00046          'dirs': {
00047              'rc': homedir + '/.casa',
00048              'data': None,
00049              'recipes': casadef.python_library_directory+'/recipes',
00050              'root': None
00051          },
00052          'flags': { },
00053          'files': { 
00054              'logfile': os.getcwd( ) + '/casapy-'+time.strftime("%Y%m%d-%H%M%S", time.gmtime())+'.log'
00055          },
00056          'state' : { 'startup': True }
00057        }
00058 
00059 #import matplotlib
00060 
00061 
00062 ##
00063 ## first set up CASAPATH
00064 ##
00065 #if os.environ.has_key('CASAPATH') :
00066 #    __casapath__ = os.environ['CASAPATH'].split(' ')[0]
00067 #    if not os.path.exists(__casapath__ + "/data") :
00068 #        raise RuntimeError, "CASAPATH environment variable is improperly set"
00069 #else :
00070 #    __casapath__ = casac.__file__
00071 #    while __casapath__ and __casapath__ != "/" :
00072 #        if os.path.exists( __casapath__ + "/data") :
00073 #            break
00074 #        __casapath__ = os.path.dirname(__casapath__)
00075 #    if __casapath__ and __casapath__ != "/" :
00076 #        os.environ['CASAPATH']=__casapath__ + " linux local host"
00077 #    else :
00078 #        raise RuntimeError, "CASAPATH environment variable must be set"
00079 #
00080 ###
00081 ### next adjust the PYTHONPATH
00082 ###
00083 #if re.match( r'.*/\d+\.\d+\.\d+\w*-\d+$', __casapath__ ) :
00084 #    for root, dirs, files in os.walk(os.path.dirname(__casapath__)):
00085 #        if root.endswith("/numpy"):
00086 #            sys.path.append(os.path.dirname(root))
00087 #            break
00088 #else:
00089 #    for root, dirs, files in os.walk(__casapath__):
00090 #        if root.endswith("/numpy"):
00091 #            sys.path.append(os.path.dirname(root))
00092 #            break
00093 #
00094 ###
00095 ### next adjust PATH and LD_LIBRARY_PATH
00096 ###
00097 #for root, dirs, files in os.walk(__casapath__):
00098 #    if root.endswith("/bin") and "casapyinfo" in files :
00099 #        __ipcontroller__ = (lambda fd: fd.readline().strip('\n'))(os.popen(root + "/casapyinfo --exec 'which ipcontroller'"))
00100 #        if os.path.exists(__ipcontroller__) :
00101 #            os.environ['PATH'] = os.path.dirname(__ipcontroller__) + ":" + os.environ['PATH']
00102 #        else :
00103 #            raise RuntimeError, "cannot configure CASA tasking system"
00104 #        __ld_library_path__ = (lambda fd: fd.readline().strip('\n').split(':'))(os.popen(root + "/casapyinfo --exec 'echo $LD_LIBRARY_PATH'"))
00105 #        map(lambda x: sys.path.append(x),__ld_library_path__)
00106 #        break
00107 
00108 #
00109 #from taskinit import *
00110 # cannot do this because taskinit contain
00111 # other functions the engines do not need
00112 # we load tools and tasks explicitly
00113 
00114 ##
00115 ## finally load tools
00116 ####
00117 
00118 # jagonzal: Import tasks but don't load task manager and dbus
00119 os.environ['CASA_ENGINE']="YES"
00120 from tasks import *
00121 
00122 casalog = casac.logsink()
00123 casalog.setglobal(True)
00124 quanta = casac.quanta()
00125 measures = casac.measures()
00126 imager = casac.imager()
00127 synthesisimager = casac.synthesisimager()
00128 calibrater = casac.calibrater()
00129 ms = casac.ms()
00130 tableplot = casac.tableplot()
00131 msplot = casac.msplot()
00132 calplot = casac.calplot()
00133 table = casac.table()
00134 flagger = casac.flagger()
00135 agentflagger = casac.agentflagger()
00136 image = casac.image()
00137 imagepol = casac.imagepol()
00138 simulator = casac.simulator()
00139 componentlist = casac.componentlist()
00140 coordsys = casac.coordsys()
00141 regionmanager = casac.regionmanager()
00142 spectralline = casac.spectralline()
00143 utils = casac.utils()
00144 deconvolver = casac.deconvolver()
00145 vpmanager = casac.vpmanager()
00146 vlafillertask = casac.vlafillertask()
00147 atmosphere = casac.atmosphere()
00148 cu = casac.utils()
00149 #plotms = __plotmshome__.create( )
00150 
00151 
00152 from imstat_pg import imstat_pg as imstat
00153 from flagdata_pg import flagdata_pg as flagdata
00154 #from tflagdata_pg import tflagdata_pg as tflagdata
00155 from flagcmd_pg import flagcmd_pg as flagcmd
00156 from importevla_pg import importevla_pg as importevla
00157 from split_pg import split_pg as split
00158 from importvla_pg import importvla_pg as importvla
00159 from hanningsmooth_pg import hanningsmooth_pg as hanningsmooth
00160 from widefield_pg import widefield_pg as widefield
00161 from immoments_pg import immoments_pg as immoments
00162 from uvcontsub_pg import uvcontsub_pg as uvcontsub
00163 from listhistory_pg import listhistory_pg as listhistory
00164 
00165 from mosaic_pg import mosaic_pg as mosaic
00166 from importfits_pg import importfits_pg as importfits
00167 from imfit_pg import imfit_pg as imfit
00168 from deconvolve_pg import deconvolve_pg as deconvolve
00169 
00170 from simalma_pg import simalma_pg as simalma
00171 from simanalyze_pg import simanalyze_pg as simanalyze
00172 from simobserve_pg import simobserve_pg as simobserve
00173 
00174 from importasdm_pg import importasdm_pg as importasdm
00175 from uvmodelfit_pg import uvmodelfit_pg as uvmodelfit
00176 #from polcal_pg import polcal_pg as polcal
00177 
00178 from clearcal_pg import clearcal_pg as clearcal
00179 from delmod_pg import delmod_pg as delmod
00180 from bandpass_pg import bandpass_pg as bandpass
00181 #from clearplot_pg import clearplot_pg as clearplot
00182 from asdmsummary import  asdmsummary
00183 from listvis_pg import listvis_pg as listvis
00184 from accum_pg import accum_pg as accum
00185 from concat_pg import concat_pg as concat
00186 from listobs_pg import listobs_pg as listobs
00187 from feather_pg import feather_pg as feather
00188 from imregrid_pg import imregrid_pg as imregrid
00189 from listcal_pg import listcal_pg as listcal
00190 from listpartition_pg import listpartition_pg as listpartition
00191 #from plotxy_pg import plotxy_pg as plotxy
00192 from ft_pg import ft_pg as ft
00193 from importuvfits_pg import importuvfits_pg as importuvfits
00194 #somebody contaminated setjy.py
00195 from setjy_pg import setjy_pg  as setjy
00196 from clean_pg import clean_pg as clean
00197 from immath_pg import immath_pg as immath
00198 from imhead_pg import imhead_pg as imhead
00199 from find_pg import find_pg as find
00200 from gaincal_pg import gaincal_pg as gaincal
00201 from fluxscale_pg import fluxscale_pg as fluxscale
00202 from applycal_pg import applycal_pg as applycal
00203 #from plotants_pg import plotants_pg as plotants
00204 from exportuvfits_pg import exportuvfits_pg as exportuvfits
00205 #from plotcal_pg import plotcal_pg as plotcal
00206 from flagmanager_pg import flagmanager_pg as flagmanager
00207 from specfit_pg import specfit_pg  as specfit
00208 #from viewer_pg import viewer_pg as viewer
00209 from exportfits_pg import exportfits_pg as exportfits
00210 from blcal_pg import blcal_pg as blcal
00211 from uvsub_pg import uvsub_pg as uvsub
00212 from imcontsub_pg import imcontsub_pg as imcontsub
00213 from imstat_pg import imstat_pg as imstat
00214 from clearstat_pg import clearstat_pg as clearstat
00215 from browsetable_pg import browsetable_pg as browsetable
00216 from smoothcal_pg import smoothcal_pg as smoothcal
00217 from imval_pg import imval_pg as imval
00218 from vishead_pg import vishead_pg as vishead
00219 from visstat_pg import visstat_pg as visstat
00220 from calstat_pg import calstat_pg as calstat
00221 from msmoments_pg import msmoments_pg as msmoments
00222 from partition_pg import partition_pg as partition
00223 
00224 ##
00225 ## asap may not be available with every casa installation
00226 ##
00227 try:
00228     #import asap as sd
00229     from sdbaseline_pg import sdbaseline_pg as sdbaseline
00230     from sdcal_pg import sdcal_pg as sdcal
00231     from sdcoadd_pg import sdcoadd_pg as sdcoadd
00232     from sdflag_pg import sdflag_pg as sdflag
00233     from sdflagmanager_pg import sdflagmanager_pg as sdflagmanager
00234     from sdfit_pg import sdfit_pg as sdfit
00235     from sdgrid_pg import sdgrid_pg as sdgrid
00236     from sdimaging_pg import sdimaging_pg as sdimaging
00237     from sdimprocess_pg import sdimprocess_pg as sdimprocess
00238     from sdlist_pg import sdlist_pg as sdlist
00239     from sdmath_pg import sdmath_pg as sdmath
00240     from sdplot_pg import sdplot_pg as sdplot
00241     from sdreduce_pg import sdreduce_pg as sdreduce
00242     from sdsave_pg import sdsave_pg as sdsave
00243     from sdscale_pg import sdscale_pg as sdscale 
00244     from sdsmooth_pg import sdsmooth_pg as sdsmooth
00245     from sdstat_pg import sdstat_pg as sdstat
00246     from sdtpimaging_pg import sdtpimaging_pg as sdtpimaging
00247 except ImportError, e:
00248     print "failed to load ASAP:\n", e
00249     sdcoadd = None
00250     sdscale = None
00251     sdtpimaging = None
00252     sdlist = None
00253     sdfit = None
00254     sdbaseline = None
00255     sdstat = None
00256     sdsave = None
00257     sdflag = None
00258     sdcal = None
00259     sdplot = None
00260     sdsmooth = None
00261     sdreduce = None
00262      
00263 
00264 #from tasks import *
00265 
00266 #
00267 # Check if the display environment is set if not
00268 # switch the backend to Agg only if it's TkAgg
00269 #
00270 
00271 if not os.environ.has_key('DISPLAY'):
00272    nodisplay='no display'
00273    #if matplotlib.get_backend() == "TkAgg" :
00274    #   matplotlib.use('Agg')
00275 
00276 from time import strftime
00277 stamp=strftime("%Y%m%d%H%M%S")
00278 contrid='0'
00279 
00280 try:
00281    contrid=os.environ['contrid']
00282    stamp=os.environ['stamp']
00283 except:
00284    pass 
00285 
00286 #thisproc='casaengine-'+stamp+'-'+contrid+'-'
00287 thispid=os.getpid()
00288 
00289 #thelogfile='casapy-'+stamp+'-'+contrid+'-'+str(thispid)+'.log'
00290 
00291 #is this sufficient?
00292 thelogfile='casapy-'+stamp+'-'+str(id)+'.log'
00293 
00294 def get_logs():
00295    return work_dir+'/'+thelogfile
00296 
00297 def clear_logs():
00298    contents = os.listdir(work_dir)
00299    for f in contents:
00300       if os.path.isfile(work_dir+'/'+f) and f.startswith('casapy-') and f.endswith('.log'):
00301          os.remove(work_dir+'/'+f)
00302 
00303 def mkdir(p):
00304    dirsep = '/'
00305    pv = p.split(dirsep)
00306    path = ""
00307    for i in pv:
00308       if i:
00309          path = path + "/" + i
00310          mkdir1(path)
00311 
00312 def mkdir1(p):
00313    if os.path.exists(p):
00314       if not os.path.isdir(p):
00315          cnt = 1
00316          tmp = p + "."
00317          while os.path.exists(tmp + str(cnt)):
00318             cnt += 1
00319             os.rename(p,tmp)
00320             os.mkdir(p)
00321    else:
00322       os.mkdir(p)
00323 
00324 def rmdirs(p):
00325    contents = os.listdir(work_dir)
00326    for f in contents:
00327       #if os.path.isdir(work_dir+'/'+f) and f.startswith(p):
00328       if f.startswith(p):
00329          os.system("rm -rf %s" % f)
00330          #rmdir(f)
00331 
00332 # looks all correct, but it complains non-empty dir
00333 def rmdir(p):
00334    dirsep = '/'
00335    if os.path.isdir(p):
00336       contents = os.listdir(p)
00337       for f in contents:
00338          if os.path.isfile( p + dirsep + f ) or os.path.islink( p + dirsep + f ):
00339             os.remove( p + dirsep + f )
00340          elif os.path.isdir( p + dirsep + f ):
00341             rmdir( p + dirsep + f )
00342          os.rmdir(p)
00343 
00344 
00345 ####################
00346 # Task Interface
00347 
00348 from parameter_check import *
00349 import inspect 
00350 
00351 ####################
00352 def go(taskname=None):
00353     """ Execute taskname: """
00354     a=inspect.stack()
00355     stacklevel=0
00356     for k in range(len(a)):
00357         if (string.find(a[k][1], 'ipython console') > 0):
00358             stacklevel=k
00359             break
00360     myf=sys._getframe(stacklevel).f_globals
00361     if taskname==None: taskname=myf['taskname']
00362     oldtaskname=myf['taskname']
00363     #myf['taskname']=taskname
00364     if type(taskname)!=str:
00365         taskname=taskname.__name__
00366         myf['taskname']=taskname
00367     try:
00368         parameter_checktype(['taskname'],[taskname],str)
00369     except TypeError, e:
00370         print "go -- TypeError: ",e
00371         return
00372     fulltaskname=taskname+'()'
00373     print 'Executing: ',fulltaskname
00374     exec(fulltaskname)
00375     myf['taskname']=oldtaskname
00376 
00377 #def selectfield(vis,minstring):
00378 #    """Derive the fieldid from  minimum matched string(s): """
00379 #
00380 #    tb.open(vis+'/FIELD')
00381 #    fields=list(tb.getcol('NAME'))#get fieldname list
00382 #    tb.close()          #close table
00383 #    indexlist=list()    #initialize list
00384 #    stringlist=list()
00385 #
00386 #    fldlist=minstring.split()#split string into elements
00387 #    print 'fldlist is ',fldlist
00388 #    for fld in fldlist:     #loop over fields
00389 #        _iter=fields.__iter__() #create iterator for fieldnames
00390 #        while 1:
00391 #            try:
00392 #                x=_iter.next() # has first value of field name
00393 #            except StopIteration:
00394 #                break
00395 #            #
00396 #            if (x.find(fld)!=-1): 
00397 #                indexlist.append(fields.index(x))
00398 #                stringlist.append(x)
00399 #
00400 #    print 'Selected fields are: ',stringlist
00401 #    return indexlist
00402 #
00403 #def asap_init():
00404 #    """ Initialize ASAP....: """
00405 #    a=inspect.stack()
00406 #    stacklevel=0
00407 #    for k in range(len(a)):
00408 #        if (string.find(a[k][1], 'ipython console') > 0):
00409 #            stacklevel=k
00410 #            break
00411 #    myf=sys._getframe(stacklevel).f_globals
00412 #    casapath=os.environ['CASAPATH']
00413 #    print '*** Loading ATNF ASAP Package...'
00414 #    import asap as sd
00415 #    print '*** ... ASAP (%s rev#%s) import complete ***' % (sd.__version__,sd.__revision__)
00416 #    os.environ['CASAPATH']=casapath
00417 #    from sdcal_pg import sdcal_pg as sdcal
00418 #    from sdsmooth_pg import sdsmooth_pg as sdsmooth
00419 #    from sdbaseline_pg import sdbaseline_pg as sdbaseline
00420 #    from sdreduce_pg import sdreduce_pg as sdreduce
00421 #    from sdcoadd_pg import sdcoadd_pg as sdcoadd
00422 #    from sdsave_pg import sdsave_pg as sdsave
00423 #    from sdscale_pg import sdscale_pg as sdscale
00424 #    from sdfit_pg import sdfit_pg as sdfit
00425 #    from sdplot_pg import sdplot_pg as sdplot
00426 #    from sdstat_pg import sdstat_pg as sdstat
00427 #    from sdlist_pg import sdlist_pg as sdlist
00428 #    from sdflag_pg import sdflag_pg as sdflag
00429 #    from sdtpimaging_pg import sdtpimaging_pg as sdtpimaging
00430 #    myf['sd']=sd
00431 #    myf['sdcal']=sdcal
00432 #    myf['sdsmooth']=sdsmooth
00433 #    myf['sdbaseline']=sdbaseline
00434 #    myf['sdreduce']=sdreduce
00435 #    myf['sdcoadd']=sdcoadd
00436 #    myf['sdsave']=sdsave
00437 #    myf['sdscale']=sdscale
00438 #    myf['sdfit']=sdfit
00439 #    myf['sdplot']=sdplot
00440 #    myf['sdstat']=sdstat
00441 #    myf['sdlist']=sdlist
00442 #    myf['sdflag']=sdflag
00443 #    myf['sdtpimaging']=sdtpimaging
00444 #
00445 #
00446 #def selectantenna(vis,minstring):
00447 #    """Derive the antennaid from matched string(s): """
00448 #
00449 #    tb.open(vis+'/ANTENNA')
00450 #    ants=list(tb.getcol('NAME'))#get fieldname list
00451 #    tb.close()          #close table
00452 #    indexlist=list()    #initialize list
00453 #    stringlist=list()
00454 #
00455 #    antlist=minstring.split()#split string into elements
00456 #    for ant in antlist:     #loop over fields
00457 #        try:
00458 #            ind=ants.index(ant)
00459 #            indexlist.append(ind)
00460 #            stringlist.append(ant)
00461 #        except ValueError:
00462 #            pass
00463 #
00464 #    print 'Selected reference antenna: ',stringlist
00465 #    print 'indexlist: ',indexlist
00466 #    return indexlist[0]
00467 #
00468 #def readboxfile(boxfile):
00469 #    """ Read a file containing clean boxes (compliant with AIPS BOXFILE)
00470 #
00471 #    Format is:
00472 #    #FIELDID BLC-X BLC-Y TRC-X TRC-Y
00473 #    0       110   110   150   150 
00474 #    or
00475 #    0       hh:mm:ss.s dd.mm.ss.s hh:mm:ss.s dd.mm.ss.s
00476 #
00477 #    Note all lines beginning with '#' are ignored.
00478 #
00479 #    """
00480 #    union=[]
00481 #    f=open(boxfile)
00482 #    while 1:
00483 #        try: 
00484 #            line=f.readline()
00485 #            if (line.find('#')!=0): 
00486 #                splitline=line.split('\n')
00487 #                splitline2=splitline[0].split()
00488 #                if (len(splitline2[1])<6): 
00489 #                    boxlist=[int(splitline2[1]),int(splitline2[2]),
00490 #                    int(splitline2[3]),int(splitline2[4])]
00491 #                else:
00492 #                    boxlist=[splitline2[1],splitline2[2],splitline2[3],
00493 #                    splitline2[4]]
00494 #    
00495 #                union.append(boxlist)
00496 #    
00497 #        except:
00498 #            break
00499 #
00500 #    f.close()
00501 #    print 'union is: ',union
00502 #    return union
00503 
00504 def inp(taskname=None):
00505     try:
00506         a=inspect.stack()
00507         stacklevel=0
00508         for k in range(len(a)):
00509             if (string.find(a[k][1], 'ipython console') > 0):
00510                 stacklevel=k
00511         myf=sys._getframe(stacklevel).f_globals
00512         if((taskname==None) and (not myf.has_key('taskname'))):
00513             print 'No task name defined for inputs display'
00514             return
00515         if taskname==None: taskname=myf['taskname']
00516         myf['taskname']=taskname
00517         if type(taskname)!=str:
00518             taskname=taskname.__name__
00519             myf['taskname']=taskname
00520 
00521         try:
00522             parameter_checktype(['taskname'],taskname,str)
00523         except TypeError, e:
00524             print "inp -- TypeError: ", e
00525             return
00526         except ValueError, e:
00527             print "inp -- OptionError: ", e
00528             return
00529 
00530         ###Check if task exists by checking if task_defaults is defined
00531         if ( not myf.has_key(taskname) and
00532              str(type(myf[taskname])) != "<type 'instance'>" and
00533              not hasattr(myf[taskname],"defaults") ):
00534             raise TypeError, "task %s is not defined " %taskname
00535         if(myf.has_key('__last_taskname')):
00536             myf['__last_taskname']=taskname
00537         else:
00538             myf.update({'__last_taskname':taskname})
00539 
00540         #print '# ',myf['taskname']+' :: '+(eval(myf['taskname']+'.description()'))
00541         print '# ',myf['taskname']+' input on engine', id
00542         update_params(myf['taskname'])
00543     except TypeError, e:
00544         print "inp --error: ", e
00545     except Exception, e:
00546         print "---",e
00547 
00548 def update_params(func, printtext=True):
00549     from odict import odict
00550     a=inspect.stack()
00551     stacklevel=0
00552     for k in range(len(a)):
00553         if (string.find(a[k][1], 'ipython console') > 0):
00554             stacklevel=k
00555     myf=sys._getframe(stacklevel).f_globals
00556     ### set task to the one being called
00557     myf['taskname']=func
00558     obj=myf[func]
00559 
00560     if ( str(type(obj)) == "<type 'instance'>" and
00561          hasattr(obj,"check_params") ):
00562         hascheck = True
00563     else:
00564         hascheck = False
00565 
00566     noerror=True
00567     ###check if task has defined a task_check_params function
00568 
00569     if (hascheck):
00570         has_othertasks = myf.has_key('task_location')
00571         if(has_othertasks) :
00572            has_task = myf['task_location'].has_key(myf['taskname'])
00573            if (has_task) :
00574                 pathname=myf['task_location'][myf['taskname']]
00575            else :
00576                 pathname = os.environ.get('CASAPATH').split()[0]+'/share/xml'
00577         else :
00578            pathname = os.environ.get('CASAPATH').split()[0]+'/share/xml'
00579         xmlfile=pathname+'/'+myf['taskname']+'.xml'
00580         if(os.path.exists(xmlfile)) :
00581             cu.setconstraints('file://'+xmlfile);
00582 
00583     a=myf[myf['taskname']].defaults("paramkeys")
00584 
00585     params=a
00586     itsparams = {}
00587     for k in range(len(params)):
00588         paramval = obj.defaults(params[k])
00589 
00590         notdict=True
00591         ###if a dictionary with key 0, 1 etc then need to peel-open
00592         ###parameters
00593         if(type(paramval)==dict):
00594             if(paramval.has_key(0)):
00595                 notdict=False
00596         
00597         if (notdict ):
00598             if(not myf.has_key(params[k])):
00599                 myf.update({params[k]:paramval})
00600             if(printtext):
00601                 if(hascheck):
00602                     noerror = obj.check_params(params[k],myf[params[k]])
00603                 if(myf[params[k]]==paramval):
00604                     print_params_col(params[k],myf[params[k]],obj.description(params[k]), 'ndpdef', 'black',noerror)
00605                 else:
00606                     print_params_col(params[k],myf[params[k]],obj.description(params[k]), 'ndpnondef', 'black', noerror)
00607                 itsparams[params[k]] = myf[params[k]]
00608         else:
00609             subdict=odict(paramval)
00610             ##printtext is False....called most probably to set
00611             ##undefined params..no harm in doing it anyways
00612             if(not printtext):
00613                 ##locate which dictionary is user selected
00614                 userdict={}
00615                 subkeyupdated={}
00616                 for somekey in paramval:
00617                     somedict=dict(paramval[somekey])
00618                     subkeyupdated.update(dict.fromkeys(somedict, False))
00619                     if(somedict.has_key('value') and myf.has_key(params[k])):
00620                         if(somedict['value']==myf[params[k]]):
00621                             userdict=somedict
00622                     elif(somedict.has_key('notvalue') and myf.has_key(params[k])):
00623                         if(somedict['notvalue']!=myf[params[k]]):
00624                             userdict=somedict
00625                 ###The behaviour is to set to the first default
00626                 ### all non set parameters and parameters that
00627                 ### have no meaning for this selection
00628                 for j in range(len(subdict)):
00629                     subkey=subdict[j].keys()
00630                     for kk in range(len(subkey)):
00631                         
00632                         if( (subkey[kk] != 'value') & (subkey[kk] != 'notvalue') ):
00633                             #if user selecteddict
00634                             #does not have the key
00635                             ##put default
00636                             if((not userdict.has_key(subkey[kk])) and (not subkeyupdated[subkey[kk]])):
00637                                 myf.update({subkey[kk]:subdict[j][subkey[kk]]})
00638                                 subkeyupdated[subkey[kk]]=True
00639                                 
00640                     ###put default if not there
00641                             if(not myf.has_key(subkey[kk])):
00642                                 myf.update({subkey[kk]:subdict[j][subkey[kk]]})
00643                         
00644             ### need to do default when user has not set val
00645             if(not myf.has_key(params[k])):
00646                 if(paramval[0].has_key('notvalue')):
00647                     myf.update({params[k]:paramval[0]['notvalue']})
00648                 else:
00649                     myf.update({params[k]:paramval[0]['value']})
00650             userval=myf[params[k]]
00651             choice=0
00652             notchoice=-1
00653             valuekey='value'
00654             for j in range(len(subdict)):
00655                 if(subdict[j].has_key('notvalue')):
00656                     valuekey='notvalue'
00657                     if(subdict[j]['notvalue'] != userval):
00658                         notchoice=j;
00659                         break
00660                 else:
00661                     if(subdict[j]['value']==userval):
00662                         choice=j
00663                         notchoice=j
00664                         break
00665             subkey=subdict[choice].keys()
00666             if(hascheck):
00667                 noerror=obj.check_params(params[k],userval)
00668             if(printtext):
00669                 if(myf[params[k]]==paramval[0][valuekey]):
00670                     print_params_col(params[k],myf[params[k]],obj.description(params[k]),'dpdef','black', noerror)
00671                 else:
00672                     print_params_col(params[k],myf[params[k]],obj.description(params[k]),'dpnondef','black', noerror)
00673                 itsparams[params[k]] = myf[params[k]]
00674             for j in range(len(subkey)):
00675                 if((subkey[j] != valuekey) & (notchoice > -1)):
00676                     ###put default if not there
00677                     if(not myf.has_key(subkey[j])):
00678                         myf.update({subkey[j]:subdict[choice][subkey[j]]})
00679                     paramval=subdict[choice][subkey[j]]
00680                     if (j==(len(subkey)-1)):
00681                         # last subparameter - need to add an extra line to allow cut/pasting
00682                         comment='last'
00683                     else:
00684                         comment='blue'
00685                     if(hascheck):
00686                         noerror = obj.check_params(subkey[j],myf[subkey[j]])
00687                     if(printtext):
00688                         if(myf[subkey[j]]==paramval):
00689                             print_params_col(subkey[j],myf[subkey[j]],obj.description(subkey[j],userval),'spdef',comment, noerror)
00690                         else:
00691                             print_params_col(subkey[j],myf[subkey[j]],obj.description(subkey[j],userval),'spnondef',comment, noerror)
00692                         itsparams[params[k]] = myf[params[k]]
00693     #print itsparams                    
00694     #
00695     # Verify the complete record, with errors being reported to the user
00696     #
00697     #cu.verify(itsparams, cu.torecord('file://'+xmlfile)[myf['taskname']]);
00698 
00699 ####function to print inputs with coloring
00700 ####colorparam 'blue'=> non-default, colorcomment 'green'=> can have sub params
00701 #### 'blue' => is a sub-parameter 
00702 # blue = \x1B[94m
00703 # bold = \x1B[1m
00704 # red  = \x1B[91m
00705 # cyan = \x1B[96m
00706 # green= \x1B[92m
00707 # normal   = \x1B[0m
00708 # underline= \x1B[04m
00709 # reverse = \x1B[7m
00710 # highlight with black = \x1B[40s
00711 
00712 def print_params_col(param=None, value=None, comment='', colorparam=None,
00713                      colorcomment=None, noerrorval=True):
00714     try:
00715         from TerminalController import TerminalController
00716         term = TerminalController()
00717         cols = term.COLS
00718         del term
00719     except:
00720         cols = 80
00721     #
00722     #print 'colorparam is: ', colorparam
00723     #
00724     if type(value) == str:
00725         printval = "'" + value + "'"
00726     else:
00727         printval = value
00728 
00729     if colorparam == 'ndpnondef':
00730         firstcol = '\x1B[0m'
00731         valcol   = '\x1B[94m'
00732     elif colorparam == 'dpdef':
00733         firstcol = '\x1B[1m' + '\x1B[47m'
00734         valcol   = '\x1B[1m' + '\x1B[0m'
00735     elif colorparam == 'dpnondef':
00736         firstcol = '\x1B[1m' + '\x1B[47m'
00737         valcol   = '\x1B[1m' + '\x1B[94m'
00738     elif colorparam == 'spdef':
00739         firstcol = '\x1B[32m'
00740         valcol   = '\x1B[0m'
00741     elif colorparam == 'spnondef':
00742         firstcol = '\x1B[32m'
00743         valcol   = '\x1B[94m'
00744     else:
00745         firstcol = '\x1B[0m'
00746         valcol   = '\x1B[0m'
00747 
00748     if not noerrorval:
00749         valcol = '\x1B[1m' + '\x1B[91m'
00750 
00751     if colorcomment == 'green':
00752         secondcol = '\x1B[102m'
00753     elif colorcomment == 'blue':
00754         #secondcol='\x1B[104m'
00755         secondcol = '\x1B[0m'
00756     else:
00757         secondcol = '\x1B[0m'
00758 
00759     # RR: I think colorcomment should really be called submenu.
00760     #     Since these are left justified, I've absorbed the right space into
00761     #     the %s's, in order to handle as long a parameter name as possible.
00762     #     (The uvfilterb* params were busting out of %-10s.)
00763     if colorcomment in ('last', 'blue'):
00764         parampart = firstcol + '     %-14s ='
00765     else:
00766         parampart = firstcol + '%-19s ='
00767     parampart %= param
00768 
00769     valpart = valcol + ' %10s \x1B[0m' % printval + secondcol
00770     # Well behaved (short) parameters and values tally up to 33 characters
00771     # so far.  Pad them up to 40, assuming the param is short enough.
00772     pad = 7
00773     paramlen = len(str(param))
00774     if colorcomment in ('last', 'blue') and paramlen > 14:
00775         pad -= paramlen - 14
00776     elif paramlen > 19:
00777         pad -= paramlen - 19
00778     valuelen = len(str(printval))
00779     if valuelen > 10:
00780         pad -= valuelen - 10
00781     if pad > 0:
00782         valpart += ' ' * pad
00783 
00784     try:
00785         from textwrap import fill
00786         if pad < 0:
00787             firstskip = 40 - pad
00788             firstfiller = ' ' * firstskip + '#  '
00789             afterfiller = ' ' * 40 + '#   '
00790         else:
00791             firstskip = 40
00792             firstfiller = ' ' * 40 + '#  '
00793             afterfiller = firstfiller + ' '
00794         commentpart = fill(comment, cols, initial_indent=firstfiller,
00795                            subsequent_indent=afterfiller)[firstskip:]
00796     except:
00797         if comment:
00798             commentpart = '#  ' + comment
00799         else:
00800             commentpart = ''
00801     commentpart += '\x1B[0m'          # RR: I think this might be redundant.
00802     if colorcomment == 'last':        #     (Is colorcomment ever green?)
00803         commentpart += "\n"
00804 
00805     #print parampart + valpart + commentpart
00806     print parampart + valpart
00807 
00808 def __set_default_parameters(b):
00809     a=inspect.stack()
00810     stacklevel=0
00811     for k in range(len(a)):
00812         if (string.find(a[k][1], 'ipython console') > 0):
00813             stacklevel=k
00814     myf=sys._getframe(stacklevel).f_globals
00815     a=b
00816     elkey=a.keys()
00817     for k in range(len(a)):
00818         if (type(a[elkey[k]]) != dict):
00819             myf[elkey[k]]=a[elkey[k]]
00820         elif (type(a[elkey[k]]) == dict and len(a[elkey[k]])==0):
00821             myf[elkey[k]]=a[elkey[k]]
00822         else:
00823             subdict=a[elkey[k]]
00824             ##clear out variables of other options if they exist
00825             for j in range(1,len(subdict)):
00826                 subkey=subdict[j].keys()
00827                 for kk in range(len(subkey)):
00828                     if((subkey[kk] != 'value') & (subkey[kk] != 'notvalue') ):
00829                         if(myf.has_key(subkey[kk])):
00830                             del myf[subkey[kk]]
00831             ###
00832             if(subdict[0].has_key('notvalue')):
00833                 myf[elkey[k]]=subdict[0]['notvalue']
00834             else:
00835                 myf[elkey[k]]=subdict[0]['value']
00836             subkey=subdict[0].keys()
00837             for j in range(0, len(subkey)):
00838                 if((subkey[j] != 'value') & (subkey[j] != 'notvalue')):
00839                     myf[subkey[j]]=subdict[0][subkey[j]]
00840 
00841 def saveinputs(taskname=None, outfile='', myparams=None):
00842     #parameter_printvalues(arg_names,arg_values,arg_types)
00843     """ Save current input values to file on disk for a specified task:
00844 
00845     taskname -- Name of task
00846         default: <unset>; example: taskname='bandpass'
00847         <Options: type tasklist() for the complete list>
00848     outfile -- Output file for the task inputs
00849         default: taskname.saved; example: outfile=taskname.orion
00850 
00851     """
00852 
00853     try:
00854         a=inspect.stack()
00855         stacklevel=0
00856         for k in range(len(a)):
00857             if (string.find(a[k][1], 'ipython console') > 0):
00858                 stacklevel=k
00859         myf=sys._getframe(stacklevel).f_globals
00860         if taskname==None: taskname=myf['taskname']
00861         myf['taskname']=taskname
00862         if type(taskname)!=str:
00863             taskname=taskname.__name__
00864             myf['taskname']=taskname
00865 
00866         parameter_checktype(['taskname','outfile'],[taskname,outfile],[str,str])
00867 
00868         ###Check if task exists by checking if task_defaults is defined
00869         obj = False
00870         if ( not myf.has_key(taskname) and
00871              str(type(myf[taskname])) != "<type 'instance'>" and
00872              not hasattr(myf[taskname],"defaults") ):
00873             raise TypeError, "task %s is not defined " %taskname
00874         else:
00875             obj = myf[taskname]
00876 
00877         if taskname==None: taskname=myf['taskname']
00878         myf['taskname']=taskname
00879         if outfile=='': outfile=taskname+'.saved'
00880         ##make sure unfolded parameters get their default values
00881         myf['update_params'](func=myf['taskname'], printtext=False)
00882         ###
00883         taskparameterfile=open(outfile,'w')
00884         print >>taskparameterfile, '%-15s    = "%s"'%('taskname', taskname)
00885         print >>taskparameterfile,myf[taskname].__call__.func_defaults
00886         print >>taskparameterfile,myf[taskname].__call__.func_code.co_varnames
00887 
00888         f=zip(myf[taskname].__call__.func_code.co_varnames,myf[taskname].__call__.func_defaults)
00889         scriptstring='#'+str(taskname)+'('
00890         if myparams == None :
00891                 myparams = {}
00892         for j in range(len(f)):
00893             k=f[j][0]
00894             if not myparams.has_key(k) and k != 'self' :
00895                     myparams[k] = myf[k]
00896             if(k != 'self' and type(myparams[k])==str):
00897                 if ( myparams[k].count( '"' ) < 1 ):
00898                     # if the string doesn't contain double quotes then
00899                     # use double quotes around it in the parameter file.
00900                     print >>taskparameterfile, '%-15s    =  "%s"'%(k, myparams[k])
00901                     scriptstring=scriptstring+k+'="'+myparams[k]+'",'
00902                 else:
00903                     # use single quotes.
00904                     print >>taskparameterfile, "%-15s    =  '%s'"%(k, myparams[k])
00905                     scriptstring=scriptstring+k+"='"+myparams[k]+"',"
00906             else :
00907                 if ( j != 0 or k != "self" or
00908                      str(type(myf[taskname])) != "<type 'instance'>" ) :
00909                     print >>taskparameterfile, '%-15s    =  %s'%(k, myparams[k])
00910                     scriptstring=scriptstring+k+'='+str(myparams[k])+','
00911 
00912             ###Now delete varianle from global user space because
00913             ###the following applies: "It would be nice if one
00914             ### could tell the system to NOT recall
00915             ### previous non-default settings sometimes."
00916             if(not myf['casaglobals']):
00917                 del myf[k]
00918         scriptstring=scriptstring.rstrip(',')
00919         scriptstring=scriptstring+')'        
00920         print >>taskparameterfile,scriptstring
00921         taskparameterfile.close()
00922     except TypeError, e:
00923         print "saveinputs --error: ", e
00924 
00925 def default(taskname=None):
00926     """ reset given task to its default values :
00927 
00928     taskname -- Name of task
00929 
00930 
00931     """
00932 
00933     try:
00934         a=inspect.stack()
00935         stacklevel=0
00936         for k in range(len(a)):
00937             if (string.find(a[k][1], 'ipython console') > 0):
00938                 stacklevel=k
00939                 break
00940         myf=sys._getframe(stacklevel).f_globals
00941         if taskname==None: taskname=myf['taskname']
00942         myf['taskname']=taskname
00943         if type(taskname)!=str:
00944             taskname=taskname.__name__
00945             myf['taskname']=taskname
00946 
00947         ###Check if task exists by checking if task_defaults is defined
00948         if ( not myf.has_key(taskname) and
00949              str(type(myf[taskname])) != "<type 'instance'>" and
00950              not hasattr(myf[taskname],"defaults") ):
00951             raise TypeError, "task %s is not defined " %taskname
00952         eval(myf['taskname']+'.defaults()')
00953 
00954         casalog.origin('default')
00955         taskstring=str(taskname).split()[0]
00956         casalog.post(' #######  Setting values to default for task: '+taskstring+'  #######')
00957 
00958 
00959     except TypeError, e:
00960         print "default --error: ", e
00961 
00962 ####################
00963 
00964 #def exit():
00965 #    __IPYTHON__.exit_now=True
00966 #    #print 'Use CNTRL-D to exit'
00967 #    #return
00968 
00969 #import pylab as pl
00970 
00971 #
00972 # 
00973 import platform
00974 ##
00975 ## CAS-951: matplotlib unresponsive on some 64bit systems
00976 ##
00977 #if (platform.architecture()[0]=='64bit'):
00978 #    pl.ioff( )
00979 #    pl.clf( )
00980 #    pl.ion( )
00981 ##
00982 ##
00983 
00984 # Provide flexibility for boolean representation in the CASA shell
00985 true  = True
00986 T     = True
00987 false = False
00988 F     = False
00989 
00990 # run casapy non-interactively on engine
00991 ipython=False
00992 
00993 # setup available tasks
00994 #
00995 from math import *
00996 
00997 #from tasks import *
00998 #cannot do this because
00999 # tasks imports xxx_cli
01000 # xxx_pg imports taskmanager
01001 # taskmanager starts a cluster and 4 engines
01002 
01003 
01004 from parameter_dictionary import *
01005 from task_help import *
01006 #
01007 #home=os.environ['HOME']
01008 #if ipython:
01009 #    startup()
01010 
01011 # assignment protection
01012 #
01013 #pathname=os.environ.get('CASAPATH').split()[0]
01014 #uname=os.uname()
01015 #unameminusa=str.lower(uname[0])
01016 #fullpath=pathname+'/'+unameminusa+'/python/2.5/assignmentFilter.py'
01017 casalog.origin('casa')
01018 ##
01019 ## /home/casa-dev-01/hye/gnuactive/linux_64b/python/2.5  is substitued at build time
01020 ##
01021 #fullpath='/home/casa-dev-01/hye/casapy-casapy-23.1.6826-006-64b/lib64/python2.5'
01022 #sys.path.insert(2, fullpath)
01023 #fullpath='/usr/lib64/casapy/23.1.6826-006/lib/python2.5/assignmentFilter.py'
01024 
01025 #if os.environ.has_key('__CASAPY_PYTHONDIR'):
01026 #    fullpath=os.environ['__CASAPY_PYTHONDIR'] + '/assignmentFilter.py'
01027 
01028 #utilstool = casac.homefinder.find_home_by_name('utilsHome')
01029 #cu = casac.cu = utilstool.create()
01030 
01031 casalog.setlogfile(thelogfile)
01032 casalog.showconsole(False)
01033 casalog.version()
01034 
01035 def stop_all():
01036     #os.kill(pid,9)
01037     print "leaving casapy..."
01038 
01039 def setcwd(dir='.'):
01040     os.chdir(dir)
01041 
01042 def get_host():
01043     import commands
01044     return commands.getoutput("uname -n")
01045 
01046 import shutil
01047 
01048 def delete_scratch():
01049     for x in os.listdir('.'):
01050        if x.lower().startswith('casapy.scratch-'):
01051           if os.path.isdir(x):
01052              #shutil.rmtree(x, ignore_errors=True)
01053              os.system("rm -rf %s" % x)
01054              #print "Removed: ", x, "\n"
01055 
01056 if __name__ == "__main__":
01057    print "start casapy engine---"