stop NOTICE : All NRAO Public Wiki users MUST Change or reset their passwords (click here to change or click here to reset) by TUESDAY, APRIL 29, 2014.
Remember to use your LoginName (e.g., JohnPublic), not your email address.

Python Task Template

Prototyping A Task

The following example illustrates how a user could develop a task that behaves similarly to the tasks native to CASA. There are three parts to the python script:

  1. Define a cinp (custom inp command to view inputs)
  2. Define a csaveinputs (custom saveinputs command to save inputs to file)
  3. Define the task itself

Note: parts 1 and 2 are only needed if you want to have the same ability to query and save the inputs.

In the following example, I reproduce the listobs task native to CASA through the example task implemented in 'example.py'.

Define a cinp

# Needed libraries to use
import sys
from parameter_check import *

# Create a custom 'inp' command for your task - currently it has to be separate
# from the existing value (this will be made easier in the future)
def cinp():
        """ Print out current input values for a specified task: """
        # retrieve the global namespace
        myf=sys._getframe(1).f_globals
        # retrieve each parameter needed by your task via this sequence
        # parameter = myf['parameter']
        # this retrieves the global value for the parameter
        vis=myf['vis']
        verbose=myf['verbose']
        # print out the inputs to your task
        print ''
        print 'example -- List the observations in a data set:'
        print ''
        print 'vis         = "'+str(vis)+'"','\t: Name of input visibility file (MS)'
        print 'verbose     = ',verbose,'\t: List each observation in addition to summary'
#

Define a csaveinputs

# Save inputs
def csaveinputs(outfile=''):
        """ Save current input values to file on disk for a specified task:
        outfile -- Output file for the task inputs
                default: taskname.saved; example: outfile=taskname.orion

        """
        # as above; grab global namespace and values for used parameters
        myf=sys._getframe(1).f_globals
        vis=myf['vis']
        verbose=myf['verbose']
        if outfile=='': outfile='example.saved'
        taskparameterfile=open(outfile,'w')
        print >>taskparameterfile, 'vis         = "'+str(vis)+'"'
        print >>taskparameterfile, 'verbose     = ',verbose

Define the task functionality

def example(vis=None,verbose=None):
        """List the observations in a dataset:

        Keyword arguments:
        vis -- Name of input visibility file (MS)
                default: ; example: vis='ngc5921.ms'
        verbose -- List each observation in addition to the summary
                default=False; example: verbose=True
                

        """
        # All documentation that you would like goes between the triple double
        # quotes above - format it as you like to see it.
        # Get the global namespace
        myf=sys._getframe(1).f_globals
        # Retrieve the saveinputs command from global
        saveinputs=myf['saveinputs']
        # Retrieve the tool(s) that you will use in your task
        # example is just a copy of 'listobs' which uses the 'ms' tool
        ms=myf['ms']
        ###
        # Keep the following as is, change only the name of your task
        #Handle globals or user over-ride of arguments
        function_signature_defaults=dict(zip(example.func_code.co_varnames,example.func_defaults))
        #                                    ^^^^^^^ here     and          ^^^^^^^ here
        # Keep the following as is:
        for item in function_signature_defaults.iteritems():
                key,val = item
                keyVal = eval(key)
                if (keyVal == None):
                        #user hasn't set it - use global/default
                        pass
                else:
                        myf[key]=keyVal
                        #user has set it - use over-ride
        # Put in the parameters that you have in your task
        vis=myf['vis']
        verbose=myf['verbose']
        #
        ###
        #Add type/menu/range error checking here
        arg_names=['vis','verbose']
        arg_values=[vis,verbose]
        arg_types=[str,bool]
        #parameter_printvalues(arg_names,arg_values,arg_types)
        try:
                parameter_checktype(arg_names,arg_values,arg_types)
        except TypeError, e:
                print "example -- TypeError: ", e
                return
        ###

        #Python script - the actual toolkit commands used to
        # implement your task
        ms.open(thems=vis)
        ms.summary(verbose=verbose)
        ms.close()

How it works

CASA <1>: from example import * # import your task into the environment

CASA <2>: cinp
--------> cinp()

example -- List the observations in a data set:

vis         = "False"   : Name of input visibility file (MS)
verbose     =  False    : List each observation in addition to summary

CASA <3>: vis='n1333.ms'

CASA <4>: cinp
--------> cinp()

example -- List the observations in a data set:

vis         = "n1333.ms"        : Name of input visibility file (MS)
verbose     =  False    : List each observation in addition to summary

CASA <5>: example
--------> example()

CASA <6>: csaveinputs 
--------> csaveinputs()

CASA <7>: !more example.saved
vis         = "n1333.ms"
verbose     =  False

A more detailed look at the task definition:

