CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
__init__.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 import ROOT
4 import inspect
5 import sys
6 import optparse
7 from FWCore.ParameterSet.VarParsing import VarParsing
8 
9 
10 ROOT.gSystem.Load("libFWCoreFWLite.so")
11 ROOT.AutoLibraryLoader.enable()
12 
13 # Whether warn() should print anythingg
14 quietWarn = False
15 
16 def setQuietWarn (quiet = True):
17  global quietWarn
18  quietWarn = quiet
19 
20 def warn (*args, **kwargs):
21  """print out warning with line number and rest of arguments"""
22  if quietWarn: return
23  frame = inspect.stack()[1]
24  filename = frame[1]
25  lineNum = frame[2]
26  #print "after '%s'" % filename
27  blankLines = kwargs.get('blankLines', 0)
28  if blankLines:
29  print '\n' * blankLines
30  spaces = kwargs.get('spaces', 0)
31  if spaces:
32  print ' ' * spaces,
33  if len (args):
34  print "%s (%s): " % (filename, lineNum),
35  for arg in args:
36  print arg,
37  print
38  else:
39  print "%s (%s):" % (filename, lineNum)
40 
41 ########################
42 ## ################## ##
43 ## ## ############ ## ##
44 ## ## ## Handle ## ## ##
45 ## ## ############ ## ##
46 ## ################## ##
47 ########################
48 
49 class Handle:
50  """Python interface to FWLite Handle class"""
51 
52  def __init__ (self,
53  typeString,
54  **kwargs):
55  """Initialize python handle wrapper """
56  # turn off warnings
57  oldWarningLevel = ROOT.gErrorIgnoreLevel
58  ROOT.gErrorIgnoreLevel = ROOT.kError
59  self._type = typeString
60  self._wrapper = ROOT.edm.Wrapper (self._type)()
61  self._typeInfo = self._wrapper.typeInfo()
62  self._exception = RuntimeError ("getByLabel not called for '%s'", self)
63  ROOT.SetOwnership (self._wrapper, False)
64  # restore warning state
65  ROOT.gErrorIgnoreLevel = oldWarningLevel
66  # O.k. This is a little weird. We want a pointer to an EDM
67  # wrapper, but we don't want the memory it is pointing to.
68  # So, we've created it and grabbed the type info. Since we
69  # don't want a memory leak, we destroy it.
70  if kwargs.get ('noDelete'):
71  print "Not deleting wrapper"
72  del kwargs['noDelete']
73  else:
74  self._wrapper.IsA().Destructor( self._wrapper )
75  # Since we deleted the options as we used them, that means
76  # that kwargs should be empty. If it's not, that means that
77  # somebody passed in an argument that we're not using and we
78  # should complain.
79  if len (kwargs):
80  raise RuntimeError, "Unknown arguments %s" % kwargs
81 
82 
83  def isValid (self):
84  """Returns true if getByLabel call was successful and data is
85  present in handle."""
86  return not self._exception
87 
88 
89  def product (self):
90  """Returns product stored in handle."""
91  if self._exception:
92  raise self._exception
93  return self._wrapper.product()
94 
95 
96  def __str__ (self):
97  return "%s" % (self._type)
98 
99 
100  ## Private member functions ##
101 
102  def _typeInfoGetter (self):
103  """(Internal) Return the type info"""
104  return self._typeInfo
105 
106 
107  def _addressOf (self):
108  """(Internal) Return address of edm wrapper"""
109  return ROOT.AddressOf (self._wrapper)
110 
111 
112  def _setStatus (self, getByLabelSuccess, labelString):
113  """(Internal) To be called by Events.getByLabel"""
114  if not getByLabelSuccess:
115  self._exception = RuntimeError ("getByLabel (%s, %s) failed" \
116  % (self, labelString))
117  return
118  if not self._wrapper.isPresent():
119  self._exception = RuntimeError ("getByLabel (%s, %s) not present this event" \
120  % (self, labelString))
121  return
122  # if we're still here, then everything is happy. Clear the exception
123  self._exception = None
124 
125 
126 #######################
127 ## ################# ##
128 ## ## ########### ## ##
129 ## ## ## Lumis ## ## ##
130 ## ## ########### ## ##
131 ## ################# ##
132 #######################
133 
134 class Lumis:
135  """Python interface to FWLite LuminosityBlock"""
136  def __init__ (self, inputFiles = '', **kwargs):
137  self._lumi = None
138  self._lumiCounts = 0
139  self._tfile = None
140  self._maxLumis = 0
141  if isinstance (inputFiles, list):
142  # it's a list
143  self._filenames = inputFiles[:]
144  elif isinstance (inputFiles, VarParsing):
145  # it's a VarParsing object
146  options = inputFiles
147  self._maxLumis = options.maxEvents
148  self._filenames = options.inputFiles
149  else:
150  # it's probably a single string
151  self._filenames = [inputFiles]
152  ##############################
153  ## Parse optional arguments ##
154  ##############################
155  if kwargs.has_key ('maxEvents'):
156  self._maxLumis = kwargs['maxEvents']
157  del kwargs['maxEvents']
158  if kwargs.has_key ('options'):
159  options = kwargs ['options']
160  self._maxLumis = options.maxEvents
161  self._filenames = options.inputFiles
162  self._secondaryFilenames = options.secondaryInputFiles
163  del kwargs['options']
164  # Since we deleted the options as we used them, that means
165  # that kwargs should be empty. If it's not, that means that
166  # somebody passed in an argument that we're not using and we
167  # should complain.
168  if len (kwargs):
169  raise RuntimeError, "Unknown arguments %s" % kwargs
170  if not self._filenames:
171  raise RuntimeError, "No input files given"
172  if not self._createFWLiteLumi():
173  # this shouldn't happen as you are getting nothing the
174  # very first time out, but let's at least check to
175  # avoid problems.
176  raise RuntimeError, "Never and information about Lumi"
177 
178 
179  def __del__ (self):
180  """(Internal) Destructor"""
181  # print "Goodbye cruel world, I'm leaving you today."
182  del self._lumi
183  # print "Goodbye, goodbye, goodbye."
184 
185 
186  def __iter__ (self):
187  return self._next()
188 
189 
190  def aux (self):
191  try:
192  return self._lumi.luminosityBlockAuxiliary()
193  except:
194  raise RuntimeError, "Lumis.aux() called on object in invalid state"
195 
196 
198  try:
199  return self._lumi.luminosityBlockAuxiliary()
200  except:
201  raise RuntimeError, "Lumis.luminosityBlockAuxiliary() called on object in invalid state"
202 
203 
204  def getByLabel (self, *args):
205  """Calls FWLite's getByLabel. Called:
206  getByLabel (moduleLabel, handle)
207  getByLabel (moduleLabel, productInstanceLabel, handle),
208  getByLabel (moduleLabel, productInstanceLabel, processLabel, handle),
209  or
210  getByLabel ( (mL, pIL,pL), handle)
211  """
212  length = len (args)
213  if length < 2 or length > 4:
214  # not called correctly
215  raise RuntimeError, "Incorrect number of arguments"
216  # handle is always the last argument
217  argsList = list (args)
218  handle = argsList.pop()
219  if len(argsList)==1 and \
220  ( isinstance (argsList[0], tuple) or
221  isinstance (argsList[0], list) ) :
222  if len (argsList) > 3:
223  raise RuntimeError, "getByLabel Error: label tuple has too " \
224  "many arguments '%s'" % argsList[0]
225  argsList = list(argsList[0])
226  while len(argsList) < 3:
227  argsList.append ('')
228  (moduleLabel, productInstanceLabel, processLabel) = argsList
229  labelString = "'" + "', '".join(argsList) + "'"
230  handle._setStatus ( self._lumi.getByLabel( handle._typeInfoGetter(),
231  moduleLabel,
232  productInstanceLabel,
233  processLabel,
234  handle._addressOf() ),
235  labelString )
236  return handle.isValid()
237 
238 
239  ##############################
240  ## Private Member Functions ##
241  ##############################
242 
243  def _createFWLiteLumi (self):
244  """(Internal) Creates an FWLite Lumi"""
245  # are there any files left?
246  if not self._filenames:
247  return False
248  if self._lumi:
249  del self._lumi
250  self._lumi = None
251  self._veryFirstTime = False
252  self._currFilename = self._filenames.pop(0)
253  #print "Opening file", self._currFilename
254  if self._tfile:
255  del self._tfile
256  self._tfile = ROOT.TFile.Open (self._currFilename)
257  self._lumi = ROOT.fwlite.LuminosityBlock (self._tfile);
258  self._lumi.toBegin()
259  return True
260 
261 
262  def _next (self):
263  """(Internal) Iterator internals"""
264  while True:
265  if self._lumi.atEnd():
266  if not self._createFWLiteLumi():
267  # there are no more files here, so we are done
268  break
269  yield self
270  self._lumiCounts += 1
271  if self._maxLumis > 0 and self._lumiCounts >= self._maxLumis:
272  break
273  self._lumi.__preinc__()
274 
275 
276 
277 ######################
278 ## ################ ##
279 ## ## ########## ## ##
280 ## ## ## Runs ## ## ##
281 ## ## ########## ## ##
282 ## ################ ##
283 ######################
284 
285 class Runs:
286  """Python interface to FWLite LuminosityBlock"""
287  def __init__ (self, inputFiles = '', **kwargs):
288  self._run = None
289  self._runCounts = 0
290  self._tfile = None
291  self._maxRuns = 0
292  if isinstance (inputFiles, list):
293  # it's a list
294  self._filenames = inputFiles[:]
295  elif isinstance (inputFiles, VarParsing):
296  # it's a VarParsing object
297  options = inputFiles
298  self._maxRuns = options.maxEvents
299  self._filenames = options.inputFiles
300  else:
301  # it's probably a single string
302  self._filenames = [inputFiles]
303  ##############################
304  ## Parse optional arguments ##
305  ##############################
306  if kwargs.has_key ('maxEvents'):
307  self._maxRuns = kwargs['maxEvents']
308  del kwargs['maxEvents']
309  if kwargs.has_key ('options'):
310  options = kwargs ['options']
311  self._maxRuns = options.maxEvents
312  self._filenames = options.inputFiles
313  self._secondaryFilenames = options.secondaryInputFiles
314  del kwargs['options']
315  # Since we deleted the options as we used them, that means
316  # that kwargs should be empty. If it's not, that means that
317  # somebody passed in an argument that we're not using and we
318  # should complain.
319  if len (kwargs):
320  raise RuntimeError, "Unknown arguments %s" % kwargs
321  if not self._filenames:
322  raise RuntimeError, "No input files given"
323  if not self._createFWLiteRun():
324  # this shouldn't happen as you are getting nothing the
325  # very first time out, but let's at least check to
326  # avoid problems.
327  raise RuntimeError, "Never and information about Run"
328 
329 
330  def __del__ (self):
331  """(Internal) Destructor"""
332  # print "Goodbye cruel world, I'm leaving you today."
333  del self._run
334  # print "Goodbye, goodbye, goodbye."
335 
336 
337  def __iter__ (self):
338  return self._next()
339 
340 
341  def aux (self):
342  try:
343  return self._run.runAuxiliary()
344  except:
345  raise RuntimeError, "Runs.aux() called on object in invalid state"
346 
347 
348  def runAuxiliary (self):
349  try:
350  return self._run.runAuxiliary()
351  except:
352  raise RuntimeError, "Runs.runAuxiliary() called on object in invalid state"
353 
354 
355  def getByLabel (self, *args):
356  """Calls FWLite's getByLabel. Called:
357  getByLabel (moduleLabel, handle)
358  getByLabel (moduleLabel, productInstanceLabel, handle),
359  getByLabel (moduleLabel, productInstanceLabel, processLabel, handle),
360  or
361  getByLabel ( (mL, pIL,pL), handle)
362  """
363  length = len (args)
364  if length < 2 or length > 4:
365  # not called correctly
366  raise RuntimeError, "Incorrect number of arguments"
367  # handle is always the last argument
368  argsList = list (args)
369  handle = argsList.pop()
370  if len(argsList)==1 and \
371  ( isinstance (argsList[0], tuple) or
372  isinstance (argsList[0], list) ) :
373  if len (argsList) > 3:
374  raise RuntimeError, "getByLabel Error: label tuple has too " \
375  "many arguments '%s'" % argsList[0]
376  argsList = list(argsList[0])
377  while len(argsList) < 3:
378  argsList.append ('')
379  (moduleLabel, productInstanceLabel, processLabel) = argsList
380  labelString = "'" + "', '".join(argsList) + "'"
381  handle._setStatus ( self._run.getByLabel( handle._typeInfoGetter(),
382  moduleLabel,
383  productInstanceLabel,
384  processLabel,
385  handle._addressOf() ),
386  labelString )
387  return handle.isValid()
388 
389 
390 
391 
392  ##############################
393  ## Private Member Functions ##
394  ##############################
395 
396  def _createFWLiteRun (self):
397  """(Internal) Creates an FWLite Run"""
398  # are there any files left?
399  if not self._filenames:
400  return False
401  if self._run:
402  del self._run
403  self._run = None
404  self._veryFirstTime = False
405  self._currFilename = self._filenames.pop(0)
406  #print "Opening file", self._currFilename
407  if self._tfile:
408  del self._tfile
409  self._tfile = ROOT.TFile.Open (self._currFilename)
410  self._run = ROOT.fwlite.Run (self._tfile);
411  self._run.toBegin()
412  return True
413 
414 
415  def _next (self):
416  """(Internal) Iterator internals"""
417  while True:
418  if self._run.atEnd():
419  if not self._createFWLiteRun():
420  # there are no more files here, so we are done
421  break
422  yield self
423  self._runCounts += 1
424  if self._maxRuns > 0 and self._runCounts >= self._maxRuns:
425  break
426  self._run.__preinc__()
427 
428 
429 ########################
430 ## ################## ##
431 ## ## ############ ## ##
432 ## ## ## Events ## ## ##
433 ## ## ############ ## ##
434 ## ################## ##
435 ########################
436 
437 class Events:
438  """Python interface to FWLite ChainEvent class"""
439 
440  def __init__(self, inputFiles = '', **kwargs):
441  """inputFiles => Either a single filename or a list of filenames
442  Optional arguments:
443  forceEvent => Use fwlite::Event IF there is only one file
444  maxEvents => Maximum number of events to process
445  """
446  self._veryFirstTime = True
447  self._event = 0
448  self._eventCounts = 0
449  self._maxEvents = 0
450  self._forceEvent = False
451  self._mode = None
453  if isinstance (inputFiles, list):
454  # it's a list
455  self._filenames = inputFiles[:]
456  elif isinstance (inputFiles, VarParsing):
457  # it's a VarParsing object
458  options = inputFiles
459  self._maxEvents = options.maxEvents
460  self._filenames = options.inputFiles
461  self._secondaryFilenames = options.secondaryInputFiles
462  else:
463  # it's probably a single string
464  self._filenames = [inputFiles]
465  ##############################
466  ## Parse optional arguments ##
467  ##############################
468  if kwargs.has_key ('maxEvents'):
469  self._maxEvents = kwargs['maxEvents']
470  del kwargs['maxEvents']
471  if kwargs.has_key ('forceEvent'):
472  self._forceEvent = kwargs['forceEvent']
473  del kwargs['forceEvent']
474  if kwargs.has_key ('options'):
475  options = kwargs ['options']
476  self._maxEvents = options.maxEvents
477  self._filenames = options.inputFiles
478  self._secondaryFilenames = options.secondaryInputFiles
479  del kwargs['options']
480  # Since we deleted the options as we used them, that means
481  # that kwargs should be empty. If it's not, that means that
482  # somebody passed in an argument that we're not using and we
483  # should complain.
484  if len (kwargs):
485  raise RuntimeError, "Unknown arguments %s" % kwargs
486  if not self._filenames:
487  raise RuntimeError, "No input files given"
488 
489 
490  def to (self, entryIndex):
491  """Jumps to event entryIndex"""
492  if self._veryFirstTime:
493  self._createFWLiteEvent()
494  return self._event.to ( long(entryIndex) )
495 
496 
497  def toBegin (self):
498  """Called to reset event loop to first event."""
499  self._toBegin = True
500 
501 
502  def size (self):
503  """Returns number of events"""
504  if self._veryFirstTime:
505  self._createFWLiteEvent()
506  return self._event.size()
507 
508 
509  def eventAuxiliary (self):
510  """Returns eventAuxiliary object"""
511  if self._veryFirstTime:
512  raise RuntimeError, "eventAuxiliary() called before "\
513  "toBegin() or to()"
514  return self._event.eventAuxiliary()
515 
516 
517  def object (self):
518  """Returns event object"""
519  return self._event
520 
521 
522  def getByLabel (self, *args):
523  """Calls FWLite's getByLabel. Called:
524  getByLabel (moduleLabel, handle)
525  getByLabel (moduleLabel, productInstanceLabel, handle),
526  getByLabel (moduleLabel, productInstanceLabel, processLabel, handle),
527  or
528  getByLabel ( (mL, pIL,pL), handle)
529  """
530  if self._veryFirstTime:
531  self._createFWLiteEvent()
532  length = len (args)
533  if length < 2 or length > 4:
534  # not called correctly
535  raise RuntimeError, "Incorrect number of arguments"
536  # handle is always the last argument
537  argsList = list (args)
538  handle = argsList.pop()
539  if len(argsList)==1 and \
540  ( isinstance (argsList[0], tuple) or
541  isinstance (argsList[0], list) ) :
542  if len (argsList) > 3:
543  raise RuntimeError, "getByLabel Error: label tuple has too " \
544  "many arguments '%s'" % argsList[0]
545  argsList = list(argsList[0])
546  while len(argsList) < 3:
547  argsList.append ('')
548  (moduleLabel, productInstanceLabel, processLabel) = argsList
549  labelString = "'" + "', '".join(argsList) + "'"
550  handle._setStatus ( self._event.getByLabel( handle._typeInfoGetter(),
551  moduleLabel,
552  productInstanceLabel,
553  processLabel,
554  handle._addressOf() ),
555  labelString )
556  return handle.isValid()
557 
558 
559  def __iter__ (self):
560  return self._next()
561 
562 
563  def fileIndex (self):
564  if self._event:
565  return self._event.fileIndex()
566  else:
567  # default non-existant value is -1. Return something else
568  return -2
569 
570 
571  def secondaryFileIndex (self):
572  if self._event:
573  return self._event.secondaryFileIndex()
574  else:
575  # default non-existant value is -1. Return something else
576  return -2
577 
578 
579  def fileIndicies (self):
580  return (self.fileIndex(), self.secondaryFileIndex())
581 
582 
583  ## Private Member Functions ##
584 
585 
586  def _parseOptions (self, options):
587  """(Internal) Parse options"""
588 
589 
590  def _toBeginCode (self):
591  """(Internal) Does actual work of toBegin() call"""
592  self._toBegin = False
593  self._event.toBegin()
594  self._eventCounts = 0
595 
596 
597  def __del__ (self):
598  """(Internal) Destructor"""
599  # print "Goodbye cruel world, I'm leaving you today."
600  del self._event
601  # print "Goodbye, goodbye, goodbye."
602 
603 
604  def _createFWLiteEvent (self):
605  """(Internal) Creates an FWLite Event"""
606  self._veryFirstTime = False
607  self._toBegin = True
608  if isinstance (self._filenames[0], ROOT.TFile):
609  self._event = ROOT.fwlite.Event (self._filenames[0])
610  self._mode = 'single'
611  return self._mode
612  if len (self._filenames) == 1 and self._forceEvent:
613  self._tfile = ROOT.TFile.Open (self._filenames[0])
614  self._event = ROOT.fwlite.Event (self._tfile)
615  self._mode = 'single'
616  return self._mode
617  filenamesSVec = ROOT.vector("string") ()
618  for name in self._filenames:
619  filenamesSVec.push_back (name)
620  if self._secondaryFilenames:
621  secondarySVec = ROOT.vector("string") ()
622  for name in self._secondaryFilenames:
623  secondarySVec.push_back (name)
624  self._event = ROOT.fwlite.MultiChainEvent (filenamesSVec,
625  secondarySVec)
626  self._mode = 'multi'
627  else:
628  self._event = ROOT.fwlite.ChainEvent (filenamesSVec)
629  self._mode = 'chain'
630  return self._mode
631 
632 
633  def _next (self):
634  """(Internal) Iterator internals"""
635  if self._veryFirstTime:
636  self._createFWLiteEvent()
637  if self._toBegin:
638  self._toBeginCode()
639  while not self._event.atEnd() :
640  yield self
641  self._eventCounts += 1
642  if self._maxEvents > 0 and self._eventCounts >= self._maxEvents:
643  break
644  # Have we been asked to go to the first event?
645  if self._toBegin:
646  self._toBeginCode()
647  else:
648  # if not, lets go to the next event
649  self._event.__preinc__()
650 
651 
652 
653 if __name__ == "__main__":
654  # test code can go here
655  pass
_secondaryFilenames
Definition: __init__.py:313
## Events
Definition: __init__.py:437
def _typeInfoGetter
Private member functions ##.
Definition: __init__.py:102
def _setStatus
Definition: __init__.py:112
def eventAuxiliary
Definition: __init__.py:509
def _createFWLiteEvent
Definition: __init__.py:604
## Runs
Definition: __init__.py:285
def getByLabel
Definition: __init__.py:204
def _createFWLiteLumi
Private Member Functions ##.
Definition: __init__.py:243
def luminosityBlockAuxiliary
Definition: __init__.py:197
def _parseOptions
Private Member Functions ##.
Definition: __init__.py:586
_maxRuns
Parse optional arguments ##.
Definition: __init__.py:291
def getByLabel
Definition: __init__.py:522
def __iter__
Definition: __init__.py:186
## Handle
Definition: __init__.py:49
def getByLabel
Definition: __init__.py:355
def __init__
Definition: __init__.py:54
def fileIndicies
Definition: __init__.py:579
def _createFWLiteRun
Private Member Functions ##.
Definition: __init__.py:396
_maxLumis
Parse optional arguments ##.
Definition: __init__.py:140
## Lumis
Definition: __init__.py:134
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def __init__
Definition: __init__.py:136
def _toBeginCode
Definition: __init__.py:590
def __del__
Definition: __init__.py:330
def secondaryFileIndex
Definition: __init__.py:571
def __init__
Definition: __init__.py:287
def warn
Definition: __init__.py:20
_maxEvents
Parse optional arguments ##.
Definition: __init__.py:449
def _addressOf
Definition: __init__.py:107
def __iter__
Definition: __init__.py:337
def setQuietWarn
Definition: __init__.py:16
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
def runAuxiliary
Definition: __init__.py:348