Logo ROOT   6.10/09
Reference Guide
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 "TEntryList.h"
17 #include "TTreeReaderValue.h"
18 
19 /** \class TTreeReader
20  TTreeReader is a simple, robust and fast interface to read values from a TTree,
21  TChain or TNtuple.
22 
23  It uses `TTreeReaderValue<T>` and `TTreeReaderArray<T>` to access the data.
24 
25  Example code can be found in
26  tutorials/tree/hsimpleReader.C and tutorials/trees/h1analysisTreeReader.h and
27  tutorials/trees/h1analysisTreeReader.C for a TSelector.
28 
29  You can generate a skeleton of `TTreeReaderValue<T>` and `TTreeReaderArray<T>` declarations
30  for all of a tree's branches using `TTree::MakeSelector()`.
31 
32  Roottest contains an
33  <a href="http://root.cern.ch/gitweb?p=roottest.git;a=tree;f=root/tree/reader;hb=HEAD">example</a>
34  showing the full power.
35 
36 A simpler analysis example - the one from the tutorials - can be found below:
37 it histograms a function of the px and py branches.
38 
39 ~~~{.cpp}
40 // A simple TTreeReader use: read data from hsimple.root (written by hsimple.C)
41 
42 #include "TFile.h
43 #include "TH1F.h
44 #include "TTreeReader.h
45 #include "TTreeReaderValue.h
46 
47 void hsimpleReader() {
48  // Create a histogram for the values we read.
49  TH1F("h1", "ntuple", 100, -4, 4);
50 
51  // Open the file containing the tree.
52  TFile *myFile = TFile::Open("$ROOTSYS/tutorials/hsimple.root");
53 
54  // Create a TTreeReader for the tree, for instance by passing the
55  // TTree's name and the TDirectory / TFile it is in.
56  TTreeReader myReader("ntuple", myFile);
57 
58  // The branch "px" contains floats; access them as myPx.
59  TTreeReaderValue<Float_t> myPx(myReader, "px");
60  // The branch "py" contains floats, too; access those as myPy.
61  TTreeReaderValue<Float_t> myPy(myReader, "py");
62 
63  // Loop over all entries of the TTree or TChain.
64  while (myReader.Next()) {
65  // Just access the data as if myPx and myPy were iterators (note the '*'
66  // in front of them):
67  myHist->Fill(*myPx + *myPy);
68  }
69 
70  myHist->Draw();
71 }
72 ~~~
73 
74 A more complete example including error handling and a few combinations of
75 TTreeReaderValue and TTreeReaderArray would look like this:
76 
77 ~~~{.cpp}
78 #include <TFile.h>
79 #include <TH1.h>
80 #include <TTreeReader.h>
81 #include <TTreeReaderValue.h>
82 #include <TTreeReaderArray.h>
83 
84 #include "TriggerInfo.h"
85 #include "Muon.h"
86 #include "Tau.h"
87 
88 #include <vector>
89 #include <iostream>
90 
91 bool CheckValue(ROOT::Internal::TTreeReaderValueBase& value) {
92  if (value->GetSetupStatus() < 0) {
93  std::cerr << "Error " << value->GetSetupStatus()
94  << "setting up reader for " << value->GetBranchName() << '\n';
95  return false;
96  }
97  return true;
98 }
99 
100 
101 // Analyze the tree "MyTree" in the file passed into the function.
102 // Returns false in case of errors.
103 bool analyze(TFile* file) {
104  // Create a TTreeReader named "MyTree" from the given TDirectory.
105  // The TTreeReader gives access to the TTree to the TTreeReaderValue and
106  // TTreeReaderArray objects. It knows the current entry number and knows
107  // how to iterate through the TTree.
108  TTreeReader reader("MyTree", file);
109 
110  // Read a single float value in each tree entries:
111  TTreeReaderValue<float> weight(reader, "event.weight");
112 
113  // Read a TriggerInfo object from the tree entries:
114  TTreeReaderValue<TriggerInfo> triggerInfo(reader, "triggerInfo");
115 
116  //Read a vector of Muon objects from the tree entries:
117  TTreeReaderValue<std::vector<Muon>> muons(reader, "muons");
118 
119  //Read the pT for all jets in the tree entry:
120  TTreeReaderArray<double> jetPt(reader, "jets.pT");
121 
122  // Read the taus in the tree entry:
123  TTreeReaderArray<Tau> taus(reader, "taus");
124 
125 
126  // Now iterate through the TTree entries and fill a histogram.
127 
128  TH1F("hist", "TTreeReader example histogram", 10, 0., 100.);
129 
130  while (reader.Next()) {
131  if (!CheckValue(weight)) return false;
132  if (!CheckValue(triggerInfo)) return false;
133  if (!CheckValue(muons)) return false;
134  if (!CheckValue(jetPt)) return false;
135  if (!CheckValue(taus)) return false;
136 
137  // Access the TriggerInfo object as if it's a pointer.
138  if (!triggerInfo->hasMuonL1())
139  continue;
140 
141  // Ditto for the vector<Muon>.
142  if (!muons->size())
143  continue;
144 
145  // Access the jetPt as an array, whether the TTree stores this as
146  // a std::vector, std::list, TClonesArray or Jet* C-style array, with
147  // fixed or variable array size.
148  if (jetPt.GetSize() < 2 || jetPt[0] < 100)
149  continue;
150 
151  // Access the array of taus.
152  if (!taus.IsEmpty()) {
153  // Access a float value - need to dereference as TTreeReaderValue
154  // behaves like an iterator
155  float currentWeight = *weight;
156  for (const Tau& tau: taus) {
157  hist->Fill(tau.eta(), currentWeight);
158  }
159  }
160  } // TTree entry / event loop
161 }
162 ~~~
163 */
164 
166 
167 using namespace ROOT::Internal;
168 
169 ////////////////////////////////////////////////////////////////////////////////
170 /// Access data from tree.
171 
172 TTreeReader::TTreeReader(TTree* tree, TEntryList* entryList /*= nullptr*/):
173  fTree(tree),
174  fEntryList(entryList)
175 {
176  if (!fTree) {
177  Error("TTreeReader", "TTree is NULL!");
178  } else {
179  Initialize();
180  }
181 }
182 
183 ////////////////////////////////////////////////////////////////////////////////
184 /// Access data from the tree called keyname in the directory (e.g. TFile)
185 /// dir, or the current directory if dir is NULL. If keyname cannot be
186 /// found, or if it is not a TTree, IsZombie() will return true.
187 
188 TTreeReader::TTreeReader(const char* keyname, TDirectory* dir, TEntryList* entryList /*= nullptr*/):
189  fEntryList(entryList)
190 {
191  if (!dir) dir = gDirectory;
192  dir->GetObject(keyname, fTree);
193  Initialize();
194 }
195 
196 ////////////////////////////////////////////////////////////////////////////////
197 /// Tell all value readers that the tree reader does not exist anymore.
198 
200 {
201  for (std::deque<ROOT::Internal::TTreeReaderValueBase*>::const_iterator
202  i = fValues.begin(), e = fValues.end(); i != e; ++i) {
203  (*i)->MarkTreeReaderUnavailable();
204  }
205  delete fDirector;
206 }
207 
208 ////////////////////////////////////////////////////////////////////////////////
209 /// Initialization of the director.
210 
212 {
213  fEntry = -1;
214  if (!fTree) {
215  MakeZombie();
218  return;
219  }
220 
221  ResetBit(kZombie);
222  if (fTree->InheritsFrom(TChain::Class())) {
224  }
226 }
227 
228 ////////////////////////////////////////////////////////////////////////////////
229 /// Set the range of entries to be loaded by `Next()`; end will not be loaded.
230 ///
231 /// If end <= begin, `end` is ignored (set to `-1`) and only `begin` is used.
232 /// Example:
233 ///
234 /// ~~~ {.cpp}
235 /// reader.SetEntriesRange(3, 5);
236 /// while (reader.Next()) {
237 /// // Will load entries 3 and 4.
238 /// }
239 /// ~~~
240 ///
241 /// \param beginEntry The first entry to be loaded by `Next()`.
242 /// \param endEntry The entry where `Next()` will return kFALSE, not loading it.
243 
245 {
246  if (beginEntry < 0)
247  return kEntryNotFound;
248  // Complain if the entries number is larger than the tree's / chain's / entry
249  // list's number of entries, unless it's a TChain and "max entries" is
250  // uninitialized (i.e. TTree::kMaxEntries).
251  if (beginEntry >= GetEntries(false) && !(IsChain() && GetEntries(false) == TTree::kMaxEntries))
252  return kEntryNotFound;
253 
254  if (endEntry > beginEntry)
255  fEndEntry = endEntry;
256  else
257  fEndEntry = -1;
258  if (beginEntry - 1 < 0)
259  Restart();
260  else
261  SetEntry(beginEntry - 1);
262  return kEntryValid;
263 }
264 
265 void TTreeReader::Restart() {
266  fDirector->SetTree(nullptr);
267  fDirector->SetReadEntry(-1);
268  fProxiesSet = false; // we might get more value readers, meaning new proxies.
269  fEntry = -1;
270 }
271 
272 ////////////////////////////////////////////////////////////////////////////////
273 /// Returns the number of entries of the TEntryList if one is provided, else
274 /// of the TTree / TChain, independent of a range set by SetEntriesRange().
275 ///
276 /// \param force If `IsChain()` and `force`, determines whether all TFiles of
277 /// this TChain should be opened to determine the exact number of entries
278 /// of the TChain. If `!IsChain()`, `force` is ignored.
279 
281  if (fEntryList)
282  return fEntryList->GetN();
283  if (!fTree)
284  return -1;
285  if (force)
286  return fTree->GetEntries();
287  return fTree->GetEntriesFast();
288 }
289 
290 
291 
292 ////////////////////////////////////////////////////////////////////////////////
293 /// Load an entry into the tree, return the status of the read.
294 /// For chains, entry is the global (i.e. not tree-local) entry number, unless
295 /// `local` is `true`, in which case `entry` specifies the entry number within
296 /// the current tree. This is needed for instance for TSelector::Process().
297 
299 {
300  if (!fTree || !fDirector) {
302  fEntry = -1;
303  return fEntryStatus;
304  }
305 
306  if (fTree->GetEntryList() && !TestBit(kBitHaveWarnedAboutEntryListAttachedToTTree)) {
307  Warning("SetEntryBase()",
308  "The TTree / TChain has an associated TEntryList. "
309  "TTreeReader ignores TEntryLists unless you construct the TTreeReader passing a TEntryList.");
311  }
312 
313  fEntry = entry;
314 
315  Long64_t entryAfterList = entry;
316  if (fEntryList) {
317  if (entry >= fEntryList->GetN()) {
318  // Passed the end of the chain, Restart() was not called:
319  // don't try to load entries anymore. Can happen in these cases:
320  // while (tr.Next()) {something()};
321  // while (tr.Next()) {somethingelse()}; // should not be calling somethingelse().
323  return fEntryStatus;
324  }
325  if (entry >= 0) entryAfterList = fEntryList->GetEntry(entry);
326  if (local && IsChain()) {
327  // Must translate the entry list's entry to the current TTree's entry number.
328  local = kFALSE;
329  }
330  }
331 
332  if (fProxiesSet && fDirector && fDirector->GetReadEntry() == -1
333  && fMostRecentTreeNumber != -1) {
334  // Passed the end of the chain, Restart() was not called:
335  // don't try to load entries anymore. Can happen in these cases:
336  // while (tr.Next()) {something()};
337  // while (tr.Next()) {somethingelse()}; // should not be calling somethingelse().
339  return fEntryStatus;
340  }
341 
342  Int_t treeNumberBeforeLoadTree = fTree->GetTreeNumber();
343 
344  TTree* treeToCallLoadOn = local ? fTree->GetTree() : fTree;
345  Long64_t loadResult = treeToCallLoadOn->LoadTree(entryAfterList);
346 
347  if (loadResult == -2) {
348  fDirector->SetTree(nullptr);
350  return fEntryStatus;
351  }
352 
353  if (fMostRecentTreeNumber != treeNumberBeforeLoadTree) {
354  // This can happen if someone switched trees behind us.
355  // Likely cause: a TChain::LoadTree() e.g. from TTree::Process().
356  // This means that "local" should be set!
357 
358  if (fTree->GetTreeNumber() != treeNumberBeforeLoadTree) {
359  // we have switched trees again, which means that "local" was not set!
360  // There are two entities switching trees which is bad.
361  R__ASSERT(!local && "Logic error - !local but tree number changed?");
362  Warning("SetEntryBase()",
363  "The current tree in the TChain %s has changed (e.g. by TTree::Process) "
364  "even though TTreeReader::SetEntry() was called, which switched the tree "
365  "again. Did you mean to call TTreeReader::SetLocalEntry()?",
366  fTree->GetName());
367  }
368  }
369 
370  if (fDirector->GetTree() != fTree->GetTree()
371  || fMostRecentTreeNumber != fTree->GetTreeNumber()) {
372  fDirector->SetTree(fTree->GetTree());
373  if (fProxiesSet) {
374  for (auto value: fValues) {
375  value->NotifyNewTree(fTree->GetTree());
376  }
377  }
378  }
379 
380  fMostRecentTreeNumber = fTree->GetTreeNumber();
381 
382  if (!fProxiesSet) {
383  // Tell readers we now have a tree
384  for (std::deque<ROOT::Internal::TTreeReaderValueBase*>::const_iterator
385  i = fValues.begin(); i != fValues.end(); ++i) { // Iterator end changes when parameterized arrays are read
386  (*i)->CreateProxy();
387 
388  if (!(*i)->GetProxy()){
390  return fEntryStatus;
391  }
392  }
393  // If at least one proxy was there and no error occurred, we assume the proxies to be set.
394  fProxiesSet = !fValues.empty();
395  }
396 
397  if (fEndEntry >= 0 && entry >= fEndEntry) {
399  return fEntryStatus;
400  }
401  fDirector->SetReadEntry(loadResult);
403  return fEntryStatus;
404 }
405 
406 ////////////////////////////////////////////////////////////////////////////////
407 /// Set (or update) the which tree to read from. `tree` can be
408 /// a TTree or a TChain.
409 
410 void TTreeReader::SetTree(TTree* tree, TEntryList* entryList /*= nullptr*/)
411 {
412  fTree = tree;
413  fEntryList = entryList;
414  fEntry = -1;
415 
416  if (fTree) {
417  ResetBit(kZombie);
418  if (fTree->InheritsFrom(TChain::Class())) {
420  }
421  }
422 
423  if (!fDirector) {
424  Initialize();
425  }
426  else {
428  fDirector->SetReadEntry(-1);
429  // Distinguish from end-of-chain case:
431  }
432 }
433 
434 ////////////////////////////////////////////////////////////////////////////////
435 /// Set (or update) the which tree to read from, passing the name of a tree in a
436 /// directory.
437 ///
438 /// \param keyname - name of the tree in `dir`
439 /// \param dir - the `TDirectory` to load `keyname` from (or gDirectory if `nullptr`)
440 /// \param entryList - the `TEntryList` to attach to the `TTreeReader`.
441 
442 void TTreeReader::SetTree(const char* keyname, TDirectory* dir, TEntryList* entryList /*= nullptr*/)
443 {
444  TTree* tree = nullptr;
445  if (!dir)
446  dir = gDirectory;
447  dir->GetObject(keyname, tree);
448  SetTree(tree, entryList);
449 }
450 
451 ////////////////////////////////////////////////////////////////////////////////
452 /// Add a value reader for this tree.
453 
455 {
456  if (fProxiesSet) {
457  Error("RegisterValueReader",
458  "Error registering reader for %s: TTreeReaderValue/Array objects must be created before the call to Next() / SetEntry() / SetLocalEntry(), or after TTreeReader::Restart()!",
459  reader->GetBranchName());
460  return false;
461  }
462  fValues.push_back(reader);
463  return true;
464 }
465 
466 ////////////////////////////////////////////////////////////////////////////////
467 /// Remove a value reader for this tree.
468 
470 {
471  std::deque<ROOT::Internal::TTreeReaderValueBase*>::iterator iReader
472  = std::find(fValues.begin(), fValues.end(), reader);
473  if (iReader == fValues.end()) {
474  Error("DeregisterValueReader", "Cannot find reader of type %s for branch %s", reader->GetDerivedTypeName(), reader->fBranchName.Data());
475  return;
476  }
477  fValues.erase(iReader);
478 }
the tree does not exist
Definition: TTreeReader.h:127
object ctor failed
Definition: TObject.h:72
long long Long64_t
Definition: RtypesCore.h:69
virtual Long64_t GetN() const
Definition: TEntryList.h:75
TTreeReader is a simple, robust and fast interface to read values from a TTree, TChain or TNtuple...
Definition: TTreeReader.h:43
void GetObject(const char *namecycle, T *&ptr)
Definition: TDirectory.h:137
Bool_t TestBit(UInt_t f) const
Definition: TObject.h:159
std::deque< ROOT::Internal::TTreeReaderValueBase * > fValues
readers that use our director
Definition: TTreeReader.h:264
#define R__ASSERT(e)
Definition: TError.h:96
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
Long64_t fEndEntry
The end of the entry loop.
Definition: TTreeReader.h:272
EEntryStatus SetEntryBase(Long64_t entry, Bool_t local)
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:687
Bool_t RegisterValueReader(ROOT::Internal::TTreeReaderValueBase *reader)
void Class()
Definition: Class.C:29
the tree entry number does not exist
Definition: TTreeReader.h:128
EEntryStatus fEntryStatus
status of most recent read request
Definition: TTreeReader.h:261
the tree had a TEntryList and we have warned about that
Definition: TTreeReader.h:256
TEntryList * fEntryList
entry list to be used
Definition: TTreeReader.h:260
ROOT::Internal::TBranchProxyDirector * fDirector
proxying director, owned
Definition: TTreeReader.h:263
Bool_t fProxiesSet
True if the proxies have been set, false otherwise.
Definition: TTreeReader.h:273
Long64_t GetEntries(Bool_t force) const
~TTreeReader()
Tell all value readers that the tree reader does not exist anymore.
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:873
virtual Long64_t GetEntry(Int_t index)
Return the number of the entry #index of this TEntryList in the TTree or TChain See also Next()...
Definition: TEntryList.cxx:657
EEntryStatus SetEntry(Long64_t entry)
Set the next entry (or index of the TEntryList if that is set).
Definition: TTreeReader.h:170
const Bool_t kFALSE
Definition: RtypesCore.h:92
TTreeReader()=default
void Restart()
Restart a Next() loop from entry 0 (of TEntryList index 0 of fEntryList is set).
#define ClassImp(name)
Definition: Rtypes.h:336
please use SetEntriesRange()!")
Definition: TTreeReader.h:188
Describe directory structure in memory.
Definition: TDirectory.h:34
TTree * fTree
tree that&#39;s read
Definition: TTreeReader.h:259
void Initialize()
Initialization of the director.
void DeregisterValueReader(ROOT::Internal::TTreeReaderValueBase *reader)
you should not use this method at all Int_t Int_t Double_t Double_t Double_t e
Definition: TRolke.cxx:630
problem reading dictionary info from tree
Definition: TTreeReader.h:131
Bool_t IsChain() const
Definition: TTreeReader.h:150
our tree is a chain
Definition: TTreeReader.h:255
Long64_t fEntry
Current (non-local) entry of fTree or of fEntryList if set.
Definition: TTreeReader.h:267
void MakeZombie()
Definition: TObject.h:49
virtual const char * GetDerivedTypeName() const =0
Definition: tree.py:1
#define gDirectory
Definition: TDirectory.h:211
void ResetBit(UInt_t f)
Definition: TObject.h:158
void SetTree(TTree *tree, TEntryList *entryList=nullptr)
Int_t fMostRecentTreeNumber
TTree::GetTreeNumber() of the most recent tree.
Definition: TTreeReader.h:262
A List of entry numbers in a TTree or TChain.
Definition: TEntryList.h:25
static constexpr Long64_t kMaxEntries
Definition: TTree.h:213
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:859
last entry loop has reached its end
Definition: TTreeReader.h:132