Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2023-03-17 10:51:55

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