casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
listshapes.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 from glob import glob
00004 import os
00005 
00006 try:
00007     from  casac import *  # No-op if already in casapy.
00008 except:
00009     import sys
00010     
00011     casacpath = glob(os.sep.join(os.environ["CASAPATH"].split() +
00012                                  ['python', '2.*']))  # devs
00013     casacpath.sort()
00014     casacpath.reverse()
00015     casacpath.extend(glob(os.sep.join([os.environ["CASAPATH"].split()[0],
00016                                        'lib', 'python2.*'])))  # users
00017     #print "casacpath =", "\n".join(casacpath)
00018     sys.path.extend(casacpath)
00019 
00020 
00021 def get_tool(toolname):
00022     """
00023     Returns a CASA tool with name toolname, or None on failure.
00024     """
00025     tool = None
00026     if toolname != 'table':
00027         tool = casac.table()
00028     else:
00029         print "The factory name for", toolname, "is unknown."
00030     return tool
00031 
00032 
00033 def listshapes(musthave=[], mspat="*[-_.][Mm][Ss]", combine='or',
00034                sortfirst=False, incl_ddid=False):
00035     """
00036     Lists the data shapes of the MSes matched by mspat.
00037     """
00038     if type(musthave) == str:
00039         musthave = [s.replace(',', '') for s in musthave.split()]
00040 
00041     holderdict = {}
00042     holderdict['mytb'] = get_tool('tb')
00043     holderdict['incl_ddid'] = incl_ddid
00044 
00045     splitatdoubleglob = mspat.split('**/')
00046     if len(splitatdoubleglob) > 1:
00047         if splitatdoubleglob[0] == '':
00048             splitatdoubleglob[0] = '.'
00049         holderdict['mspat'] = splitatdoubleglob[1]
00050         os.path.walk(splitatdoubleglob[0], checkMSes, holderdict)
00051     else:
00052         holderdict['mspat'] = mspat
00053         checkMSes(holderdict, '', [])
00054     return holderdict['msdict']
00055 
00056 
00057 def checkMSes(holderdict, dir, files):
00058     """
00059     Updates holderdict['msdict'] with a list of (ncorr, nchan)s for
00060     each MS in dir that matches holderdict['mspat'].
00061     """        
00062     # Yup, ignore files.  It's just a os.path.walk()ism.
00063     mses = glob(os.path.join(dir, holderdict['mspat']))
00064 
00065     #musthave = holderdict.get('musthave', set([]))
00066     #use_and = holderdict.get('use_and', False)
00067     #listall = holderdict.get('listall', False)
00068 
00069     if not holderdict.get('msdict'):   # Initialize it so retval
00070         holderdict['msdict'] = {}      # can be tied to it.
00071     retval = holderdict['msdict']
00072     
00073     #needed_items = holderdict.get('needed_items', {})
00074     
00075     mytb = holderdict['mytb']
00076     incl_ddid = holderdict['incl_ddid']
00077 
00078     def myopen(mytb, whichtab):
00079         """
00080         A wrapper around (my)tb.open(whichtab) which is smarter about error
00081         handling.  It will still throw an exception on an error, but it tries
00082         to make the message less misleading.
00083         """
00084         retval = False
00085         if not hasattr(mytb, 'open'):
00086             raise ValueError, 'mytb is not a tb tool'
00087         try:
00088             mytb.open(whichtab)
00089             retval = True
00090         except Exception, e:
00091             # Typically if we are here whichtab is too malformed for
00092             # mytb to handle, and e is usually "whichtab does not exist",
00093             # which is usually incorrect.
00094             if str(e)[-15:] == " does not exist":
00095                 print "tb could not open", whichtab
00096             else:
00097                 print "Error", e, "from tb.open(", whichtab, ")"
00098             mytb.close()  # Just in case.
00099         return retval
00100     
00101     for currms in mses:
00102         if currms[:2] == './':  # strip off leading ./, if present.
00103             currms = currms[2:]    # cosmetic.
00104 
00105         if incl_ddid:
00106             retval[currms] = {}
00107         else:
00108             retval[currms] = set([])
00109 
00110         if not myopen(mytb, currms + '/POLARIZATION'):
00111             break
00112         num_corrs = mytb.getcol('NUM_CORR')
00113         mytb.close()
00114         
00115         if not myopen(mytb, currms + '/SPECTRAL_WINDOW'):
00116             break
00117         num_chans = mytb.getcol('NUM_CHAN')
00118         mytb.close()
00119         
00120         if not myopen(mytb, currms + '/DATA_DESCRIPTION'):
00121             break
00122 
00123         for row in xrange(mytb.nrows()):
00124             if not mytb.getcell('FLAG_ROW', row):
00125                 key = (num_corrs[mytb.getcell('POLARIZATION_ID', row)],
00126                        num_chans[mytb.getcell('SPECTRAL_WINDOW_ID', row)])
00127                 if incl_ddid:
00128                     if retval[currms].has_key(key):
00129                         retval[currms][key].append(row)
00130                     else:
00131                         retval[currms][key] = [row]
00132                 else:
00133                     retval[currms].add(key)
00134         mytb.close()
00135 
00136 
00137 if __name__ == '__main__':
00138     import pprint
00139     import sys
00140     mspat = '*.ms'
00141     musthave = []
00142     incl_ddid = False
00143     if len(sys.argv) > 1:
00144         incl_ddid = sys.argv[1]
00145         mspat = sys.argv[2]
00146         musthave = sys.argv[3:]
00147     msdict = listshapes(musthave, mspat, incl_ddid=incl_ddid)
00148     pprint.pprint(msdict)
00149