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