Logo ROOT   6.10/00
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 "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  fProxies.SetOwner();
207 }
208 
209 ////////////////////////////////////////////////////////////////////////////////
210 /// Initialization of the director.
211 
213 {
214  fEntry = -1;
215  if (!fTree) {
216  MakeZombie();
219  return;
220  }
221 
222  ResetBit(kZombie);
223  if (fTree->InheritsFrom(TChain::Class())) {
225  }
227 }
228 
229 ////////////////////////////////////////////////////////////////////////////////
230 /// Set the range of entries to be loaded by `Next()`; end will not be loaded.
231 ///
232 /// If end <= begin, `end` is ignored (set to `-1`) and only `begin` is used.
233 /// Example:
234 ///
235 /// ~~~ {.cpp}
236 /// reader.SetEntriesRange(3, 5);
237 /// while (reader.Next()) {
238 /// // Will load entries 3 and 4.
239 /// }
240 /// ~~~
241 ///
242 /// \param beginEntry The first entry to be loaded by `Next()`.
243 /// \param endEntry The entry where `Next()` will return kFALSE, not loading it.
244 
246 {
247  if (beginEntry < 0)
248  return kEntryNotFound;
249  // Complain if the entries number is larger than the tree's / chain's / entry
250  // list's number of entries, unless it's a TChain and "max entries" is
251  // uninitialized (i.e. TTree::kMaxEntries).
252  if (beginEntry >= GetEntries(false) && !(IsChain() && GetEntries(false) == TTree::kMaxEntries))
253  return kEntryNotFound;
254 
255  if (endEntry > beginEntry)
256  fEndEntry = endEntry;
257  else
258  fEndEntry = -1;
259  if (beginEntry - 1 < 0)
260  Restart();
261  else
262  SetEntry(beginEntry - 1);
263  return kEntryValid;
264 }
265 
267  fDirector->SetTree(nullptr);
268  fDirector->SetReadEntry(-1);
269  fProxiesSet = false; // we might get more value readers, meaning new proxies.
270  fEntry = -1;
271 }
272 
273 ////////////////////////////////////////////////////////////////////////////////
274 /// Returns the number of entries of the TEntryList if one is provided, else
275 /// of the TTree / TChain, independent of a range set by SetEntriesRange().
276 ///
277 /// \param force If `IsChain()` and `force`, determines whether all TFiles of
278 /// this TChain should be opened to determine the exact number of entries
279 /// of the TChain. If `!IsChain()`, `force` is ignored.
280 
282  if (fEntryList)
283  return fEntryList->GetN();
284  if (!fTree)
285  return -1;
286  if (force)
287  return fTree->GetEntries();
288  return fTree->GetEntriesFast();
289 }
290 
291 
292 
293 ////////////////////////////////////////////////////////////////////////////////
294 /// Load an entry into the tree, return the status of the read.
295 /// For chains, entry is the global (i.e. not tree-local) entry number, unless
296 /// `local` is `true`, in which case `entry` specifies the entry number within
297 /// the current tree. This is needed for instance for TSelector::Process().
298 
300 {
301  if (!fTree || !fDirector) {
303  fEntry = -1;
304  return fEntryStatus;
305  }
306 
307  if (fTree->GetEntryList() && !TestBit(kBitHaveWarnedAboutEntryListAttachedToTTree)) {
308  Warning("SetEntryBase()",
309  "The TTree / TChain has an associated TEntryList. "
310  "TTreeReader ignores TEntryLists unless you construct the TTreeReader passing a TEntryList.");
312  }
313 
314  fEntry = entry;
315 
316  Long64_t entryAfterList = entry;
317  if (fEntryList) {
318  if (entry >= fEntryList->GetN()) {
319  // Passed the end of the chain, Restart() was not called:
320  // don't try to load entries anymore. Can happen in these cases:
321  // while (tr.Next()) {something()};
322  // while (tr.Next()) {somethingelse()}; // should not be calling somethingelse().
324  return fEntryStatus;
325  }
326  if (entry >= 0) entryAfterList = fEntryList->GetEntry(entry);
327  if (local && IsChain()) {
328  // Must translate the entry list's entry to the current TTree's entry number.
329  local = kFALSE;
330  }
331  }
332 
333  if (fProxiesSet && fDirector && fDirector->GetReadEntry() == -1
334  && fMostRecentTreeNumber != -1) {
335  // Passed the end of the chain, Restart() was not called:
336  // don't try to load entries anymore. Can happen in these cases:
337  // while (tr.Next()) {something()};
338  // while (tr.Next()) {somethingelse()}; // should not be calling somethingelse().
340  return fEntryStatus;
341  }
342 
343  Int_t treeNumberBeforeLoadTree = fTree->GetTreeNumber();
344 
345  TTree* treeToCallLoadOn = local ? fTree->GetTree() : fTree;
346  Long64_t loadResult = treeToCallLoadOn->LoadTree(entryAfterList);
347 
348  if (loadResult == -2) {
349  fDirector->SetTree(nullptr);
351  return fEntryStatus;
352  }
353 
354  if (fMostRecentTreeNumber != treeNumberBeforeLoadTree) {
355  // This can happen if someone switched trees behind us.
356  // Likely cause: a TChain::LoadTree() e.g. from TTree::Process().
357  // This means that "local" should be set!
358 
359  if (fTree->GetTreeNumber() != treeNumberBeforeLoadTree) {
360  // we have switched trees again, which means that "local" was not set!
361  // There are two entities switching trees which is bad.
362  R__ASSERT(!local && "Logic error - !local but tree number changed?");
363  Warning("SetEntryBase()",
364  "The current tree in the TChain %s has changed (e.g. by TTree::Process) "
365  "even though TTreeReader::SetEntry() was called, which switched the tree "
366  "again. Did you mean to call TTreeReader::SetLocalEntry()?",
367  fTree->GetName());
368  }
369  }
370 
371  if (fDirector->GetTree() != fTree->GetTree()
372  || fMostRecentTreeNumber != fTree->GetTreeNumber()) {
373  fDirector->SetTree(fTree->GetTree());
374  if (fProxiesSet) {
375  for (auto value: fValues) {
376  value->NotifyNewTree(fTree->GetTree());
377  }
378  }
379  }
380 
381  fMostRecentTreeNumber = fTree->GetTreeNumber();
382 
383  if (!fProxiesSet) {
384  // Tell readers we now have a tree
385  for (std::deque<ROOT::Internal::TTreeReaderValueBase*>::const_iterator
386  i = fValues.begin(); i != fValues.end(); ++i) { // Iterator end changes when parameterized arrays are read
387  (*i)->CreateProxy();
388 
389  if (!(*i)->GetProxy()){
391  return fEntryStatus;
392  }
393  }
394  // If at least one proxy was there and no error occurred, we assume the proxies to be set.
395  fProxiesSet = !fValues.empty();
396  }
397 
398  if (fEndEntry >= 0 && entry >= fEndEntry) {
400  return fEntryStatus;
401  }
402  fDirector->SetReadEntry(loadResult);
404  return fEntryStatus;
405 }
406 
407 ////////////////////////////////////////////////////////////////////////////////
408 /// Set (or update) the which tree to read from. `tree` can be
409 /// a TTree or a TChain.
410 
411 void TTreeReader::SetTree(TTree* tree, TEntryList* entryList /*= nullptr*/)
412 {
413  fTree = tree;
414  fEntryList = entryList;
415  fEntry = -1;
416 
417  if (fTree) {
418  ResetBit(kZombie);
419  if (fTree->InheritsFrom(TChain::Class())) {
421  }
422  }
423 
424  if (!fDirector) {
425  Initialize();
426  }
427  else {
429  fDirector->SetReadEntry(-1);
430  // Distinguish from end-of-chain case:
432  }
433 }
434 
435 ////////////////////////////////////////////////////////////////////////////////
436 /// Set (or update) the which tree to read from, passing the name of a tree in a
437 /// directory.
438 ///
439 /// \param keyname - name of the tree in `dir`
440 /// \param dir - the `TDirectory` to load `keyname` from (or gDirectory if `nullptr`)
441 /// \param entryList - the `TEntryList` to attach to the `TTreeReader`.
442 
443 void TTreeReader::SetTree(const char* keyname, TDirectory* dir, TEntryList* entryList /*= nullptr*/)
444 {
445  TTree* tree = nullptr;
446  if (!dir)
447  dir = gDirectory;
448  dir->GetObject(keyname, tree);
449  SetTree(tree, entryList);
450 }
451 
452 ////////////////////////////////////////////////////////////////////////////////
453 /// Add a value reader for this tree.
454 
456 {
457  if (fProxiesSet) {
458  Error("RegisterValueReader",
459  "Error registering reader for %s: TTreeReaderValue/Array objects must be created before the call to Next() / SetEntry() / SetLocalEntry(), or after TTreeReader::Restart()!",
460  reader->GetBranchName());
461  return false;
462  }
463  fValues.push_back(reader);
464  return true;
465 }
466 
467 ////////////////////////////////////////////////////////////////////////////////
468 /// Remove a value reader for this tree.
469 
471 {
472  std::deque<ROOT::Internal::TTreeReaderValueBase*>::iterator iReader
473  = std::find(fValues.begin(), fValues.end(), reader);
474  if (iReader == fValues.end()) {
475  Error("DeregisterValueReader", "Cannot find reader of type %s for branch %s", reader->GetDerivedTypeName(), reader->fBranchName.Data());
476  return;
477  }
478  fValues.erase(iReader);
479 }
the tree does not exist
Definition: TTreeReader.h:126
object ctor failed
Definition: TObject.h:72
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:42
void GetObject(const char *namecycle, T *&ptr)
Definition: TDirectory.h:137
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
readers that use our director
Definition: TTreeReader.h:240
#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:248
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:687
THashTable fProxies
attached ROOT::TNamedBranchProxies; owned
Definition: TTreeReader.h:241
Bool_t RegisterValueReader(ROOT::Internal::TTreeReaderValueBase *reader)
Add a value reader for this tree.
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
the tree entry number does not exist
Definition: TTreeReader.h:127
Long64_t GetEntries(Bool_t force) const
Returns the number of entries of the TEntryList if one is provided, else of the TTree / TChain...
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:873
EEntryStatus fEntryStatus
status of most recent read request
Definition: TTreeReader.h:237
the tree had a TEntryList and we have warned about that
Definition: TTreeReader.h:232
void Error(const char *location, const char *msgfmt,...)
TEntryList * fEntryList
entry list to be used
Definition: TTreeReader.h:236
ROOT::Internal::TBranchProxyDirector * fDirector
proxying director, owned
Definition: TTreeReader.h:239
Bool_t IsChain() const
Definition: TTreeReader.h:149
void Initialize(Bool_t useTMVAStyle=kTRUE)
Definition: tmvaglob.cxx:176
Bool_t fProxiesSet
True if the proxies have been set, false otherwise.
Definition: TTreeReader.h:249
Bool_t TestBit(UInt_t f) const
Definition: TObject.h:159
~TTreeReader()
Tell all value readers that the tree reader does not exist anymore.
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:169
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:187
Describe directory structure in memory.
Definition: TDirectory.h:34
TTree * fTree
tree that&#39;s read
Definition: TTreeReader.h:235
void Initialize()
Initialization of the director.
void DeregisterValueReader(ROOT::Internal::TTreeReaderValueBase *reader)
Remove a value reader for this tree.
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:130
virtual Long64_t GetN() const
Definition: TEntryList.h:75
our tree is a chain
Definition: TTreeReader.h:231
Long64_t fEntry
Current (non-local) entry of fTree or of fEntryList if set.
Definition: TTreeReader.h:243
void MakeZombie()
Definition: TObject.h:49
virtual const char * GetDerivedTypeName() const =0
#define gDirectory
Definition: TDirectory.h:211
void ResetBit(UInt_t f)
Definition: TObject.h:158
void SetTree(TTree *tree, TEntryList *entryList=nullptr)
Set (or update) the which tree to read from.
Int_t fMostRecentTreeNumber
TTree::GetTreeNumber() of the most recent tree.
Definition: TTreeReader.h:238
A List of entry numbers in a TTree or TChain.
Definition: TEntryList.h:25
static constexpr Long64_t kMaxEntries
Definition: TTree.h:213
last entry loop has reached its end
Definition: TTreeReader.h:131
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:859