CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
useReflexToDescribeForGenObject.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import ROOT
4 import re
5 import pprint
6 import sys
7 import inspect
8 import optparse
9 
10 defsDict = {
11  'int' : '%-40s : form=%%%%8d type=int',
12  'float' : '%-40s : form=%%%%7.2f prec=',
13  'str' : '%-40s : form=%%%%20s type=string',
14  'long' : '%-40s : form=%%%%10d type=long',
15  }
16 
17 root2GOtypeDict = {
18  'int' : 'int',
19  'float' : 'float',
20  'double' : 'float',
21  'long' : 'long',
22  'long int' : 'long',
23  'unsigned int' : 'int',
24  'bool' : 'int',
25  'string' : 'str',
26  'std::basic_string<char>' : 'str',
27  }
28 
29 startString = """
30 # -*- sh -*- For Font lock mode
31 
32 ###########################
33 ## GenObject Definitions ##
34 ###########################
35 
36 # GenObject 'event' definition
37 [runevent singleton]
38 run: type=int
39 event: type=int
40 """
41 
42 defTemplate = """
43 #####################
44 ## %(OBJS)s Definition ##
45 #####################
46 
47 # Nickname and Tree
48 [%(objs)s:FWLite]
49 
50 # 'reco'-tupe 'runevent' 'tofill' information
51 [runevent:%(objs)s:EventAuxiliary shortcut=eventAuxiliary()]
52 run: run()
53 event: event()
54 
55 """
56 
57 colonRE = re.compile (r':')
58 dotRE = re.compile (r'\.')
59 nonAlphaRE = re.compile (r'\W')
60 alphaRE = re.compile (r'(\w+)')
61 vetoedTypes = set()
62 
63 def getObjectList (objectName, base, verbose = False, memberData = False):
64  """Get a list of interesting things from this object"""
65  # The autoloader needs an object before it loads its dictionary.
66  # So let's give it one.
67  try:
68  rootObjConstructor = getattr (ROOT, objectName)
69  except AttributeError as missingAttr:
70  if str(missingAttr) in ['double', 'int']:
71  print "Do not need to describe doubles or ints"
72  sys.exit(0)
73  else:
74  raise
75 
76  obj = rootObjConstructor()
77  alreadySeenFunction = set()
78  etaFound, phiFound = False, False
79  global vetoedTypes
80  retval = []
81  # Put the current class on the queue and start the while loop
82  reflexList = [ ROOT.Reflex.Type.ByName (objectName) ]
83  if verbose: print reflexList
84  # Uses while because reflixList is really a stack
85  while reflexList:
86  reflex = reflexList.pop (0) # get first element
87  print "Looking at %s" % reflex.Name (0xffffffff)
88  if verbose:
89  print "baseSize", reflex.BaseSize()
90  print "FunctionMemberSize", reflex.FunctionMemberSize()
91  for baseIndex in range( reflex.BaseSize() ) :
92  reflexList.append( reflex.BaseAt(baseIndex).ToType() )
93  for index in range( reflex.FunctionMemberSize() ):
94  funcMember = reflex.FunctionMemberAt (index)
95  # if we've already seen this, don't bother again
96  name = funcMember.Name()
97  if verbose:
98  print "name", name
99  if name == 'eta':
100  etaFound = True
101  elif name == 'phi':
102  phiFound = True
103  if name in alreadySeenFunction:
104  continue
105  # make sure this is an allowed return type
106  returnType = funcMember.TypeOf().ReturnType().Name (0xffffffff)
107  goType = root2GOtypeDict.get (returnType, None)
108  if verbose:
109  print " type", returnType, goType
110  if not goType:
111  vetoedTypes.add (returnType)
112  if verbose:
113  print " skipped"
114  continue
115  elif verbose:
116  print " good"
117  # only bother printout out lines where it is a const function
118  # and has no input parameters.
119  if funcMember.IsConst() and not funcMember.FunctionParameterSize():
120  retval.append( ("%s.%s()" % (base, name), goType))
121  alreadySeenFunction.add( name )
122  if verbose:
123  print " added"
124  elif verbose:
125  print " failed IsConst() and FunctionParameterSize()"
126  if not memberData:
127  continue
128  for index in range( reflex.DataMemberSize() ):
129  data = reflex.DataMemberAt( index );
130  name = data.Name()
131  dataType = data.MemberType().__class__.__name__
132  goType = root2GOtypeDict.get (dataType, None)
133  if not goType:
134  continue
135  if verbose:
136  print "name", name, "dataType", dataType, "goType", goType
137  retval.append ( ("%s.%s" % (base, name), goType) )
138  retval.sort()
139  return retval, etaFound and phiFound
140 
141 
142 def genObjNameDef (line):
143  """Returns GenObject name and ntuple definition function"""
144  words = dotRE.split (line)[1:]
145  func = ".".join (words)
146  name = "_".join (words)
147  name = nonAlphaRE.sub ('', name)
148  return name, func
149 
150 
151 def genObjectDef (mylist, tuple, alias, label, type, etaPhiFound):
152  """Does something, but I can't remembrer what... """
153  print "tuple %s alias %s label %s type %s" % (tuple, alias, label, type)
154  # first get the name of the object
155  firstName = mylist[0][0]
156  match = alphaRE.match (firstName)
157  if not match:
158  raise RuntimeError, "firstName doesn't parse correctly. (%s)" \
159  % firstName
160  genName = match.group (1)
161  genDef = " ## GenObject %s Definition ##\n[%s]\n" % \
162  (genName, genName)
163  if options.index or not etaPhiFound:
164  # either we told it to always use index OR either eta or phi
165  # is missing.
166  genDef += "-equiv: index,0\n";
167  else:
168  genDef += "-equiv: eta,0.1 phi,0.1 index,100000\n";
169  tupleDef = '[%s:%s:%s label=%s type=%s]\n' % \
170  (genName, tuple, alias, label, type)
171 
172  for variable in mylist:
173  name, func = genObjNameDef (variable[0])
174  typeInfo = variable[1]
175  form = defsDict[ typeInfo ]
176  genDef += form % name + '\n'
177  tupleDef += "%-40s : %s\n" % (name, func)
178  return genDef, tupleDef
179 
180 
181 if __name__ == "__main__":
182  # Setup options parser
183  parser = optparse.OptionParser \
184  ("usage: %prog [options] objectName\n" \
185  "Creates control file for GenObject.")
186  parser.add_option ('--goName', dest='goName', type='string',
187  default='',
188  help='GenObject name')
189  parser.add_option ('--index', dest='index', action='store_true',
190  help='use index for matching')
191  parser.add_option ('--label', dest='label', type='string',
192  default = 'dummyLabel',
193  help="Tell GO to set an label")
194  parser.add_option ('--output', dest='output', type='string',
195  default = '',
196  help="Output (Default 'objectName.txt')")
197  parser.add_option ('--precision', dest='precision', type='string',
198  default = '1e-5',
199  help="precision to use for floats (default %default)")
200  parser.add_option ('--privateMemberData', dest='privateMemberData',
201  action='store_true',
202  help='include private member data (NOT for comparisons)')
203  parser.add_option ('--tupleName', dest='tupleName', type='string',
204  default = 'reco',
205  help="Tuple name (default '%default')")
206  parser.add_option ('--type', dest='type', type='string',
207  default = 'dummyType',
208  help="Tell GO to set an type")
209  parser.add_option ('--verbose', dest='verbose', action='store_true',
210  help='Verbose output')
211  options, args = parser.parse_args()
212  defsDict['float'] += options.precision
213  from Validation.Tools.GenObject import GenObject
214  options.type = GenObject.decodeNonAlphanumerics (options.type)
215  if len (args) < 1:
216  raise RuntimeError, "Need to provide object name."
217  #
218  objectName = GenObject.decodeNonAlphanumerics (args[0])
219  goName = options.goName or colonRE.sub ('', objectName)
220  outputFile = options.output or goName + '.txt'
221  ROOT.gROOT.SetBatch()
222  # load the right libraries, etc.
223  ROOT.gSystem.Load("libFWCoreFWLite")
224  ROOT.gSystem.Load("libDataFormatsFWLite")
225  ROOT.gSystem.Load("libReflexDict")
226  ROOT.AutoLibraryLoader.enable()
227  mylist, etaPhiFound = getObjectList (objectName, goName, options.verbose,
228  options.privateMemberData)
229  if not len (mylist):
230  print "There are no member functions that are useful for comparison."
231  sys.exit (GenObject.uselessReturnCode)
232  targetFile = open (outputFile, 'w')
233  genDef, tupleDef = genObjectDef (mylist,
234  options.tupleName,
235  goName,
236  options.label,
237  options.type,
238  etaPhiFound)
239  targetFile.write (startString)
240  targetFile.write (genDef)
241  targetFile.write (defTemplate % {'objs':'reco', 'OBJS':'RECO'})
242  targetFile.write (tupleDef)
243  print "Vetoed types:"
244  pprint.pprint ( sorted( list(vetoedTypes) ) )
std::map< DetId, double > ReturnType
How EventSelector::AcceptEvent() decides whether to accept an event for output otherwise it is excluding the probing of A single or multiple positive and the trigger will pass if any such matching triggers are PASS or EXCEPTION[A criterion thatmatches no triggers at all is detected and causes a throw.] A single negative with an expectation of appropriate bit checking in the decision and the trigger will pass if any such matching triggers are FAIL or EXCEPTION A wildcarded negative criterion that matches more than one trigger in the trigger list("!*","!HLTx*"if it matches 2 triggers or more) will accept the event if all the matching triggers are FAIL.It will reject the event if any of the triggers are PASS or EXCEPTION(this matches the behavior of"!*"before the partial wildcard feature was incorporated).Triggers which are in the READY state are completely ignored.(READY should never be returned since the trigger paths have been run