Logo ROOT  
Reference Guide
TTreeReader.h
Go to the documentation of this file.
1// @(#)root/tree:$Id$
2// Author: Axel Naumann, 2010-08-02
3
4/*************************************************************************
5 * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. *
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#ifndef ROOT_TTreeReader
13#define ROOT_TTreeReader
14
15
16////////////////////////////////////////////////////////////////////////////
17// //
18// TTreeReader //
19// //
20// A simple interface for reading trees or chains. //
21// //
22// //
23////////////////////////////////////////////////////////////////////////////
24
25#include "TTree.h"
26#include "TTreeReaderUtils.h"
27#include "TNotifyLink.h"
28
29#include <deque>
30#include <iterator>
31#include <unordered_map>
32
33class TDictionary;
34class TDirectory;
35class TFileCollection;
36
37namespace ROOT {
38namespace Internal {
39 class TBranchProxyDirector;
40}
41}
42
43class TTreeReader: public TObject {
44public:
45
46 ///\class TTreeReader::Iterator_t
47 /// Iterate through the entries of a TTree.
48 ///
49 /// This iterator drives the associated TTreeReader; its
50 /// dereferencing (and actually even the iteration) will
51 /// set the entry number represented by this iterator.
52 /// It does not really represent a data element; it simply
53 /// returns the entry number (or -1 once the end of the tree
54 /// is reached).
56 public std::iterator<std::input_iterator_tag, const Long64_t, Long64_t> {
57 private:
58 Long64_t fEntry; ///< Entry number of the tree referenced by this iterator; -1 is invalid.
59 TTreeReader* fReader; ///< The reader we select the entries on.
60
61 /// Whether the iterator points to a valid entry.
62 bool IsValid() const { return fEntry >= 0; }
63
64 public:
65 /// Default-initialize the iterator as "past the end".
67
68 /// Initialize the iterator with the reader it steers and a
69 /// tree entry number; -1 is invalid.
71 fEntry(entry), fReader(&reader) {}
72
73 /// Compare two iterators for equality.
74 bool operator==(const Iterator_t& lhs) const {
75 // From C++14: value initialized (past-end) it compare equal.
76 if (!IsValid() && !lhs.IsValid()) return true;
77 return fEntry == lhs.fEntry && fReader == lhs.fReader;
78 }
79
80 /// Compare two iterators for inequality.
81 bool operator!=(const Iterator_t& lhs) const {
82 return !(*this == lhs);
83 }
84
85 /// Increment the iterator (postfix i++).
87 Iterator_t ret = *this;
88 this->operator++();
89 return ret;
90 }
91
92 /// Increment the iterator (prefix ++i).
94 if (IsValid()) {
95 ++fEntry;
96 // Force validity check of new fEntry.
97 this->operator*();
98 // Don't set the old entry: op* will if needed, and
99 // in most cases it just adds a lot of spinning back
100 // and forth: in most cases teh sequence is ++i; *i.
101 }
102 return *this;
103 }
104
105 /// Set the entry number in the reader and return it.
107 if (IsValid()) {
108 // If we cannot access that entry, mark the iterator invalid.
110 fEntry = -1;
111 }
112 }
113 // There really is no data in this iterator; return the number.
114 return fEntry;
115 }
116
117 const Long64_t& operator*() const {
118 return **const_cast<Iterator_t*>(this);
119 }
120 };
121
123
125 kEntryValid = 0, ///< data read okay
126 kEntryNotLoaded, ///< no entry has been loaded yet
127 kEntryNoTree, ///< the tree does not exist
128 kEntryNotFound, ///< the tree entry number does not exist
129 kEntryChainSetupError, ///< problem in accessing a chain element, e.g. file without the tree
130 kEntryChainFileError, ///< problem in opening a chain's file
131 kEntryDictionaryError, ///< problem reading dictionary info from tree
132 kEntryBeyondEnd, ///< last entry loop has reached its end
133 kEntryBadReader, ///< One of the readers was not successfully initialized.
134 kEntryUnknownError ///< LoadTree return less than -4, likely a 'newer' error code.
135 };
136
138 kNoTree = 0, ///< default state, no TTree is connected (formerly 'Zombie' state)
139 kLoadTreeNone, ///< Notify has not been called yet.
140 kInternalLoadTree, ///< Notify/LoadTree was last called from SetEntryBase
141 kExternalLoadTree ///< User code called LoadTree directly.
142 };
143
144 static constexpr const char * const fgEntryStatusText[kEntryBeyondEnd + 1] = {
145 "valid entry",
146 "the tree does not exist",
147 "the tree entry number does not exist",
148 "cannot access chain element",
149 "problem in opening a chain's file",
150 "problem reading dictionary info from tree",
151 "last entry loop has reached its end"
152 };
153
154 TTreeReader();
155
156 TTreeReader(TTree* tree, TEntryList* entryList = nullptr);
157 TTreeReader(const char* keyname, TDirectory* dir, TEntryList* entryList = nullptr);
158 TTreeReader(const char *keyname, TEntryList *entryList = nullptr) : TTreeReader(keyname, nullptr, entryList) {}
159
160 ~TTreeReader();
161
162 void SetTree(TTree* tree, TEntryList* entryList = nullptr);
163 void SetTree(const char* keyname, TEntryList* entryList = nullptr) {
164 SetTree(keyname, nullptr, entryList);
165 }
166 void SetTree(const char* keyname, TDirectory* dir, TEntryList* entryList = nullptr);
167
168 Bool_t IsChain() const { return TestBit(kBitIsChain); }
169
171
172 TTree* GetTree() const { return fTree; }
173 TEntryList* GetEntryList() const { return fEntryList; }
174
175 ///\{ \name Entry setters
176
177 /// Move to the next entry (or index of the TEntryList if that is set).
178 ///
179 /// \return false if the previous entry was already the last entry. This allows
180 /// the function to be used in `while (reader.Next()) { ... }`
182 return SetEntry(GetCurrentEntry() + 1) == kEntryValid;
183 }
184
185 /// Set the next entry (or index of the TEntryList if that is set).
186 ///
187 /// \param entry If not TEntryList is set, the entry is a global entry (i.e.
188 /// not the entry number local to the chain's current tree).
189 /// \returns the `entry`'s read status, i.e. whether the entry is available.
191
192 /// Set the next local tree entry. If a TEntryList is set, this function is
193 /// equivalent to `SetEntry()`.
194 ///
195 /// \param entry Entry number of the TChain's current TTree. This is the
196 /// entry number passed for instance by `TSelector::Process(entry)`, i.e.
197 /// within `TSelector::Process()` always use `SetLocalEntry()` and not
198 /// `SetEntry()`!
199 /// \return the `entry`'s read status, i.e. whether the entry is available.
201
202 /// Set the begin and end entry numbers
203 ///
204 /// \param beginEntry The first entry that `Next()` will load.
205 /// \param endEntry The entry that `Next()` will return `kFALSE` on (i.e. not
206 /// load anymore).
207 EEntryStatus SetEntriesRange(Long64_t beginEntry, Long64_t endEntry);
208
209 /// Get the begin and end entry numbers
210 ///
211 /// \return a pair contained the begin and end entry numbers.
212 std::pair<Long64_t, Long64_t> GetEntriesRange() const { return std::make_pair(fBeginEntry, fEndEntry); }
213
214 /// Restart a Next() loop from entry 0 (of TEntryList index 0 of fEntryList is set).
215 void Restart();
216
217 ///\}
218
220
221 Long64_t GetEntries() const;
223
224 /// Returns the index of the current entry being read.
225 ///
226 /// If `IsChain()`, the returned index corresponds to the global entry number
227 /// (i.e. not the entry number local to the chain's current tree).
228 /// If `fEntryList`, the returned index corresponds to an index in the
229 /// TEntryList; to translate to the TChain's / TTree's entry number pass it
230 /// through `reader.GetEntryList()->GetEntry(reader.GetCurrentEntry())`.
231 Long64_t GetCurrentEntry() const { return fEntry; }
232
233 Bool_t Notify();
234
235 /// Return an iterator to the 0th TTree entry.
237 return Iterator_t(*this, 0);
238 }
239 /// Return an iterator beyond the last TTree entry.
240 Iterator_t end() const { return Iterator_t(); }
241
242protected:
243 using NamedProxies_t = std::unordered_map<std::string, std::unique_ptr<ROOT::Internal::TNamedBranchProxy>>;
244 void Initialize();
245 ROOT::Internal::TNamedBranchProxy* FindProxy(const char* branchname) const
246 {
247 const auto proxyIt = fProxies.find(branchname);
248 return fProxies.end() != proxyIt ? proxyIt->second.get() : nullptr;
249 }
250
252 {
253 auto bpName = p->GetName();
254#ifndef NDEBUG
255 if (fProxies.end() != fProxies.find(bpName)) {
256 std::string err = "A proxy with key " + std::string(bpName) + " was already stored!";
257 throw std::runtime_error(err);
258 }
259#endif
260
261 fProxies[bpName].reset(p);
262 }
263
266
268
270
271private:
272
273 std::string GetProxyKey(const char *branchname)
274 {
275 std::string key(branchname);
276 //key += reinterpret_cast<std::uintptr_t>(fTree);
277 return key;
278 }
279
281 kBitIsChain = BIT(14), ///< our tree is a chain
282 kBitHaveWarnedAboutEntryListAttachedToTTree = BIT(15), ///< the tree had a TEntryList and we have warned about that
283 kBitSetEntryBaseCallingLoadTree = BIT(16) ///< SetEntryBase is in the process of calling TChain/TTree::LoadTree.
284 };
285
286 TTree* fTree = nullptr; ///< tree that's read
287 TEntryList* fEntryList = nullptr; ///< entry list to be used
288 EEntryStatus fEntryStatus = kEntryNotLoaded; ///< status of most recent read request
289 ELoadTreeStatus fLoadTreeStatus = kNoTree; ///< Indicator on how LoadTree was called 'last' time.
290 TNotifyLink<TTreeReader> fNotify; // Callback object used by the TChain to update this proxy
291 ROOT::Internal::TBranchProxyDirector* fDirector = nullptr; ///< proxying director, owned
292 std::deque<ROOT::Internal::TFriendProxy*> fFriendProxies; ///< proxying for friend TTrees, owned
293 std::deque<ROOT::Internal::TTreeReaderValueBase*> fValues; ///< readers that use our director
294 NamedProxies_t fProxies; ///< attached ROOT::TNamedBranchProxies; owned
295
296 Long64_t fEntry = -1; ///< Current (non-local) entry of fTree or of fEntryList if set.
297
298 /// The end of the entry loop. When set (i.e. >= 0), it provides a way
299 /// to stop looping over the TTree when we reach a certain entry: Next()
300 /// returns kFALSE when GetCurrentEntry() reaches fEndEntry.
302 Long64_t fBeginEntry = 0LL; ///< This allows us to propagate the range to the TTreeCache
303 Bool_t fProxiesSet = kFALSE; ///< True if the proxies have been set, false otherwise
304 Bool_t fSetEntryBaseCallingLoadTree = kFALSE; ///< True if during the LoadTree execution triggered by SetEntryBase.
305
308
309 ClassDef(TTreeReader, 0); // A simple interface to read trees
310};
311
312#endif // defined TTreeReader
const Bool_t kFALSE
Definition: RtypesCore.h:90
bool Bool_t
Definition: RtypesCore.h:61
long long Long64_t
Definition: RtypesCore.h:71
const Bool_t kTRUE
Definition: RtypesCore.h:89
#define ClassDef(name, id)
Definition: Rtypes.h:322
#define BIT(n)
Definition: Rtypes.h:83
Base class of TTreeReaderArray.
Base class of TTreeReaderValue.
This class defines an abstract interface that must be implemented by all classes that contain diction...
Definition: TDictionary.h:166
Describe directory structure in memory.
Definition: TDirectory.h:40
A List of entry numbers in a TTree or TChain.
Definition: TEntryList.h:26
Class that contains a list of TFileInfo's and accumulated meta data information about its entries.
Mother of all ROOT objects.
Definition: TObject.h:37
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition: TObject.h:187
EStatusBits
Definition: TObject.h:57
Iterate through the entries of a TTree.
Definition: TTreeReader.h:56
Iterator_t & operator++()
Increment the iterator (prefix ++i).
Definition: TTreeReader.h:93
Iterator_t()
Default-initialize the iterator as "past the end".
Definition: TTreeReader.h:66
const Long64_t & operator*() const
Definition: TTreeReader.h:117
Long64_t fEntry
Entry number of the tree referenced by this iterator; -1 is invalid.
Definition: TTreeReader.h:58
Iterator_t(TTreeReader &reader, Long64_t entry)
Initialize the iterator with the reader it steers and a tree entry number; -1 is invalid.
Definition: TTreeReader.h:70
bool operator==(const Iterator_t &lhs) const
Compare two iterators for equality.
Definition: TTreeReader.h:74
TTreeReader * fReader
The reader we select the entries on.
Definition: TTreeReader.h:59
const Long64_t & operator*()
Set the entry number in the reader and return it.
Definition: TTreeReader.h:106
bool IsValid() const
Whether the iterator points to a valid entry.
Definition: TTreeReader.h:62
bool operator!=(const Iterator_t &lhs) const
Compare two iterators for inequality.
Definition: TTreeReader.h:81
Iterator_t operator++(int)
Increment the iterator (postfix i++).
Definition: TTreeReader.h:86
A simple, robust and fast interface to read values from ROOT columnar datasets such as TTree,...
Definition: TTreeReader.h:43
TTreeReader()
Default constructor. Call SetTree to connect to a TTree.
Bool_t fProxiesSet
True if the proxies have been set, false otherwise.
Definition: TTreeReader.h:303
ELoadTreeStatus fLoadTreeStatus
Indicator on how LoadTree was called 'last' time.
Definition: TTreeReader.h:289
void SetTree(const char *keyname, TEntryList *entryList=nullptr)
Definition: TTreeReader.h:163
Long64_t GetEntries() const
Returns the number of entries of the TEntryList if one is provided, else of the TTree / TChain,...
EEntryStatus fEntryStatus
status of most recent read request
Definition: TTreeReader.h:288
std::unordered_map< std::string, std::unique_ptr< ROOT::Internal::TNamedBranchProxy > > NamedProxies_t
Definition: TTreeReader.h:243
void SetTree(TTree *tree, TEntryList *entryList=nullptr)
Set (or update) the which tree to read from.
std::pair< Long64_t, Long64_t > GetEntriesRange() const
Get the begin and end entry numbers.
Definition: TTreeReader.h:212
TNotifyLink< TTreeReader > fNotify
Definition: TTreeReader.h:290
Bool_t SetProxies()
Tell readers we now have a tree.
Bool_t IsChain() const
Definition: TTreeReader.h:168
@ kEntryNotFound
the tree entry number does not exist
Definition: TTreeReader.h:128
@ kEntryUnknownError
LoadTree return less than -4, likely a 'newer' error code.
Definition: TTreeReader.h:134
@ kEntryDictionaryError
problem reading dictionary info from tree
Definition: TTreeReader.h:131
@ kEntryChainSetupError
problem in accessing a chain element, e.g. file without the tree
Definition: TTreeReader.h:129
@ kEntryNotLoaded
no entry has been loaded yet
Definition: TTreeReader.h:126
@ kEntryBeyondEnd
last entry loop has reached its end
Definition: TTreeReader.h:132
@ kEntryChainFileError
problem in opening a chain's file
Definition: TTreeReader.h:130
@ kEntryNoTree
the tree does not exist
Definition: TTreeReader.h:127
@ kEntryBadReader
One of the readers was not successfully initialized.
Definition: TTreeReader.h:133
@ kEntryValid
data read okay
Definition: TTreeReader.h:125
std::deque< ROOT::Internal::TTreeReaderValueBase * > fValues
readers that use our director
Definition: TTreeReader.h:293
Bool_t Notify()
Callback from TChain and TTree's LoadTree.
TTree * fTree
tree that's read
Definition: TTreeReader.h:286
ROOT::Internal::TBranchProxyDirector * fDirector
proxying director, owned
Definition: TTreeReader.h:291
TTree * GetTree() const
Definition: TTreeReader.h:172
Iterator_t end() const
Return an iterator beyond the last TTree entry.
Definition: TTreeReader.h:240
~TTreeReader()
Tell all value readers that the tree reader does not exist anymore.
EEntryStatus SetEntriesRange(Long64_t beginEntry, Long64_t endEntry)
Set the begin and end entry numbers.
std::deque< ROOT::Internal::TFriendProxy * > fFriendProxies
proxying for friend TTrees, owned
Definition: TTreeReader.h:292
std::string GetProxyKey(const char *branchname)
Definition: TTreeReader.h:273
Bool_t fSetEntryBaseCallingLoadTree
True if during the LoadTree execution triggered by SetEntryBase.
Definition: TTreeReader.h:304
EEntryStatus GetEntryStatus() const
Definition: TTreeReader.h:219
@ kInternalLoadTree
Notify/LoadTree was last called from SetEntryBase.
Definition: TTreeReader.h:140
@ kNoTree
default state, no TTree is connected (formerly 'Zombie' state)
Definition: TTreeReader.h:138
@ kExternalLoadTree
User code called LoadTree directly.
Definition: TTreeReader.h:141
@ kLoadTreeNone
Notify has not been called yet.
Definition: TTreeReader.h:139
static constexpr const char *const fgEntryStatusText[kEntryBeyondEnd+1]
Definition: TTreeReader.h:144
void Initialize()
Initialization of the director.
void Restart()
Restart a Next() loop from entry 0 (of TEntryList index 0 of fEntryList is set).
EEntryStatus SetEntryBase(Long64_t entry, Bool_t local)
Load an entry into the tree, return the status of the read.
TEntryList * fEntryList
entry list to be used
Definition: TTreeReader.h:287
Long64_t fEntry
Current (non-local) entry of fTree or of fEntryList if set.
Definition: TTreeReader.h:296
Bool_t RegisterValueReader(ROOT::Internal::TTreeReaderValueBase *reader)
Add a value reader for this tree.
Long64_t fBeginEntry
This allows us to propagate the range to the TTreeCache.
Definition: TTreeReader.h:302
void AddProxy(ROOT::Internal::TNamedBranchProxy *p)
Definition: TTreeReader.h:251
void DeregisterValueReader(ROOT::Internal::TTreeReaderValueBase *reader)
Remove a value reader for this tree.
@ kBitSetEntryBaseCallingLoadTree
SetEntryBase is in the process of calling TChain/TTree::LoadTree.
Definition: TTreeReader.h:283
@ kBitHaveWarnedAboutEntryListAttachedToTTree
the tree had a TEntryList and we have warned about that
Definition: TTreeReader.h:282
@ kBitIsChain
our tree is a chain
Definition: TTreeReader.h:281
EEntryStatus SetLocalEntry(Long64_t entry)
Set the next local tree entry.
Definition: TTreeReader.h:200
NamedProxies_t fProxies
attached ROOT::TNamedBranchProxies; owned
Definition: TTreeReader.h:294
TEntryList * GetEntryList() const
Definition: TTreeReader.h:173
Bool_t IsInvalid() const
Definition: TTreeReader.h:170
Iterator_t begin()
Return an iterator to the 0th TTree entry.
Definition: TTreeReader.h:236
TTreeReader(const char *keyname, TEntryList *entryList=nullptr)
Definition: TTreeReader.h:158
Long64_t fEndEntry
The end of the entry loop.
Definition: TTreeReader.h:301
Iterator_t iterator
Definition: TTreeReader.h:122
EEntryStatus SetEntry(Long64_t entry)
Set the next entry (or index of the TEntryList if that is set).
Definition: TTreeReader.h:190
Bool_t Next()
Move to the next entry (or index of the TEntryList if that is set).
Definition: TTreeReader.h:181
ROOT::Internal::TNamedBranchProxy * FindProxy(const char *branchname) const
Definition: TTreeReader.h:245
Long64_t GetCurrentEntry() const
Returns the index of the current entry being read.
Definition: TTreeReader.h:231
A TTree represents a columnar dataset.
Definition: TTree.h:78
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
Definition: StringConv.hxx:21
Definition: tree.py:1