Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-12-01 23:40:11

0001 
0002 import cStringIO,operator
0003 from functools import reduce
0004 
0005 def indent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='left',
0006            separateRows=False, prefix='', postfix='', wrapfunc=lambda x:x):
0007     """Indents a table by column.
0008        - rows: A sequence of sequences of items, one sequence per row.
0009        - hasHeader: True if the first row consists of the columns' names.
0010        - headerChar: Character to be used for the row separator line
0011          (if hasHeader==True or separateRows==True).
0012        - delim: The column delimiter.
0013        - justify: Determines how are data justified in their column. 
0014          Valid values are 'left','right' and 'center'.
0015        - separateRows: True if rows are to be separated by a line
0016          of 'headerChar's.
0017        - prefix: A string prepended to each printed row.
0018        - postfix: A string appended to each printed row.
0019        - wrapfunc: A function f(text) for wrapping text; each element in
0020          the table is first wrapped by this function."""
0021     # closure for breaking logical rows to physical, using wrapfunc
0022     def rowWrapper(row):
0023         newRows = [wrapfunc(item).split('\n') for item in row]
0024         return [[substr or '' for substr in item] for item in map(None,*newRows)]
0025     # break each logical row into one or more physical ones
0026     logicalRows = [rowWrapper(row) for row in rows]
0027     # columns of physical rows
0028     columns = map(None,*reduce(operator.add,logicalRows))
0029     # get the maximum of each column by the string length of its items
0030     maxWidths = [max([len(str(item)) for item in column]) for column in columns]
0031     rowSeparator = headerChar * (len(prefix) + len(postfix) + sum(maxWidths) + \
0032                                  len(delim)*(len(maxWidths)-1))
0033     # select the appropriate justify method
0034     justify = {'center':str.center, 'right':str.rjust, 'left':str.ljust}[justify.lower()]
0035     output=cStringIO.StringIO()
0036     if separateRows: print(rowSeparator, file=output)
0037     for physicalRows in logicalRows:
0038         for row in physicalRows:
0039             print(prefix \
0040                 + delim.join([justify(str(item),width) for (item,width) in zip(row,maxWidths)]) \
0041                 + postfix, file=output)
0042         if separateRows or hasHeader: print(rowSeparator, file=output); hasHeader=False
0043     return output.getvalue()
0044 
0045 # written by Mike Brown
0046 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061
0047 def wrap_onspace(text, width):
0048     """
0049     A word-wrap function that preserves existing line breaks
0050     and most spaces in the text. Expects that existing line
0051     breaks are posix newlines (\n).
0052     """
0053     return reduce(lambda line, word, width=width: '%s%s%s' %
0054                   (line,
0055                    ' \n'[(len(line[line.rfind('\n')+1:])
0056                          + len(word.split('\n',1)[0]
0057                               ) >= width)],
0058                    word),
0059                   text.split(' ')
0060                  )
0061 
0062 import re
0063 def wrap_onspace_strict(text, width):
0064     """Similar to wrap_onspace, but enforces the width constraint:
0065        words longer than width are split."""
0066     wordRegex = re.compile(r'\S{'+str(width)+r',}')
0067     return wrap_onspace(wordRegex.sub(lambda m: wrap_always(m.group(),width),text),width)
0068 
0069 import math
0070 def wrap_always(text, width):
0071     """A simple word-wrap function that wraps text on exactly width characters.
0072        It doesn't split the text in words."""
0073     return '\n'.join([ text[width*i:width*(i+1)] \
0074                        for i in xrange(int(math.ceil(1.*len(text)/width))) ])
0075 
0076 
0077 
0078 # END OF TABLE FORMATING
0079 
0080 # START of import
0081 import sys
0082 imported_modules = []
0083 
0084 def importDF(path):
0085 
0086     modules_to_import = "RecoTracker RecoLocalTracker RecoLocalCalo RecoEcal RecoEgamma RecoLocalMuon RecoMuon RecoJets RecoMET RecoBTag RecoTauTag RecoVertex RecoPixelVertexing HLTrigger RecoParticleFlow".split()
0087     modules_to_import = "RecoLocalTracker RecoLocalMuon RecoLocalCalo RecoEcal TrackingTools RecoTracker RecoJets RecoMET RecoMuon RecoBTau RecoBTag RecoTauTag RecoVertex RecoPixelVertexing RecoEgamma RecoParticleFlow L1Trigger".split()
0088   
0089 
0090     for module in modules_to_import:
0091         m = module + "_dataformats"
0092         try:
0093             sys.path.append(path+"/src/Documentation/DataFormats/python/")
0094 #            sys.path.append(".")
0095             globals()[m] = __import__(m)
0096             imported_modules.append(m)
0097             print("Searching in "+ module)
0098         except ImportError:
0099             print("skipping", module)
0100         
0101 # END of import            
0102        
0103 
0104 def search(query):
0105     labels = ('Where(Package)', 'Instance', 'Container', 'Description')
0106     width = 20
0107     data = ""
0108     
0109     for module in imported_modules:
0110         dict = vars(globals()[module])["json"]
0111         for type in ["full", "reco", "aod"]:
0112             for data_items in dict[type]['data']:
0113                 if query.lower() in data_items.__str__().lower() and not (("No documentation".lower()) in data_items.__str__().lower()):
0114                     data+= module.replace("_json", "")+" ("+ type.replace("full", "FEVT") + ")||" + "||".join(data_items.values())+"\n"
0115     
0116     if (data != ""):
0117         rows = [row.strip().split('||')  for row in data.splitlines()]
0118         print(indent([labels]+rows, hasHeader=True, separateRows=True, prefix='| ', postfix=' |',  wrapfunc=lambda x: wrap_always(x,width)))
0119     else:
0120         print("No documentation found") 
0121 
0122 def help():
0123     print("usage: dataformats pattern_to_search")
0124     print("example: dataformats muon")
0125     print("Note! multiple patterns separated by space are not supported")
0126 
0127 if __name__ == "__main__":
0128 
0129     if ("help" in sys.argv):
0130         help()
0131         sys.exit(0) 
0132 
0133     if (len(sys.argv) > 2):
0134         importDF(sys.argv[1])
0135         print("\nSearching for: "+sys.argv[2]+"\n") 
0136         search(sys.argv[2])
0137 
0138     else:
0139         help()
0140  
0141