CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
chain.py
Go to the documentation of this file.
1 # Copyright (C) 2014 Colin Bernet
2 # https://github.com/cbernet/heppy/blob/master/LICENSE
3 
4 import glob
5 import os
6 import pprint
7 from ROOT import TChain, TFile, TTree, gSystem
8 
9 class Chain( object ):
10  """Wrapper to TChain, with a python iterable interface.
11 
12  Example of use: #TODO make that a doctest / nose?
13  from chain import Chain
14  the_chain = Chain('../test/test_*.root', 'test_tree')
15  event3 = the_chain[2]
16  print event3.var1
17 
18  for event in the_chain:
19  print event.var1
20  """
21 
22  def __init__(self, input, tree_name=None):
23  """
24  Create a chain.
25 
26  Parameters:
27  input = either a list of files or a wildcard (e.g. 'subdir/*.root').
28  In the latter case all files matching the pattern will be used
29  to build the chain.
30  tree_name = key of the tree in each file.
31  if None and if each file contains only one TTree,
32  this TTree is used.
33  """
34  self.files = input
35  if isinstance(input, basestring): # input is a pattern
36  self.files = glob.glob(input)
37  if len(self.files)==0:
38  raise ValueError('no matching file name: '+input)
39  else: # case of a list of files
40  if False in [ os.path.isfile(fnam) for fnam in self.files ]:
41  err = 'at least one input file does not exist\n'
42  err += pprint.pformat(self.files)
43  raise ValueError(err)
44  if tree_name is None:
45  tree_name = self._guessTreeName(input)
46  self.chain = TChain(tree_name)
47  for file in self.files:
48  self.chain.Add(file)
49 
50  def _guessTreeName(self, pattern):
51  """
52  Find the set of keys of all TTrees in all files matching pattern.
53  If the set contains only one key
54  Returns: the TTree key
55  else raises ValueError.
56  """
57  names = []
58  for fnam in self.files:
59  rfile = TFile(fnam)
60  for key in rfile.GetListOfKeys():
61  obj = rfile.Get(key.GetName())
62  if type(obj) is TTree:
63  names.append( key.GetName() )
64  thename = set(names)
65  if len(thename)==1:
66  return list(thename)[0]
67  else:
68  err = [
69  'several TTree keys in {pattern}:'.format(
70  pattern=pattern
71  ),
72  ','.join(thename)
73  ]
74  raise ValueError('\n'.join(err))
75 
76  def __getattr__(self, attr):
77  """
78  All functions of the wrapped TChain are made available
79  """
80  return getattr(self.chain, attr)
81 
82  def __iter__(self):
83  return iter(self.chain)
84 
85  def __len__(self):
86  return int(self.chain.GetEntries())
87 
88  def __getitem__(self, index):
89  """
90  Returns the event at position index.
91  """
92  self.chain.GetEntry(index)
93  return self.chain
94 
95 
96 if __name__ == '__main__':
97 
98  import sys
99 
100  if len(sys.argv)!=3:
101  print 'usage: Chain.py <tree_name> <pattern>'
102  sys.exit(1)
103  tree_name = sys.argv[1]
104  pattern = sys.argv[2]
105  chain = Chain( tree_name, pattern )
def _guessTreeName
Definition: chain.py:50
def __iter__
Definition: chain.py:82
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def __init__
Definition: chain.py:22
list object
Definition: dbtoconf.py:77
def __getattr__
Definition: chain.py:76
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 __len__
Definition: chain.py:85
def __getitem__
Definition: chain.py:88