CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
dataformats.py
Go to the documentation of this file.
1 
2 import cStringIO,operator
3 
4 def indent(rows, hasHeader=False, headerChar='-', delim=' | ', justify='left',
5  separateRows=False, prefix='', postfix='', wrapfunc=lambda x:x):
6  """Indents a table by column.
7  - rows: A sequence of sequences of items, one sequence per row.
8  - hasHeader: True if the first row consists of the columns' names.
9  - headerChar: Character to be used for the row separator line
10  (if hasHeader==True or separateRows==True).
11  - delim: The column delimiter.
12  - justify: Determines how are data justified in their column.
13  Valid values are 'left','right' and 'center'.
14  - separateRows: True if rows are to be separated by a line
15  of 'headerChar's.
16  - prefix: A string prepended to each printed row.
17  - postfix: A string appended to each printed row.
18  - wrapfunc: A function f(text) for wrapping text; each element in
19  the table is first wrapped by this function."""
20  # closure for breaking logical rows to physical, using wrapfunc
21  def rowWrapper(row):
22  newRows = [wrapfunc(item).split('\n') for item in row]
23  return [[substr or '' for substr in item] for item in map(None,*newRows)]
24  # break each logical row into one or more physical ones
25  logicalRows = [rowWrapper(row) for row in rows]
26  # columns of physical rows
27  columns = map(None,*reduce(operator.add,logicalRows))
28  # get the maximum of each column by the string length of its items
29  maxWidths = [max([len(str(item)) for item in column]) for column in columns]
30  rowSeparator = headerChar * (len(prefix) + len(postfix) + sum(maxWidths) + \
31  len(delim)*(len(maxWidths)-1))
32  # select the appropriate justify method
33  justify = {'center':str.center, 'right':str.rjust, 'left':str.ljust}[justify.lower()]
34  output=cStringIO.StringIO()
35  if separateRows: print >> output, rowSeparator
36  for physicalRows in logicalRows:
37  for row in physicalRows:
38  print >> output, \
39  prefix \
40  + delim.join([justify(str(item),width) for (item,width) in zip(row,maxWidths)]) \
41  + postfix
42  if separateRows or hasHeader: print >> output, rowSeparator; hasHeader=False
43  return output.getvalue()
44 
45 # written by Mike Brown
46 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061
47 def wrap_onspace(text, width):
48  """
49  A word-wrap function that preserves existing line breaks
50  and most spaces in the text. Expects that existing line
51  breaks are posix newlines (\n).
52  """
53  return reduce(lambda line, word, width=width: '%s%s%s' %
54  (line,
55  ' \n'[(len(line[line.rfind('\n')+1:])
56  + len(word.split('\n',1)[0]
57  ) >= width)],
58  word),
59  text.split(' ')
60  )
61 
62 import re
63 def wrap_onspace_strict(text, width):
64  """Similar to wrap_onspace, but enforces the width constraint:
65  words longer than width are split."""
66  wordRegex = re.compile(r'\S{'+str(width)+r',}')
67  return wrap_onspace(wordRegex.sub(lambda m: wrap_always(m.group(),width),text),width)
68 
69 import math
70 def wrap_always(text, width):
71  """A simple word-wrap function that wraps text on exactly width characters.
72  It doesn't split the text in words."""
73  return '\n'.join([ text[width*i:width*(i+1)] \
74  for i in xrange(int(math.ceil(1.*len(text)/width))) ])
75 
76 
77 
78 # END OF TABLE FORMATING
79 
80 # START of import
81 import sys
82 imported_modules = []
83 
84 def importDF(path):
85 
86  modules_to_import = "RecoTracker RecoLocalTracker RecoLocalCalo RecoEcal RecoEgamma RecoLocalMuon RecoMuon RecoJets RecoMET RecoBTag RecoTauTag RecoVertex RecoPixelVertexing HLTrigger RecoParticleFlow".split()
87  modules_to_import = "RecoLocalTracker RecoLocalMuon RecoLocalCalo RecoEcal TrackingTools RecoTracker RecoJets RecoMET RecoMuon RecoBTau RecoBTag RecoTauTag RecoVertex RecoPixelVertexing RecoEgamma RecoParticleFlow L1Trigger".split()
88 
89 
90  for module in modules_to_import:
91  m = module + "_dataformats"
92  try:
93  sys.path.append(path+"/src/Documentation/DataFormats/python/")
94 # sys.path.append(".")
95  globals()[m] = __import__(m)
96  imported_modules.append(m)
97  print "Searching in "+ module
98  except ImportError:
99  print "skipping", module
100 
101 # END of import
102 
103 
104 def search(query):
105  labels = ('Where(Package)', 'Instance', 'Container', 'Description')
106  width = 20
107  data = ""
108 
109  for module in imported_modules:
110  dict = vars(globals()[module])["json"]
111  for type in ["full", "reco", "aod"]:
112  for data_items in dict[type]['data']:
113  if query.lower() in data_items.__str__().lower() and not (("No documentation".lower()) in data_items.__str__().lower()):
114  data+= module.replace("_json", "")+" ("+ type.replace("full", "FEVT") + ")||" + "||".join(data_items.values())+"\n"
115 
116  if (data != ""):
117  rows = [row.strip().split('||') for row in data.splitlines()]
118  print indent([labels]+rows, hasHeader=True, separateRows=True, prefix='| ', postfix=' |', wrapfunc=lambda x: wrap_always(x,width))
119  else:
120  print "No documentation found"
121 
122 def help():
123  print "usage: dataformats pattern_to_search"
124  print "example: dataformats muon"
125  print "Note! multiple patterns separated by space are not supported"
126 
127 if __name__ == "__main__":
128 
129  if ("help" in sys.argv):
130  help()
131  sys.exit(0)
132 
133  if (len(sys.argv) > 2):
134  importDF(sys.argv[1])
135  print "\nSearching for: "+sys.argv[2]+"\n"
136  search(sys.argv[2])
137 
138  else:
139  help()
140 
141 
def wrap_onspace
Definition: dataformats.py:47
def wrap_always
Definition: dataformats.py:70
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def wrap_onspace_strict
Definition: dataformats.py:63
double split
Definition: MVATrainer.cc:139