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, pprint
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 m in modules_to_import:
91  m = m + "_dataformats"
92  try:
93  sys.path.append(path+"/src/Documentation/DataFormats/python/")
94  globals()[m] = __import__(m)
95  imported_modules.append(m)
96  print m
97  except ImportError:
98  print "skipping", m
99 
100 # END of import
101 
102 def search(query):
103  labels = ('Where(Package)', 'Instance', 'Container', 'Description')
104  width = 20
105 
106  data = ""
107  for module in imported_modules:
108  for dict_name in ["full", "reco", "aod"]: # going through all dictionaries
109  #print module
110  dict = vars(globals()[module])[dict_name]
111 
112  for key in sorted(dict.keys()): # going though all elements in dictionary
113  # TODO: IMPROVE
114  element = dict[key]
115  if query.lower() in element.__str__().lower(): # searching for query
116  if not (("No documentation".lower()) in element.__str__().lower()):
117  data+= module.replace("_dataformats", "")+" ("+ dict_name.replace("full", "FEVT") + ")||" + "||".join(element)+"\n"
118 
119  if (data != ""):
120  rows = [row.strip().split('||') for row in data.splitlines()]
121  print indent([labels]+rows, hasHeader=True, separateRows=True, prefix='| ', postfix=' |', wrapfunc=lambda x: wrap_always(x,width))
122  else:
123  print "No documentation found"
124 
125 def help():
126  print "usage: dataformats pattern_to_search"
127  print "example: dataformats muon"
128  print "Note! multiple patterns separated by space are not supported"
129 
130 if __name__ == "__main__":
131 
132  if ("help" in sys.argv):
133  help()
134  sys.exit(0)
135 
136  print sys.argv[1]
137  print sys.argv[2]
138 
139  if (len(sys.argv) > 2):
140  importDF(sys.argv[1])
141  print "\nSearching for: "+sys.argv[2]+"\n"
142  search(sys.argv[2])
143  else:
144  help()
145 
146 
def wrap_onspace
Definition: dataformats.py:47
dictionary map
Definition: Association.py:205
def wrap_always
Definition: dataformats.py:70
const T & max(const T &a, const T &b)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def wrap_onspace_strict
Definition: dataformats.py:63
double split
Definition: MVATrainer.cc:139