casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
flagcmd.py
Go to the documentation of this file.
00001 #
00002 # This file was generated using xslt from its XML file
00003 #
00004 # Copyright 2009, Associated Universities Inc., Washington DC
00005 #
00006 import sys
00007 import os
00008 from  casac import *
00009 import string
00010 from taskinit import casalog
00011 #from taskmanager import tm
00012 import task_flagcmd
00013 def flagcmd(vis='', inpmode='table', inpfile='', tablerows=[], reason='any', useapplied=False, tbuff=0.0, ants='', action='apply', flagbackup=True, clearall=False, rowlist=[], plotfile='', savepars=False, outfile=''):
00014 
00015         """Flagging task based on batches of flag-commands
00016 
00017     Flag commands follow the mode and parameter names from the flagdata task
00018     (also explained below).  The available modes are: manual, clip, shadow, quack, 
00019     elevation,  tfcrop, rflag, extend and unflag.
00020 
00021     The flagcmd task will flag data based on the commands input on inpmode:
00022         table = input from FLAG_CMD table in MS
00023         list  = input from a file or a (Python) list of command strings
00024         xml   = input from Flag.xml in the MS given by vis
00025 
00026     Batch operations include : apply/unapply/list/plot/clear/extract
00027 
00028     IMPORTANT: The FLAG_CMD sub-table is meant only for meta-data selections such as online flags.
00029                Using it to save other parameters (from modes such as clip, quack, shadow, etc) is
00030                possible but carries a risk that in future releases these parameters maybe renamed
00031                or changed their default values. Use it at your own risk! There will be no automatic
00032                way to rename any parameter that changes in the future.
00033                
00034     NOTE on flagging calibration tables.
00035     -----------------------------------
00036     
00037     It is possible to flag cal tables using this task, although we recommend using the flagdata
00038     task for this.
00039     
00040     When using this task to flag cal tables, only the apply and list actions are supported. 
00041     Because cal tables do not have a FLAG_CMD sub-table, the default inpmode='table' can only 
00042     be used if an MS is given in the inpfile parameter so that flags from the MS are applied to 
00043     the cal table. Otherwise, the flag commands must be given using inpmode='list', either from a 
00044     file or from a list of strings. See below for more information about these parameters. 
00045     Data selection for calibration tables is limited to field, antenna and spw at the moment. 
00046 
00047 
00048     Keyword arguments:
00049 
00050     vis -- Name of input visibility file or calibration table.
00051             default: '' (none) 
00052             example1: vis='uid___A002_X2a5c2f_X54.ms' or
00053             example2: vis='cal-X54.B1'
00054 
00055     -- INPUT of flag commands --
00056 
00057     inpmode -- Input mode for flag commands.
00058             options: 'table','list','xml'
00059             default: 'table'
00060 
00061        inpmode "table" --  input commands from FLAG_CMD table of MS.
00062    
00063           inpfile -- path to MS containing FLAG_CMD
00064                default: '' (read from FLAG_CMD table in the MS specified via 'vis')
00065 
00066                Main use is to read flags from internal FLAG_CMD,
00067                but by setting inpfile to a different MS you can 
00068                use this to copy the flags from one MS to another.
00069                
00070                One use case is to read the flag commands from an MS given in
00071                inpfile and apply them to a cal table given in vis. Example:
00072              
00073              flagcmd(vis='cal-X54.B1', inpmode='table', inpfile='uid___A002_X2a5c2f_X54.ms', action='apply')
00074 
00075           tablerows -- list of rows of the FLAG_CMD table to read
00076                default: [] (read all rows)
00077                example: [0,1,2,10]
00078 
00079                NOTE: currently only takes integer lists, not
00080                parseable strings with ranges.  Use the Python
00081                range function to generate ranges, e.g.
00082                   tablerows = range(0,30) + range(50,55)
00083                instead of '0~29,50~54' for now.
00084    
00085           reason -- select flag commands based on REASON(s) 
00086                default: 'any' (all flags regardless of reason)
00087                         can be a string, or list of strings
00088                example: reason='FOCUS_ERROR'
00089                         reason=['FOCUS_ERROR','SUBREFLECTOR_ERROR']
00090 
00091                NOTE: what is within the string is literally
00092                mateched, e.g. reason='' matches only blank reasons, 
00093                and reason = 'FOCUS_ERROR,SUBREFLECTOR_ERROR'
00094                matches this compound reason string only
00095 
00096           useapplied -- select the flag commands of rows that have APPLIED=True
00097                options: True,False
00098                default: False   
00099 
00100                If useapplied=True it will read in both applied and
00101                unapplied flags
00102 
00103 
00104        inpmode "list" -- input commands from an ASCII file or via a list of strings.
00105    
00106           inpfile -- name of an ASCII file or a list of strings.
00107                default: '' 
00108                options: [] or '' with filename.
00109                   example1: the following commands can be saved into a file and given
00110                             to the task (e.g. save it to flags.txt).
00111                   
00112                      scan='1~3' mode='manual'
00113                      mode='clip' clipminmax=[0,2] correlation='ABS_XX' clipoutside=False
00114                      spw='9' mode='tfcrop' correlation='ABS_YY' ntime=51.0
00115                      mode='extend' extendpols=True
00116 
00117                     flagcmd(vis, inpmode='list',inpfile='flags.txt')
00118 
00119                example2: the same commands can be written in a Python list of strings and given
00120                              to the task.
00121                      cmd=["scan='1~3' mode='manual'", 
00122                           "mode='clip' clipminmax=[0,2] correlation='ABS_XX' clipoutside=False",
00123                           "spw='9' mode='tfcrop' correlation='ABS_YY' ntime=51.0",
00124                           "mode='extend' extendpols=True"]
00125 
00126                      flagcmd(vis, inpmode='list',inpfile=cmd)                    
00127 
00128 
00129           reason -- select flag commands based on REASON(s) 
00130                default: 'any' (all flags regardless of reason)
00131                         can be a string, or list of strings
00132                example: reason='FOCUS_ERROR'
00133                         reason=['FOCUS_ERROR','SUBREFLECTOR_ERROR']
00134 
00135                NOTE: what is within the string is literally
00136                mateched, e.g. reason='' matches only blank reasons, 
00137                and reason = 'FOCUS_ERROR,SUBREFLECTOR_ERROR'
00138                matches this compound reason string only
00139 
00140    
00141        inpmode "xml" -- input online flags from Flag.xml file in the MS. This mode
00142                         is not available for cal tables.
00143    
00144           tbuff -- (float) time padding buffer (seconds, default=1.0)
00145    
00146           ants -- select flags based on antenna, 
00147                     e.g. antenna='ea01'
00148                default: '' (all flags regardless of antenna)
00149    
00150           reason -- select flag commands based on REASON(s), 
00151                default: 'Any' (all flags regardless of reason)
00152                         can be a string, or list of strings
00153                example: reason='FOCUS_ERROR'
00154                         reason=['FOCUS_ERROR','SUBREFLECTOR_ERROR']
00155 
00156                NOTE: what is within the string is literally
00157                mateched, e.g. reason='' matches only blank reasons, 
00158                and reason = 'FOCUS_ERROR,SUBREFLECTOR_ERROR'
00159                matches this compound reason string only
00160 
00161     --ACTIONS--
00162 
00163     action -- operation to perform on MS and/or in flag commands from inpfile
00164             options: 'apply','clear','list','plot','unapply','extract'
00165             default: 'apply'
00166 
00167        action "apply" --  apply flags to MS or cal table.
00168    
00169           This operation will apply the commands chosen by inpmode.       
00170           If inpmode='table' it will set the APPLIED column to True.
00171           
00172           flagbackup -- Automatically backup MS/cal table FLAG column before applying.
00173                options: True,False
00174                default: True
00175 
00176    
00177        action "unapply" --  unapply flags in MS. (Not available for cal tables)
00178 
00179           This operation will unapply the commands chosen by inpmode.
00180           If inpmode='table' it will set the APPLIED column to False. 
00181           
00182           IMPORTANT: In order to guarantee that only the data selected in 
00183           the command is unapplied, the framework will first unapply the selected
00184           rows and then re-apply the overlapping data that got unapplied in the
00185           first pass. This is a true unapply action, but it will take longer to
00186           process because it will re-apply all the remaining commands that have
00187           APPLIED = True!
00188    
00189           flagbackup -- Automatically backup MS FLAG column before unapplying?
00190                options: True,False
00191                default: True
00192 
00193 
00194        action "list" --  list and/or save flag commands. 
00195 
00196           This operation will list the commands chosen by inpmode on the screen
00197           and save them to the MS or to a file without applying. It will save the commands
00198           to outfile if the parameter savepars is set to True. If outfile is None, it
00199           will save the commands to the MS given in vis.
00200 
00201 
00202        action "plot" --  plot flags (ant vs. time). (Not available for cal tables)
00203 
00204           This operation will plot the flags chosen by inpmode to a 
00205           matplotlib gui or to a file.  These will be sorted by
00206           antenna vs. time.  Most useful for showing the online
00207           flags.
00208 
00209           plotfile -- output plot file
00210                default: '' (plot to matplotlib window)
00211 
00212                WARNING: will only reliably plot individual flags
00213                per antenna and timerange (e.g. direct from xml)
00214    
00215        action "clear" --  clear flags from FLAG_CMD in MS. (Not available for cal tables)
00216 
00217           This operation will delete the selected flag rows from
00218           the internal FLAG_CMD table of the MS.
00219 
00220           NOTE: choosing this option will disregard anything you
00221           set in inpmode and will always work on the FLAG_CMD table
00222           in vis.
00223 
00224           clearall -- really clear all flags?
00225                default: False (will not clear)
00226 
00227           rowlist -- list of FLAG_CMD rows to clear
00228                default: [] (all flags in table)
00229                example: [0,1,2,10]
00230 
00231                NOTE: currently only takes integer lists, not
00232                parseable strings with ranges.  Use the Python
00233                range function to generate ranges, e.g.
00234                   rowlist = range(0,30) + range(50,55)
00235                instead of '0~29,50~54' for now.
00236    
00237           WARNING: this can be dangerous, and you must set clearall=True 
00238           to use this!!! This will delete the specified rows from the 
00239           internal FLAG_CMD table for vis regardless of what mode is set
00240           to (useful for when you import from xml or file), and decide to 
00241           redo it). This action will NOT unapply the commands.
00242 
00243 
00244        action "extract" -- extract internal flag dictionary. (Not available for cal tables)
00245 
00246           This option will return the internal flagging dictionary to
00247           python.
00248 
00249 
00250     savepars -- Save the flag commands to the FLAG_CMD table of the MS or to an output text file.
00251             default: False
00252             options: True/False
00253             
00254             outfile -- Name of output file to save the flag commands.
00255                 default: ' '; it will save the commands in the FLAG_CMD table of the MS.
00256                 example: outfile='flags.txt' will save the parameters in a text file.
00257 
00258      ===========================================================================
00259 
00260      -- Internal FLAG_CMD input 'inpmode' useage --
00261 
00262         (For inpmode='table')
00263 
00264        * It is a good idea to use action='list' first to see what is there
00265         before doing anything else, e.g.
00266         
00267           inpmode = 'table'
00268           action = 'list'
00269 
00270        * To apply the flags stored in the FLAG_CMD table in the MS,
00271         simply set inpmode='table' and action='apply', e.g.
00272 
00273           inpmode = 'table'
00274           action = 'apply'
00275           useapplied = False
00276 
00277         This is the default setup of flagcmd.
00278 
00279        * To merely save to FLAG_CMD but not apply, then
00280         
00281           inpmode = 'table'
00282           inpfile = 'other.ms'
00283           action = 'list'
00284           
00285        * To save commands from a file into the MS without applying.
00286         
00287           inpmode = 'list'
00288           inpfile = 'flags.txt'
00289           action = 'list'
00290 
00291         If you need to select only certain rows from the FLAG_CMD table,
00292         use the tablerows parameter to control this.  Currently this must
00293         be a list of individual row numbers (0-based), e.g.
00294 
00295           tablerows = [0,1,2,3,10,11]
00296 
00297         or
00298 
00299           tablerows = range(29)
00300 
00301         NOTE: the useapplied=True/False tag is important if you are
00302         going to (re)apply flags marked as APPLIED True in FLAG_CMD. 
00303         It is common to have a "failed" flagging operation mark the flags
00304         as already applied and then they don't show up when you re-run
00305         (e.g. in 'list').  Set useapplied=True so that it will use these
00306         anyway.
00307         
00308        * To apply the flag commands from an MS to a calibration table.
00309        
00310        vis = 'mycaltable'
00311        inpmode = 'table'
00312        inpfile = 'myMS.ms' 
00313        action = 'apply'
00314        
00315 
00316      -- Online flag input inpmode useage --
00317 
00318         (For inpmode='xml')
00319 
00320        * To list the online flags stored in the Flag.xml file in the
00321          MS, simply set:
00322 
00323           inpmode = 'xml'
00324           action = 'list'
00325           savepars = False
00326 
00327        * It is then straightforward to save these to FLAG_CMD
00328 
00329           inpmode = 'xml'
00330           action = 'list'
00331           savepars = True
00332 
00333        * To directly apply the online flags stored in the Flag.xml file in the
00334         MS, set inpmode='xml' and desired buffer, e.g.
00335 
00336           inpmode = 'xml'
00337           tbuff = 1.0    # pad flag times by 1 sec
00338           action = 'apply'
00339           set savepars to save or not the commands in the MS
00340 
00341        * You can also specify a set of reasons (a comma separated list)
00342         for flags to apply, e.g.
00343         
00344           reason = 'FOCUS_ERROR,SUBREFLECTOR_ERROR'   # select these flags
00345           reason = 'ANTENNA_NOT_ON_SOURCE'
00346 
00347         NOTE: The online flag time buffer tbuff is specified in
00348         seconds, but in fact should be keyed to the intrinsic online 
00349         integration time.  This is particularly true for EVLA data,
00350         were a tbuff value of 0.5x to 1.5x the integration time is
00351         needed (currently you should use 1.5x for data taken in
00352         early 2011 or before).
00353 
00354         Because the Flag.xml is copied to the MS by importevla,
00355         you can re-apply the online flags with an increased tbuff
00356         simply by running with inpmode='xml' and optype='apply', e.g.
00357 
00358           inpmode = 'xml'
00359           tbuff = 15.0    # pad flag times by 15 sec for 10sec integrations
00360           optype = 'apply'
00361 
00362         if you originally used a smaller value (e.g. 1.0) by mistake
00363         or you want to try longer values.  Note these will be added to
00364         the FLAG_CMD table which you would have to clean up manually
00365         if you care about this.
00366 
00367 
00368      -- Flag command useage --
00369 
00370         (For inpmode='list')
00371 
00372        * For example, a series of commands might be:
00373 
00374           antenna='ea01' timerange='00:00:00~01:00:00'
00375           antenna='ea11' timerange='00:00:00~03:00:00' spw='0~4'
00376           mode='clip' clipminmax=[0,5] correlation='ABS_ALL'
00377           mode='quack' quackmode='end' quackinterval=1.0
00378           mode='shadow'
00379 
00380         Any other mode can also use selection (see the help of flagdata):
00381 
00382           mode='shadow' antenna='ea01,ea02,ea03'
00383           mode='quack' quackmode='end' quackinterval=1.0 antenna='ea22'
00384 
00385         These commands can be saved in an ASCII file, e.g. "myflags.txt"
00386         and input using inpmode='list', e.g.
00387 
00388           flagcmd(vis='myvis.ms',inpmode='list',inpfile='myflags.txt')
00389 
00390         or input from the interface
00391 
00392           flagcmd(vis='myvis.ms',inpmode='list',
00393                   inpfile=["mode='shadow'",
00394                            "mode='clip' clipminmax=[0,5] correlation='ABS_ALL'",
00395                            "mode='quack' quackmode='end' quackinterval=1.0",
00396                            "antenna='ea01' timerange='00:00:00~01:00:00'",
00397                            "antenna='ea11' timerange='00:00:00~03:00:00' spw='0~4'"])
00398 
00399 
00400      -- ACTIONs --
00401 
00402         The action parameter controls what flagcmd will actually do with the
00403         flag commands:
00404 
00405         * action = 'apply'
00406 
00407           This will apply the selected commands to the data.
00408           
00409           If inpmode='table' and inpfile='' then the APPLIED column in FLAG_CMD
00410           will be set to True.
00411 
00412         * action = 'unapply'
00413 
00414           This will effectively unapply any commands on the selected data.
00415 
00416         * action = 'list'
00417 
00418           List what is selected and or save in the MS or in a file. It is wise to do 
00419           this first before doing any other action. It will list the output in the logger 
00420           and save them to the FLAG_CMD table of the MS when savepars=True and outfile = '' or 
00421           to a file if outfile is non-blank.
00422 
00423         * action = 'plot'
00424 
00425           Will pop up a little matplotlib GUI (if outfile='') or plot to a
00426           file.  Currently only gives an antenna vs time plot, mostly useful
00427           for looking at the online flags.
00428 
00429         * action = 'clear'
00430           
00431           DANGER! This can be used to totally delete rows from the FLAG_CMD
00432           table. It ignores what inpmode is pointing to and always works
00433           on FLAG_CMD.  Use at your own peril but sometimes you need to just
00434           blow that table away, e.g.
00435 
00436             vis = msfile
00437             optype = 'clear'
00438             rowlist = []          # all rows
00439             clearall = True       # disarm the safety
00440           
00441           Note you have to explicitly set clearall=True to arm the deletion
00442           (a minimal precaution).
00443 
00444         * action = 'extract'
00445 
00446           This option will return the internal flagging dictionary to
00447           python.  This will allow a power-user to manipulate these
00448           commands directly (e.g. for plotting etc.).  For example,
00449 
00450           myflagd = flagcmd(vis=msfile,useapplied=True,action='extract')
00451 
00452           will extract all the commands (including those already applied)
00453           in the FLAG_CMD MS table.
00454 
00455           NOTE: There is no extant description of the format of this
00456           dictionary, as it is an internal device used by the flagcmd
00457           task. This action is provided for the convenience of
00458           advanced users.
00459 
00460 
00461      ------- FLAG COMMAND SYNTAX -------
00462 
00463         The command syntax is based on the flagdata parameters.
00464 
00465         Basic Syntax Rules
00466         
00467           Commands are a string (which may contain internal "strings") consisting of
00468           KEY=VALUE pairs separated by whitespace (see examples below). 
00469 
00470           NOTE: There should be no whitespace between KEY=VALUE or within each KEY or 
00471           VALUE, since the simple parser first breaks command lines on whitespace, 
00472           then on "=". 
00473         
00474           Each key should only appear once on a given command line/string
00475         
00476           There is an implicit "mode" for each command, with the default
00477           being 'manual' if not given.
00478 
00479           Comment lines can start with '#' and will be ignored.
00480         
00481         
00482         1. Data selection parameters (used by all flagging modes)
00483         
00484           timerange=''
00485           antenna=''
00486           spw=''
00487           correlation=''
00488           field=''
00489           scan=''
00490           feed=''
00491           array=''
00492           uvrange=''
00493           intent=''
00494           observation=''
00495         
00496           Note: a command consisting only of selection key-value pairs is a 
00497           basic "manual" operation, ie. flag the data meeting the selection.
00498           
00499         
00500         2. Modes specific parameters with default values (for further details and updated
00501            default values, refer to the task flagdata).
00502           
00503           2.1 Mode manual.
00504               autocorr=False
00505 
00506           2.2 Mode clip.
00507               datacolumn='DATA'
00508               clipminmax=[]  
00509               clipoutside=True
00510               channelavg=False  
00511               clipzeros=False
00512               
00513           2.3 Mode shadow.
00514               tolerance=0.0
00515               addantenna=''
00516               
00517           2.4 Mode quack.
00518               quackinterval=1.0     
00519               quackmode='beg' 
00520               quackincrement=False
00521               
00522           2.5 Mode elevation.
00523               lowerlimit=0.0
00524               upperlimit=90.0
00525               
00526           2.6 Mode tfcrop.
00527               ntime='scan'
00528               combinescans=False
00529               datacolumn='DATA' 
00530               timecutoff=4.0 
00531               freqcutoff=3.0
00532               timefit='line'
00533               freqfit='poly'
00534               maxnpieces=7 
00535               flagdimension='freqtime' 
00536               usewindowstats='none'
00537               halfwin=1 
00538          
00539           2.7 Mode extend.
00540               ntime='scan'
00541               combinescans=False
00542               extendpols=True
00543               growtime=50.0
00544               growfreq=50.0
00545               growaround=False
00546               flagneartime=False
00547               flagnearfreq=False
00548  
00549           2.8 Mode rflag.
00550               ntime='scan'
00551               combinescans=False
00552               datacolumn='DATA'
00553               winsize=3
00554               timedev=''
00555               freqdev=''
00556               timedevscale=5.0
00557               freqdevscale=5.0
00558               spectralmax=1000000.0
00559               spectralmin=0.0
00560               
00561           2.9 Mode unflag.
00562               
00563               
00564         3. Basic elaboration options for online and interface use
00565         
00566           id=''              # flag ID tag (not necessary)
00567           reason=''          # reason string for flag
00568           flagtime=''        # a timestamp for when this flag was generated (for 
00569                                user history use)
00570         
00571                                NOTE: there is no flagtime column in FLAG_CMD at
00572                                this time, but we will propose to add this as an
00573                                optional column
00574 
00575            NOTE: These are currently ignored and not used.
00576         
00577         4. Extended elaboration options for online and interface use 
00578            Note: these are FLAG_CMD columns, but their use is not clear but included
00579            here for compatibility and future expansion
00580         
00581           level=N            # flagging "level" for flags with same reason
00582           severity=N         # Severity code for the flag, on a scale of 0-10 in order 
00583                                of increasing severity; user specified
00584         
00585 
00586 
00587         """
00588         if type(tablerows)==int: tablerows=[tablerows]
00589         if type(rowlist)==int: rowlist=[rowlist]
00590 
00591 #
00592 #    The following is work around to avoid a bug with current python translation
00593 #
00594         mytmp = {}
00595 
00596         mytmp['vis'] = vis
00597         mytmp['inpmode'] = inpmode
00598         mytmp['inpfile'] = inpfile
00599         mytmp['tablerows'] = tablerows
00600         mytmp['reason'] = reason
00601         mytmp['useapplied'] = useapplied
00602         mytmp['tbuff'] = tbuff
00603         mytmp['ants'] = ants
00604         mytmp['action'] = action
00605         mytmp['flagbackup'] = flagbackup
00606         mytmp['clearall'] = clearall
00607         mytmp['rowlist'] = rowlist
00608         mytmp['plotfile'] = plotfile
00609         mytmp['savepars'] = savepars
00610         mytmp['outfile'] = outfile
00611         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00612         trec = casac.utils().torecord(pathname+'flagcmd.xml')
00613 
00614         casalog.origin('flagcmd')
00615         if trec.has_key('flagcmd') and casac.utils().verify(mytmp, trec['flagcmd']) :
00616             result = task_flagcmd.flagcmd(vis, inpmode, inpfile, tablerows, reason, useapplied, tbuff, ants, action, flagbackup, clearall, rowlist, plotfile, savepars, outfile)
00617 
00618         else :
00619           result = False
00620         return result