ROOT  6.07/01
Reference Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
TTreeReader.cxx
Go to the documentation of this file.
1 // @(#)root/treeplayer:$Id$
2 // Author: Axel Naumann, 2011-09-21
3 
4 /*************************************************************************
5  * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers and al. *
6  * All rights reserved. *
7  * *
8  * For the licensing terms see $ROOTSYS/LICENSE. *
9  * For the list of contributors see $ROOTSYS/README/CREDITS. *
10  *************************************************************************/
11 
12 #include "TTreeReader.h"
13 
14 #include "TChain.h"
15 #include "TDirectory.h"
16 #include "TTreeReaderValue.h"
17 
18 /** \class TTreeReader
19  TTreeReader is a simple, robust and fast interface to read values from a TTree,
20  TChain or TNtuple.
21 
22  It uses TTreeReaderValue<T> and TTreeReaderArray<T> to access the data.
23 
24  Example code can be found in
25  tutorials/tree/hsimpleReader.C and tutorials/trees/h1analysisTreeReader.h and
26  tutorials/trees/h1analysisTreeReader.C for a TSelector.
27 
28  Roottest contains an
29  <a href="http://root.cern.ch/gitweb?p=roottest.git;a=tree;f=root/tree/reader;hb=HEAD">example</a>
30  showing the full power.
31 
32 A simpler analysis example - the one from the tutorials - can be found below:
33 it histograms a function of the px and py branches.
34 
35 ~~~{.cpp}
36 // A simple TTreeReader use: read data from hsimple.root (written by hsimple.C)
37 
38 #include "TFile.h
39 #include "TH1F.h
40 #include "TTreeReader.h
41 #include "TTreeReaderValue.h
42 
43 void hsimpleReader() {
44  // Create a histogram for the values we read.
45  TH1F("h1", "ntuple", 100, -4, 4);
46 
47  // Open the file containing the tree.
48  TFile *myFile = TFile::Open("$ROOTSYS/tutorials/hsimple.root");
49 
50  // Create a TTreeReader for the tree, for instance by passing the
51  // TTree's name and the TDirectory / TFile it is in.
52  TTreeReader myReader("ntuple", myFile);
53 
54  // The branch "px" contains floats; access them as myPx.
55  TTreeReaderValue<Float_t> myPx(myReader, "px");
56  // The branch "py" contains floats, too; access those as myPy.
57  TTreeReaderValue<Float_t> myPy(myReader, "py");
58 
59  // Loop over all entries of the TTree or TChain.
60  while (myReader.Next()) {
61  // Just access the data as if myPx and myPy were iterators (note the '*'
62  // in front of them):
63  myHist->Fill(*myPx + *myPy);
64  }
65 
66  myHist->Draw();
67 }
68 ~~~
69 
70 A more complete example including error handling and a few combinations of
71 TTreeReaderValue and TTreeReaderArray would look like this:
72 
73 ~~~{.cpp}
74 #include <TFile.h>
75 #include <TH1.h>
76 #include <TTreeReader.h>
77 #include <TTreeReaderValue.h>
78 #include <TTreeReaderArray.h>
79 
80 #include "TriggerInfo.h"
81 #include "Muon.h"
82 #include "Tau.h"
83 
84 #include <vector>
85 #include <iostream>
86 
87 bool CheckValue(ROOT::TTreeReaderValueBase* value) {
88  if (value->GetSetupStatus() < 0) {
89  std::cerr << "Error " << value->GetSetupStatus()
90  << "setting up reader for " << value->GetBranchName() << '\n';
91  return false;
92  }
93  return true;
94 }
95 
96 
97 // Analyze the tree "MyTree" in the file passed into the function.
98 // Returns false in case of errors.
99 bool analyze(TFile* file) {
100  // Create a TTreeReader named "MyTree" from the given TDirectory.
101  // The TTreeReader gives access to the TTree to the TTreeReaderValue and
102  // TTreeReaderArray objects. It knows the current entry number and knows
103  // how to iterate through the TTree.
104  TTreeReader reader("MyTree", file);
105 
106  // Read a single float value in each tree entries:
107  TTreeReaderValue<float> weight(reader, "event.weight");
108  if (!CheckValue(weight)) return false;
109 
110  // Read a TriggerInfo object from the tree entries:
111  TTreeReaderValue<TriggerInfo> triggerInfo(reader, "triggerInfo");
112  if (!CheckValue(triggerInfo)) return false;
113 
114  //Read a vector of Muon objects from the tree entries:
115  TTreeReaderValue<std::vector<Muon>> muons(reader, "muons");
116  if (!CheckValue(muons)) return false;
117 
118  //Read the pT for all jets in the tree entry:
119  TTreeReaderArray<double> jetPt(reader, "jets.pT");
120  if (!CheckValue(jetPt)) return false;
121 
122  // Read the taus in the tree entry:
123  TTreeReaderArray<Tau> taus(reader, "taus");
124  if (!CheckValue(taus)) return false;
125 
126 
127  // Now iterate through the TTree entries and fill a histogram.
128 
129  TH1F("hist", "TTreeReader example histogram", 10, 0., 100.);
130 
131  while (reader.Next()) {
132 
133  if (reader.GetEntryStatus() == kEntryValid) {
134  std::cout << "Loaded entry " << reader.GetCurrentEntry() << '\n';
135  } else {
136  switch (reader.GetEntryStatus()) {
137  kEntryValid:
138  // Handled above.
139  break;
140  kEntryNotLoaded:
141  std::cerr << "Error: TTreeReader has not loaded any data yet!\n";
142  break;
143  kEntryNoTree:
144  std::cerr << "Error: TTreeReader cannot find a tree names \"MyTree\"!\n";
145  break;
146  kEntryNotFound:
147  // Can't really happen as TTreeReader::Next() knows when to stop.
148  std::cerr << "Error: The entry number doe not exist\n";
149  break;
150  kEntryChainSetupError:
151  std::cerr << "Error: TTreeReader cannot access a chain element, e.g. file without the tree\n";
152  break;
153  kEntryChainFileError:
154  std::cerr << "Error: TTreeReader cannot open a chain element, e.g. missing file\n";
155  break;
156  kEntryDictionaryError:
157  std::cerr << "Error: TTreeReader cannot find the dictionary for some data\n";
158  break;
159  }
160  return false;
161  }
162 
163  // Access the TriggerInfo object as if it's a pointer.
164  if (!triggerInfo->hasMuonL1())
165  continue;
166 
167  // Ditto for the vector<Muon>.
168  if (!muons->size())
169  continue;
170 
171  // Access the jetPt as an array, whether the TTree stores this as
172  // a std::vector, std::list, TClonesArray or Jet* C-style array, with
173  // fixed or variable array size.
174  if (jetPt.GetSize() < 2 || jetPt[0] < 100)
175  continue;
176 
177  // Access the array of taus.
178  if (!taus.IsEmpty()) {
179  float currentWeight = *weight;
180  for (int iTau = 0, nTau = taus.GetSize(); iTau < nTau; ++iTau) {
181  // Access a float value - need to dereference as TTreeReaderValue
182  // behaves like an iterator
183  hist->Fill(taus[iTau].eta(), currentWeight);
184  }
185  }
186  } // TTree entry / event loop
187 }
188 ~~~
189 */
190 
192 
193 using namespace ROOT::Internal;
194 
195 ////////////////////////////////////////////////////////////////////////////////
196 /// Access data from tree.
197 
199  fTree(tree),
200  fDirectory(0),
201  fEntryStatus(kEntryNotLoaded),
202  fDirector(0),
203  fLastEntry(-1),
204  fProxiesSet(kFALSE)
205 {
206  Initialize();
207 }
208 
209 ////////////////////////////////////////////////////////////////////////////////
210 /// Access data from the tree called keyname in the directory (e.g. TFile)
211 /// dir, or the current directory if dir is NULL. If keyname cannot be
212 /// found, or if it is not a TTree, IsZombie() will return true.
213 
214 TTreeReader::TTreeReader(const char* keyname, TDirectory* dir /*= NULL*/):
215  fTree(0),
216  fDirectory(dir),
217  fEntryStatus(kEntryNotLoaded),
218  fDirector(0),
219  fLastEntry(-1),
220  fProxiesSet(kFALSE)
221 {
223  fDirectory->GetObject(keyname, fTree);
224  Initialize();
225 }
226 
227 ////////////////////////////////////////////////////////////////////////////////
228 /// Tell all value readers that the tree reader does not exist anymore.
229 
231 {
232  for (std::deque<ROOT::Internal::TTreeReaderValueBase*>::const_iterator
233  i = fValues.begin(), e = fValues.end(); i != e; ++i) {
234  (*i)->MarkTreeReaderUnavailable();
235  }
236  delete fDirector;
237  fProxies.SetOwner();
238 }
239 
240 ////////////////////////////////////////////////////////////////////////////////
241 /// Initialization of the director.
242 
244 {
245  if (!fTree) {
246  MakeZombie();
248  } else {
250  }
251 }
252 
253 ////////////////////////////////////////////////////////////////////////////////
254 /// Set the range of entries to be processed.
255 /// If last > first, this call is equivalent to
256 /// `SetEntry(first); SetLastEntry(last);`. Otherwise `last` is ignored and
257 /// only `first` is set.
258 /// \return the EEntryStatus that would be returned by SetEntry(first)
259 
261 {
262  if(last > first)
263  fLastEntry = last;
264  else
265  fLastEntry = -1;
266  return SetLocalEntry(first);
267 }
268 
269 ////////////////////////////////////////////////////////////////////////////////
270 ///Returns the index of the current entry being read
271 
273  if (!fDirector) return 0;
274  Long64_t currentTreeEntry = fDirector->GetReadEntry();
275  if (fTree->IsA() == TChain::Class() && currentTreeEntry >= 0) {
276  return ((TChain*)fTree)->GetChainEntryNumber(currentTreeEntry);
277  }
278  return currentTreeEntry;
279 }
280 
281 ////////////////////////////////////////////////////////////////////////////////
282 /// Load an entry into the tree, return the status of the read.
283 /// For chains, entry is the global (i.e. not tree-local) entry number.
284 
286 {
287  if (!fTree) {
289  return fEntryStatus;
290  }
291 
292  TTree* prevTree = fDirector->GetTree();
293 
294  Long64_t loadResult;
295  if (!local){
296  Int_t treeNumInChain = fTree->GetTreeNumber();
297 
298  loadResult = fTree->LoadTree(entry);
299 
300  if (loadResult == -2) {
302  return fEntryStatus;
303  }
304 
305  Int_t currentTreeNumInChain = fTree->GetTreeNumber();
306  if (treeNumInChain != currentTreeNumInChain) {
308  }
309  }
310  else {
311  loadResult = entry;
312  }
313  if (!prevTree || fDirector->GetReadEntry() == -1 || !fProxiesSet) {
314  // Tell readers we now have a tree
315  for (std::deque<ROOT::Internal::TTreeReaderValueBase*>::const_iterator
316  i = fValues.begin(); i != fValues.end(); ++i) { // Iterator end changes when parameterized arrays are read
317  (*i)->CreateProxy();
318 
319  if (!(*i)->GetProxy()){
321  return fEntryStatus;
322  }
323  }
324  // If at least one proxy was there and no error occurred, we assume the proxies to be set.
325  fProxiesSet = !fValues.empty();
326  }
327  if (fLastEntry >= 0 && loadResult >= fLastEntry) {
329  return fEntryStatus;
330  }
331  fDirector->SetReadEntry(loadResult);
333  return fEntryStatus;
334 }
335 
336 ////////////////////////////////////////////////////////////////////////////////
337 /// Set (or update) the which tree to reader from. tree can be
338 /// a TTree or a TChain.
339 
341 {
342  fTree = tree;
343  if (fTree) {
344  ResetBit(kZombie);
345  if (fTree->InheritsFrom(TChain::Class())) {
347  }
348  }
349 
350  if (!fDirector) {
351  Initialize();
352  }
353  else {
355  fDirector->SetReadEntry(-1);
356  }
357 }
358 
359 ////////////////////////////////////////////////////////////////////////////////
360 /// Add a value reader for this tree.
361 
363 {
364  fValues.push_back(reader);
365 }
366 
367 ////////////////////////////////////////////////////////////////////////////////
368 /// Remove a value reader for this tree.
369 
371 {
372  std::deque<ROOT::Internal::TTreeReaderValueBase*>::iterator iReader
373  = std::find(fValues.begin(), fValues.end(), reader);
374  if (iReader == fValues.end()) {
375  Error("DeregisterValueReader", "Cannot find reader of type %s for branch %s", reader->GetDerivedTypeName(), reader->fBranchName.Data());
376  return;
377  }
378  fValues.erase(iReader);
379 }
long long Long64_t
Definition: RtypesCore.h:69
TTreeReader is a simple, robust and fast interface to read values from a TTree, TChain or TNtuple...
Definition: TTreeReader.h:48
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition: TObject.cxx:487
void GetObject(const char *namecycle, T *&ptr)
Definition: TDirectory.h:147
virtual void SetOwner(Bool_t enable=kTRUE)
Set whether this collection is the owner (enable==true) of its content.
std::deque< ROOT::Internal::TTreeReaderValueBase * > fValues
Definition: TTreeReader.h:197
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
const Bool_t kFALSE
Definition: Rtypes.h:92
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:732
THashTable fProxies
Definition: TTreeReader.h:198
const char * Data() const
Definition: TString.h:349
EEntryStatus SetEntryBase(Long64_t entry, Bool_t local)
Load an entry into the tree, return the status of the read.
void Class()
Definition: Class.C:29
virtual Long64_t LoadTree(Long64_t entry)
Set current entry.
Definition: TTree.cxx:5785
Long64_t GetCurrentEntry() const
Returns the index of the current entry being read.
TDirectory * fDirectory
Definition: TTreeReader.h:194
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:918
EEntryStatus fEntryStatus
Definition: TTreeReader.h:195
Long64_t fLastEntry
Definition: TTreeReader.h:199
void RegisterValueReader(ROOT::Internal::TTreeReaderValueBase *reader)
Add a value reader for this tree.
ROOT::Internal::TBranchProxyDirector * fDirector
Definition: TTreeReader.h:196
void Initialize(Bool_t useTMVAStyle=kTRUE)
Definition: tmvaglob.cxx:176
virtual Int_t GetTreeNumber() const
Definition: TTree.h:438
Bool_t fProxiesSet
Definition: TTreeReader.h:200
~TTreeReader()
Tell all value readers that the tree reader does not exist anymore.
bool first
Definition: line3Dfit.C:48
Long64_t entry
tuple tree
Definition: tree.py:24
EEntryStatus SetLocalEntry(Long64_t entry)
Definition: TTreeReader.h:160
#define ClassImp(name)
Definition: Rtypes.h:279
Describe directory structure in memory.
Definition: TDirectory.h:44
TTree * fTree
Definition: TTreeReader.h:193
void dir(char *path=0)
Definition: rootalias.C:30
void Initialize()
Initialization of the director.
void DeregisterValueReader(ROOT::Internal::TTreeReaderValueBase *reader)
Remove a value reader for this tree.
virtual TTree * GetTree() const
Definition: TTree.h:436
void MakeZombie()
Definition: TObject.h:68
virtual const char * GetDerivedTypeName() const =0
A chain is a collection of files containg TTree objects.
Definition: TChain.h:35
A TTree object has a header with a name and a title.
Definition: TTree.h:98
#define gDirectory
Definition: TDirectory.h:221
void SetTree(TTree *tree)
Set (or update) the which tree to reader from.
void ResetBit(UInt_t f)
Definition: TObject.h:172
EEntryStatus SetEntriesRange(Long64_t first, Long64_t last)
Set the range of entries to be processed.