Logo ROOT   6.08/02
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  fMostRecentTreeNumber(-1),
203  fDirector(0),
204  fLastEntry(-1),
205  fProxiesSet(kFALSE)
206 {
207  if (!fTree) {
208  Error("TTreeReader", "TTree is NULL!");
209  } else {
210  Initialize();
211  }
212 }
213 
214 ////////////////////////////////////////////////////////////////////////////////
215 /// Access data from the tree called keyname in the directory (e.g. TFile)
216 /// dir, or the current directory if dir is NULL. If keyname cannot be
217 /// found, or if it is not a TTree, IsZombie() will return true.
218 
219 TTreeReader::TTreeReader(const char* keyname, TDirectory* dir /*= NULL*/):
220  fTree(0),
221  fDirectory(dir),
222  fEntryStatus(kEntryNotLoaded),
223  fMostRecentTreeNumber(-1),
224  fDirector(0),
225  fLastEntry(-1),
226  fProxiesSet(kFALSE)
227 {
229  fDirectory->GetObject(keyname, fTree);
230  Initialize();
231 }
232 
233 ////////////////////////////////////////////////////////////////////////////////
234 /// Tell all value readers that the tree reader does not exist anymore.
235 
237 {
238  for (std::deque<ROOT::Internal::TTreeReaderValueBase*>::const_iterator
239  i = fValues.begin(), e = fValues.end(); i != e; ++i) {
240  (*i)->MarkTreeReaderUnavailable();
241  }
242  delete fDirector;
243  fProxies.SetOwner();
244 }
245 
246 ////////////////////////////////////////////////////////////////////////////////
247 /// Initialization of the director.
248 
250 {
251  if (!fTree) {
252  MakeZombie();
255  } else {
256  ResetBit(kZombie);
257  if (fTree->InheritsFrom(TChain::Class())) {
259  }
261  }
262 }
263 
264 ////////////////////////////////////////////////////////////////////////////////
265 /// Set the range of entries to be processed. This call is usually followed by
266 /// an iteration of the range using TTreeReader::Next(), which will visit the
267 /// the entries from `first` to `last - 1`.
268 /// If last > first, this call is equivalent to
269 /// `SetEntry(first - 1); SetLastEntry(last);`. Otherwise `last` is ignored and
270 /// only `first` is set.
271 /// \return the EEntryStatus that would be returned by SetEntry(first - 1)
272 
274 {
275  if(last > first)
276  fLastEntry = last;
277  else
278  fLastEntry = -1;
279  return SetEntry(first - 1);
280 }
281 
282 ////////////////////////////////////////////////////////////////////////////////
283 /// Restart a Next() loop from the first entry.
284 
286  fDirector->SetTree(nullptr);
287  fDirector->SetReadEntry(-1);
288  fProxiesSet = false; // we might get more value readers, meaning new proxies.
289 }
290 
291 ////////////////////////////////////////////////////////////////////////////////
292 /// Returns the index of the current entry being read
293 
295  if (!fDirector) return -1;
296  Long64_t currentTreeEntry = fDirector->GetReadEntry();
297  if (TestBit(kBitIsChain) && currentTreeEntry >= 0) {
298  return ((TChain*)fTree)->GetChainEntryNumber(currentTreeEntry);
299  }
300  return currentTreeEntry;
301 }
302 
303 ////////////////////////////////////////////////////////////////////////////////
304 /// Load an entry into the tree, return the status of the read.
305 /// For chains, entry is the global (i.e. not tree-local) entry number, unless
306 /// `local` is `true`, in which case `entry` specifies the entry number within
307 /// the current tree. This is needed for instance for TSelector::Process().
308 
310 {
311  if (!fTree || !fDirector) {
313  return fEntryStatus;
314  }
315 
316  if (fProxiesSet && fDirector && fDirector->GetReadEntry() == -1
317  && fMostRecentTreeNumber != -1) {
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 
326  Int_t treeNumberBeforeLoadTree = fTree->GetTreeNumber();
327 
328  TTree* treeToCallLoadOn = local ? fTree->GetTree() : fTree;
329  Long64_t loadResult = treeToCallLoadOn->LoadTree(entry);
330 
331  if (loadResult == -2) {
332  fDirector->SetTree(nullptr);
334  return fEntryStatus;
335  }
336 
337  if (fMostRecentTreeNumber != treeNumberBeforeLoadTree) {
338  // This can happen if someone switched trees behind us.
339  // Likely cause: a TChain::LoadTree() e.g. from TTree::Process().
340  // This means that "local" should be set!
341 
342  if (fTree->GetTreeNumber() != treeNumberBeforeLoadTree) {
343  // we have switched trees again, which means that "local" was not set!
344  // There are two entities switching trees which is bad.
345  R__ASSERT(!local && "Logic error - !local but tree number changed?");
346  Warning("SetEntryBase()",
347  "The current tree in the TChain %s has changed (e.g. by TTree::Process) "
348  "even though TTreeReader::SetEntry() was called, which switched the tree "
349  "again. Did you mean to call TTreeReader::SetLocalEntry()?",
350  fTree->GetName());
351  }
352  }
353 
354  if (fDirector->GetTree() != fTree->GetTree()
355  || fMostRecentTreeNumber != fTree->GetTreeNumber()) {
356  fDirector->SetTree(fTree->GetTree());
357  if (fProxiesSet) {
358  for (auto value: fValues) {
359  value->NotifyNewTree(fTree->GetTree());
360  }
361  }
362  }
363 
364  fMostRecentTreeNumber = fTree->GetTreeNumber();
365 
366  if (!fProxiesSet) {
367  // Tell readers we now have a tree
368  for (std::deque<ROOT::Internal::TTreeReaderValueBase*>::const_iterator
369  i = fValues.begin(); i != fValues.end(); ++i) { // Iterator end changes when parameterized arrays are read
370  (*i)->CreateProxy();
371 
372  if (!(*i)->GetProxy()){
374  return fEntryStatus;
375  }
376  }
377  // If at least one proxy was there and no error occurred, we assume the proxies to be set.
378  fProxiesSet = !fValues.empty();
379  }
380 
381  if (fLastEntry >= 0 && entry >= fLastEntry) {
383  return fEntryStatus;
384  }
385  fDirector->SetReadEntry(loadResult);
387  return fEntryStatus;
388 }
389 
390 ////////////////////////////////////////////////////////////////////////////////
391 /// Set (or update) the which tree to reader from. tree can be
392 /// a TTree or a TChain.
393 
395 {
396  fTree = tree;
397  if (fTree) {
398  ResetBit(kZombie);
399  if (fTree->InheritsFrom(TChain::Class())) {
401  }
402  }
403 
404  if (!fDirector) {
405  Initialize();
406  }
407  else {
409  fDirector->SetReadEntry(-1);
410  // Distinguish from end-of-chain case:
412  }
413 }
414 
415 ////////////////////////////////////////////////////////////////////////////////
416 /// Add a value reader for this tree.
417 
419 {
420  if (fProxiesSet) {
421  Error("RegisterValueReader",
422  "Error registering reader for %s: TTreeReaderValue/Array objects must be created before the call to Next() / SetEntry() / SetLocalEntry(), or after TTreeReader::Restart()!",
423  reader->GetBranchName());
424  return false;
425  }
426  fValues.push_back(reader);
427  return true;
428 }
429 
430 ////////////////////////////////////////////////////////////////////////////////
431 /// Remove a value reader for this tree.
432 
434 {
435  std::deque<ROOT::Internal::TTreeReaderValueBase*>::iterator iReader
436  = std::find(fValues.begin(), fValues.end(), reader);
437  if (iReader == fValues.end()) {
438  Error("DeregisterValueReader", "Cannot find reader of type %s for branch %s", reader->GetDerivedTypeName(), reader->fBranchName.Data());
439  return;
440  }
441  fValues.erase(iReader);
442 }
the tree does not exist
Definition: TTreeReader.h:132
object ctor failed
Definition: TObject.h:70
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
last entry was reached
Definition: TTreeReader.h:137
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
readers that use our director
Definition: TTreeReader.h:202
#define R__ASSERT(e)
Definition: TError.h:98
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
const Bool_t kFALSE
Definition: Rtypes.h:92
const char * Class
Definition: TXMLSetup.cxx:64
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:739
THashTable fProxies
attached ROOT::TNamedBranchProxies; owned
Definition: TTreeReader.h:203
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.
the tree entry number does not exist
Definition: TTreeReader.h:133
Long64_t GetCurrentEntry() const
Returns the index of the current entry being read.
TDirectory * fDirectory
directory (or current file for chains)
Definition: TTreeReader.h:198
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:925
EEntryStatus fEntryStatus
status of most recent read request
Definition: TTreeReader.h:199
void Error(const char *location, const char *msgfmt,...)
Long64_t fLastEntry
The last entry to be processed.
Definition: TTreeReader.h:208
ROOT::Internal::TBranchProxyDirector * fDirector
proxying director, owned
Definition: TTreeReader.h:201
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:209
Bool_t TestBit(UInt_t f) const
Definition: TObject.h:157
~TTreeReader()
Tell all value readers that the tree reader does not exist anymore.
EEntryStatus SetEntry(Long64_t entry)
Definition: TTreeReader.h:162
void Restart()
Restart a Next() loop from the first entry.
#define ClassImp(name)
Definition: Rtypes.h:279
Describe directory structure in memory.
Definition: TDirectory.h:44
TTree * fTree
tree that&#39;s read
Definition: TTreeReader.h:197
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:136
our tree is a chain
Definition: TTreeReader.h:194
void MakeZombie()
Definition: TObject.h:47
virtual const char * GetDerivedTypeName() const =0
A chain is a collection of files containg TTree objects.
Definition: TChain.h:35
#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:156
Int_t fMostRecentTreeNumber
TTree::GetTreeNumber() of the most recent tree.
Definition: TTreeReader.h:200
EEntryStatus SetEntriesRange(Long64_t first, Long64_t last)
Set the range of entries to be processed.
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:911