There are essentially four parts to the template:
  1. setup
  2. function definition and documentation
  3. error checking
  4. python script

Part 1: Setup

#load system modules
import sys
#load parameter checking modules
from parameter_check import *

Part 2: Function definition and documentation

def taskname(arg1=value, arg2=value,...argn=value):
       """ Basic description of the task

       Keyword arguments:
       arg1 -- description of arg1
                 default: value; example: arg1=somevalue
       arg2 -- description of arg2
                 default: value; example: arg2=somevalue
       ...
       argn -- description of argn
                 default: value; example: argn=somevalue
                 

       """

Note: *

Part 3: Error checking and Interface handling

        myf=sys._getframe(1).f_globals
        #tool abbreviation is: ms, cb, im, sm, af etc.
        tool_abbreviation=myf['tool_abbreviation']
        ###
        #Handle globals or user over-ride of arguments
        function_signature_defaults=dict(zip(taskname.func_code.co_varnames,taskname.func_d
efaults))
        for item in function_signature_defaults.iteritems():
                key,val = item
                keyVal = eval(key)
                if (keyVal == None):
                        #user hasn't set it - use global/default
                        pass
                else:
                        #user has set it - use over-ride
                        myf[key]=keyVal

        arg1=myf['arg1']
        arg2=myf['arg2']
        #etc

        #Add type/menu/range error checking here
        arg_names=['arg1','arg2','argn']
        arg_values=[arg1,arg2,argn]
        arg_types=[type,type,type]
        try:
                parameter_checktype(arg_names,arg_values,arg_types)
                parameter_checkmenu('fitmode',fitmode,['subtract','replace','model'])
        except TypeError, e:
                print "contsub -- TypeError: ", e
                return
        except ValueError, e:
                print "contsub -- OptionError: ", e
                return
        ###

Part 4: Python script

        #Python script
        tool_abbrev.open(arg1)
        tool_abbrev.method1(arg2)
        tool_abbrev.method2(argn)
        tool_abbrev.close()

Complete Example (contsub.py)

import sys

from parameter_check import *

def contsub(vis=None,fieldid=None,spwid=None,channels=None,solint=None,fitorder=None,
        fitmode=None):
        """Continuum fitting and subtraction in the uv plane:

        Keyword arguments:
        vis -- Name of input visibility file (MS)
                default: ; example: vis='ngc5921.ms'
        fieldid -- Field index identifier
                default=unset; example: fieldid=1
        spwid -- Spectral window index identifier
                default=0; example: spwid=1
        channels -- Range of channels to fit
                default:; example: channels=range(4,7)+range(50,60)
        solint -- Averaging time (seconds)
                default: 0.0 (scan-based); example: solint=10
        fitorder -- Polynomial order for the fit
                default: 0; example: fitorder=1
        fitmode -- Use of the continuum fit model
                default: 'subtract'; example: fitmode='replace'
                

        """
        myf=sys._getframe(1).f_globals
        ms=myf['ms']
        ###
        #Handle globals or user over-ride of arguments
        function_signature_defaults=dict(zip(contsub.func_code.co_varnames,contsub.func_defaults
))
        for item in function_signature_defaults.iteritems():
                key,val = item
                keyVal = eval(key)
                if (keyVal == None):
                        #user hasn't set it - use global/default
                        pass
                else:
                        #user has set it - use over-ride
#                       #sys._getframe().f_globals[key]=keyVal
                        myf[key]=keyVal

        vis=myf['vis']
        fieldid=myf['fieldid']
        spwid=myf['spwid']
        channels=myf['channels']
        solint=myf['solint']
        fitorder=myf['fitorder']
        fitmode=myf['fitmode']
        #
        ###

        #
        ###

        #Add type/menu/range error checking here
        arg_names=['vis','fieldid','spwid','channels','solint','fitorder','fitmode']
        arg_values=[vis,fieldid,spwid,channels,solint,fitorder,fitmode]
        arg_types=[str,int,int,list,float,int,str]
        try:
                parameter_checktype(arg_names,arg_values,arg_types)
                parameter_checkmenu('fitmode',fitmode,['subtract','replace','model'])
        except TypeError, e:
                print "contsub -- TypeError: ", e
                return
        except ValueError, e:
                print "contsub -- OptionError: ", e
                return
        ###


        #Python script
        ms.open(vis,nomodify=False)
        ms.continuumsub(fldid=fieldid,spwid=spwid,chans=channels,
                solint=solint,mode=fitmode)
        ms.close()

        saveinputs=myf['saveinputs']
        saveinputs('contsub','contsub.last')

-- JosephMcMullin - 22 Sep 2006 * example.py.txt: example.py.txt
Topic revision: r6 - 2013-02-13, PatrickMurphy
 

This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding NRAO Public Wiki? Send feedback