CMS 3D CMS Logo

output.py
Go to the documentation of this file.
1 from PhysicsTools.NanoAODTools.postprocessing.framework.treeReaderArrayTools import setExtraBranch
2 from array import array
3 import ROOT
4 ROOT.PyConfig.IgnoreCommandLineOptions = True
5 
6 
7 _rootBranchType2PythonArray = {
8  'b': 'B',
9  'B': 'b',
10  's': 'H',
11  'S': 'h',
12  'i': 'I',
13  'I': 'i',
14  'F': 'f',
15  'D': 'd',
16  'l': 'L',
17  'L': 'l',
18  'O': 'B'
19 }
20 
21 
23  def __init__(
24  self, tree, name, rootBranchType, n=1,
25  lenVar=None, title=None, limitedPrecision=False
26  ):
27  n = int(n)
28  self.buff = array(
29  _rootBranchType2PythonArray[rootBranchType], n * [0. if rootBranchType in 'FD' else 0])
30  self.lenVar = lenVar
31  self.n = n
32  self.precision = ROOT.MiniFloatConverter.ReduceMantissaToNbitsRounding(
33  limitedPrecision) if limitedPrecision and rootBranchType == 'F' else lambda x: x
34  # check if a branch was already there
35  existingBranch = tree.GetBranch(name)
36  if (existingBranch):
37  self.branch = existingBranch
38  self.branch.SetAddress(self.buff)
39  else:
40  if lenVar != None:
41  self.branch = tree.Branch(
42  name, self.buff, "%s[%s]/%s" % (name, lenVar, rootBranchType))
43  elif n == 1:
44  self.branch = tree.Branch(
45  name, self.buff, name + "/" + rootBranchType)
46  else:
47  self.branch = tree.Branch(
48  name, self.buff, "%s[%d]/%s" % (name, n, rootBranchType))
49  if title:
50  self.branch.SetTitle(title)
51 
52  def fill(self, val):
53  if self.lenVar:
54  if len(self.buff) < len(val): # realloc
55  self.buff = array(self.buff.typecode, max(
56  len(val), 2 * len(self.buff)) * [0. if self.buff.typecode in 'fd' else 0])
57  self.branch.SetAddress(self.buff)
58  for i, v in enumerate(val):
59  self.buff[i] = self.precision(v)
60  elif self.n == 1:
61  self.buff[0] = self.precision(val)
62  else:
63  if len(val) != self.n:
64  raise RuntimeError("Mismatch in filling branch %s of fixed length %d with %d values (%s)" % (
65  self.branch.GetName(), self.n, len(val), val))
66  for i, v in enumerate(val):
67  self.buff[i] = v
68 
69 
70 class OutputTree:
71  def __init__(self, tfile, ttree, intree):
72  self._file = tfile
73  self._tree = ttree
74  self._intree = intree
75  self._branches = {}
76 
77  def branch(
78  self, name, rootBranchType, n=1, lenVar=None,
79  title=None, limitedPrecision=False
80  ):
81  # and (not self._tree.GetBranch(lenVar)):
82  if (lenVar != None) and (lenVar not in self._branches):
83  self._branches[lenVar] = OutputBranch(self._tree, lenVar, "i")
84  self._branches[name] = OutputBranch(
85  self._tree, name, rootBranchType, n=n,
86  lenVar=lenVar, title=title, limitedPrecision=limitedPrecision
87  )
88  return self._branches[name]
89 
90  def fillBranch(self, name, val):
91  br = self._branches[name]
92  if br.lenVar and (br.lenVar in self._branches):
93  self._branches[br.lenVar].buff[0] = len(val)
94  setExtraBranch(self._intree, br.lenVar, len(val))
95  br.fill(val)
96  setExtraBranch(self._intree, name, val)
97 
98  def tree(self):
99  return self._tree
100 
101  def fill(self):
102  self._tree.Fill()
103 
104  def write(self):
105  self._file.cd()
106  self._tree.Write()
107 
108 
110  def __init__(
111  self,
112  inputFile,
113  inputTree,
114  outputFile,
115  branchSelection=None,
116  outputbranchSelection=None,
117  fullClone=False,
118  maxEntries=None,
119  firstEntry=0,
120  provenance=False,
121  jsonFilter=None
122  ):
123  outputFile.cd()
124 
125  self.outputbranchSelection = outputbranchSelection
126  self.maxEntries = maxEntries
127  self.firstEntry = firstEntry
128  if fullClone:
129  outputTree = inputTree.CopyTree(
130  '1', "", maxEntries if maxEntries else ROOT.TVirtualTreePlayer.kMaxEntries, firstEntry)
131  else:
132  outputTree = inputTree.CloneTree(0)
133 
134  # enable back all branches in inputTree, then disable for computation
135  # the branches as requested in branchSelection
136  inputTree.SetBranchStatus("*", 1)
137  if branchSelection:
138  branchSelection.selectBranches(inputTree)
139 
140  OutputTree.__init__(self, outputFile, outputTree, inputTree)
141  self._inputTree = inputTree
142  self._otherTrees = {}
143  self._otherObjects = {}
144  for k in inputFile.GetListOfKeys():
145  kn = k.GetName()
146  if kn == "Events":
147  continue # this we are doing
148  elif kn in ("MetaData", "ParameterSets"):
149  if provenance:
150  # treat content of other trees as if associated to event 0
151  self._otherTrees[kn] = inputFile.Get(
152  kn).CopyTree('1' if firstEntry == 0 else '0')
153  elif kn in ("LuminosityBlocks", "Runs"):
154  if not jsonFilter:
155  self._otherTrees[kn] = inputFile.Get(
156  kn).CopyTree('1' if firstEntry == 0 else '0')
157  elif firstEntry == 0:
158  _isRun = (kn == "Runs")
159  _it = inputFile.Get(kn)
160  _ot = _it.CloneTree(0)
161  for ev in _it:
162  if (jsonFilter.filterRunOnly(ev.run) if _isRun else jsonFilter.filterRunLumi(ev.run, ev.luminosityBlock)):
163  _ot.Fill()
164  self._otherTrees[kn] = _ot
165  elif k.GetClassName() == "TTree":
166  print("Not copying unknown tree %s" % kn)
167  else:
168  self._otherObjects[kn] = inputFile.Get(kn)
169 
170  def fill(self):
171  self._inputTree.readAllBranches()
172  self._tree.Fill()
173 
174  def write(self):
175  if self.outputbranchSelection:
176  self.outputbranchSelection.selectBranches(self._tree)
177  self._tree = self.tree().CopyTree('1', "",
178  self.maxEntries if self.maxEntries else ROOT.TVirtualTreePlayer.kMaxEntries, 0)
179 
180  OutputTree.write(self)
181  for t in self._otherTrees.values():
182  t.Write()
183  for on, ov in self._otherObjects.items():
184  self._file.WriteTObject(ov, on)
185 
186 
188  def __init__(self, inputFile, inputTree, outputFile, treeName="Friends"):
189  outputFile.cd()
190  outputTree = ROOT.TTree(
191  treeName, "Friend tree for " + inputTree.GetName())
192  OutputTree.__init__(self, outputFile, outputTree, inputTree)
def write(self)
Definition: output.py:104
def __init__(self, tree, name, rootBranchType, n=1, lenVar=None, title=None, limitedPrecision=False)
Definition: output.py:26
def __init__(self, inputFile, inputTree, outputFile, branchSelection=None, outputbranchSelection=None, fullClone=False, maxEntries=None, firstEntry=0, provenance=False, jsonFilter=None)
Definition: output.py:122
def fill(self)
Definition: output.py:170
def fill(self)
Definition: output.py:101
def fillBranch(self, name, val)
Definition: output.py:90
void Fill(HcalDetId &id, double val, std::vector< TH2F > &depth)
def write(self)
Definition: output.py:174
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def branch(self, name, rootBranchType, n=1, lenVar=None, title=None, limitedPrecision=False)
Definition: output.py:80
def __init__(self, inputFile, inputTree, outputFile, treeName="Friends")
Definition: output.py:188
def fill(self, val)
Definition: output.py:52
def __init__(self, tfile, ttree, intree)
Definition: output.py:71
def setExtraBranch(tree, name, val)
def tree(self)
Definition: output.py:98