Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RNTupleDS.hxx
Go to the documentation of this file.
1/// \file RNTupleDS.hxx
2/// \author Jakob Blomer <jblomer@cern.ch>
3/// \author Enrico Guiraud <enrico.guiraud@cern.ch>
4/// \date 2018-10-04
5/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
6/// is welcome!
7
8/*************************************************************************
9 * Copyright (C) 1995-2025, Rene Brun and Fons Rademakers. *
10 * All rights reserved. *
11 * *
12 * For the licensing terms see $ROOTSYS/LICENSE. *
13 * For the list of contributors see $ROOTSYS/README/CREDITS. *
14 *************************************************************************/
15
16#ifndef ROOT_RNTupleDS
17#define ROOT_RNTupleDS
18
19#include <ROOT/RDataSource.hxx>
21#include <ROOT/RNTupleTypes.hxx>
22#include <string_view>
23
24#include <condition_variable>
25#include <cstdint>
26#include <memory>
27#include <mutex>
28#include <optional>
29#include <string>
30#include <thread>
31#include <vector>
32#include <unordered_map>
33
34// Follow RDF namespace convention
35namespace ROOT {
36class RDataFrame;
37}
38namespace ROOT::Internal::RDF {
39/**
40 * \brief Internal overload of the function that allows passing a range of entries
41 *
42 * The event range will be respected when processing this RNTuple. It is assumed
43 * that processing happens within one thread only.
44 */
45ROOT::RDataFrame FromRNTuple(std::string_view ntupleName, const std::vector<std::string> &fileNames,
46 const std::pair<ULong64_t, ULong64_t> &range);
47/**
48 * \brief Retrieves the cluster boundaries and the number of entries for the input RNTuple
49 *
50 * \param[in] ntupleName The name of the RNTuple dataset
51 * \param[in] location The location of the RNTuple dataset (e.g. a path to a file)
52 *
53 * \note This function is a helper for the Python side to avoid having to deal
54 * with the shared descriptor guard.
55 */
56std::pair<std::vector<ROOT::Internal::RNTupleClusterBoundaries>, ROOT::NTupleSize_t>
57GetClustersAndEntries(std::string_view ntupleName, std::string_view location);
58} // namespace ROOT::Internal::RDF
59
60namespace ROOT {
61class RFieldBase;
62class RDataFrame;
63class RNTuple;
64} // namespace ROOT
65namespace ROOT::Detail::RDF {
66class RNodeBase;
67}
68namespace ROOT::RDF {
69template <typename T>
70class RInterface;
71}
72namespace ROOT::Internal::RDF {
73class RNTupleColumnReader;
74std::vector<std::pair<std::uint64_t, std::uint64_t>>
76}
77namespace ROOT::Internal {
78class RPageSource;
79}
80
81namespace ROOT::RDF {
84
85 /// The PrepareNextRanges() method populates the fNextRanges list with REntryRangeDS records.
86 /// The GetEntryRanges() swaps fNextRanges and fCurrentRanges and uses the list of
87 /// REntryRangeDS records to return the list of ranges ready to use by the RDF loop manager.
89 std::unique_ptr<ROOT::Internal::RPageSource> fSource;
90 ULong64_t fFirstEntry = 0; ///< First entry index in fSource
91 /// End entry index in fSource, e.g. the number of entries in the range is fLastEntry - fFirstEntry
93 std::string_view fFileName; ///< Storage location of the current RNTuple
94 };
95
96 /// A clone of the first pages source's descriptor.
98
99 /// The data source may be constructed with an ntuple name and a list of files
100 std::string fNTupleName;
101 std::vector<std::string> fFileNames;
102 /// The staging area is relevant for chains of files, i.e. when fFileNames is not empty. In this case,
103 /// files are opened in the background in batches of size `fNSlots` and kept in the staging area.
104 /// The first file (chains or no chains) is always opened on construction in order to process the schema.
105 /// For all subsequent files, the corresponding page sources in the staging area only executed `LoadStructure()`,
106 /// i.e. they should have a compressed buffer of the meta-data available.
107 /// Concretely:
108 /// 1. We open the first file on construction to read the schema and then move the corresponding page source
109 /// in the staging area.
110 /// 2. On `Initialize()`, we start the I/O background thread, which in turn opens the first batch of files.
111 /// 3. At the beginning of `GetEntryRanges()`, we
112 /// a) wait for the I/O thread to finish,
113 /// b) call `PrepareNextRanges()` in the main thread to move the page sources from the staging area
114 /// into `fNextRanges`; this will also call `Attach()` on the page sources (i.e., deserialize the meta-data),
115 /// and
116 /// c) trigger staging of the next batch of files in the I/O background thread.
117 /// 4. On `Finalize()`, the I/O background thread is stopped.
118 std::vector<std::unique_ptr<ROOT::Internal::RPageSource>> fStagingArea;
119 std::size_t fNextFileIndex = 0; ///< Index into fFileNames to the next file to process
120
121 /// We prepare a prototype field for every column. If a column reader is actually requested
122 /// in GetColumnReaders(), we move a clone of the field into a new column reader for RDataFrame.
123 /// Only the clone connects to the backing page store and acquires I/O resources.
124 /// The field IDs are set in the context of the first source and used as keys in fFieldId2QualifiedName.
125 std::vector<std::unique_ptr<ROOT::RFieldBase>> fProtoFields;
126 /// Columns may be requested with types other than with which they were initially added as proto fields. For example,
127 /// a column with a `ROOT::RVec<float>` proto field may instead be requested as a `std::vector<float>`. In case this
128 /// happens, we create an alternative proto field and store it here, with the original index in `fProtoFields` as
129 /// key. A single column can have more than one alternative proto fields.
130 std::unordered_map<std::size_t, std::vector<std::unique_ptr<ROOT::RFieldBase>>> fAlternativeProtoFields;
131 /// Connects the IDs of active proto fields and their subfields to their fully qualified name (a.b.c.d).
132 /// This enables the column reader to rewire the field IDs when the file changes (chain),
133 /// using the fully qualified name as a search key in the descriptor of the other page sources.
134 std::unordered_map<ROOT::DescriptorId_t, std::string> fFieldId2QualifiedName;
135 std::vector<std::string> fColumnNames;
136 std::vector<std::string> fColumnTypes;
137 std::vector<std::string> fTopLevelFieldNames;
138 /// List of column readers returned by GetColumnReaders() organized by slot. Used to reconnect readers
139 /// to new page sources when the files in the chain change.
140 std::vector<std::vector<ROOT::Internal::RDF::RNTupleColumnReader *>> fActiveColumnReaders;
141
142 ULong64_t fSeenEntriesNoGlobalRange = 0; ///< The number of entries seen so far in GetEntryRanges()
143
144 std::vector<REntryRangeDS> fCurrentRanges; ///< Basis for the ranges returned by the last GetEntryRanges() call
145 std::vector<REntryRangeDS> fNextRanges; ///< Basis for the ranges populated by the PrepareNextRanges() call
146 /// Maps the first entries from the ranges of the last GetEntryRanges() call to their corresponding index in
147 /// the fCurrentRanges vectors. This is necessary because the returned ranges get distributed arbitrarily
148 /// onto slots. In the InitSlot method, the column readers use this map to find the correct range to connect to.
149 std::unordered_map<ULong64_t, std::size_t> fFirstEntry2RangeIdx;
150 // Keep track of the scheduled entries - necessary for processing of GlobalEntries
151 std::vector<std::pair<ULong64_t, ULong64_t>> fOriginalRanges;
152 /// One element per slot, corresponding to the current range index for that slot, as filled by InitSlot
153 std::vector<std::size_t> fSlotsToRangeIdxs;
154
155 /// The background thread that runs StageNextSources()
156 std::thread fThreadStaging;
157 /// Protects the shared state between the main thread and the I/O thread
158 std::mutex fMutexStaging;
159 /// Signal for the state information of fIsReadyForStaging and fHasNextSources
160 std::condition_variable fCvStaging;
161 /// Is true when the staging thread should start working
162 bool fIsReadyForStaging = false;
163 /// Is true when the staging thread has populated the next batch of files to fStagingArea
164 bool fHasNextSources = false;
165 /// Is true when the I/O thread should quit
167
168 /// \brief Holds useful information about fields added to the RNTupleDS
169 struct RFieldInfo {
171 std::size_t fNRepetitions;
172 // Enable `std::vector::emplace_back` for this type
177 };
178
179 /// Provides the RDF column "colName" given the field identified by fieldID. For records and collections,
180 /// AddField recurses into the sub fields. The fieldInfos argument is a list of objects holding info
181 /// about the fields of the outer collection(s) (w.r.t. fieldId). For instance, if fieldId refers to an
182 /// `std::vector<Jet>`, with
183 /// ~~~{.cpp}
184 /// struct Jet {
185 /// float pt;
186 /// float eta;
187 /// };
188 /// ~~~
189 /// AddField will recurse into `Jet.pt` and `Jet.eta` and provide the two inner fields as `ROOT::VecOps::RVec<float>`
190 /// each.
191 ///
192 /// In case the field is a collection of type `ROOT::VecOps::RVec`, `std::vector` or `std::array`, its corresponding
193 /// column is added as a `ROOT::VecOps::RVec`. Otherwise, the collection field's on-disk type is used. Note, however,
194 /// that inner record members of such collections will still be added as `ROOT::VecOps::RVec` (e.g., `std::set<Jet>
195 /// will be added as a `std::set`, but `Jet.[pt|eta] will be added as `ROOT::VecOps::RVec<float>).
196 void AddField(const ROOT::RNTupleDescriptor &desc, std::string_view colName, ROOT::DescriptorId_t fieldId,
197 std::vector<RFieldInfo> fieldInfos, bool convertToRVec = true);
198
199 /// The main function of the fThreadStaging background thread
200 void ExecStaging();
201 /// Starting from `fNextFileIndex`, opens the next `fNSlots` files. Calls `LoadStructure()` on the opened files.
202 /// The very first file is already available from the constructor.
203 void StageNextSources();
204 /// Populates fNextRanges with the next set of entry ranges. Moves files from the staging area as necessary
205 /// and aligns ranges with cluster boundaries for scheduling the tail of files.
206 /// Upon return, the fNextRanges list is ordered. It has usually fNSlots elements; fewer if there
207 /// is not enough work to give at least one cluster to every slot.
208 void PrepareNextRanges();
209
210 explicit RNTupleDS(std::unique_ptr<ROOT::Internal::RPageSource> pageSource);
211
212 ROOT::RFieldBase *GetFieldWithTypeChecks(std::string_view fieldName, const std::type_info &tid);
213
215 const std::vector<std::string> &fileNames,
216 const std::pair<ULong64_t, ULong64_t> &range);
217
218 // This function needs to acess private members fNTupleName and fFileNames
219 friend std::vector<std::pair<std::uint64_t, std::uint64_t>> ROOT::Internal::RDF::GetDatasetGlobalClusterBoundaries(
221
222 explicit RNTupleDS(std::string_view ntupleName, const std::vector<std::string> &fileNames,
223 const std::pair<ULong64_t, ULong64_t> &range);
224
225public:
226 RNTupleDS(std::string_view ntupleName, std::string_view fileName);
227 RNTupleDS(std::string_view ntupleName, const std::vector<std::string> &fileNames);
228 // Rule of five
229 RNTupleDS(const RNTupleDS &) = delete;
230 RNTupleDS &operator=(const RNTupleDS &) = delete;
231 RNTupleDS(RNTupleDS &&) = delete;
234
235 void SetNSlots(unsigned int nSlots) final;
236 std::size_t GetNFiles() const final { return fFileNames.empty() ? 1 : fFileNames.size(); }
237 const std::vector<std::string> &GetColumnNames() const final { return fColumnNames; }
238 const std::vector<std::string> &GetTopLevelFieldNames() const final { return fTopLevelFieldNames; }
239 bool HasColumn(std::string_view colName) const final;
240 std::string GetTypeName(std::string_view colName) const final;
241 std::vector<std::pair<ULong64_t, ULong64_t>> GetEntryRanges() final;
242 std::string GetLabel() final { return "RNTupleDS"; }
243
244 void Initialize() final;
245 void InitSlot(unsigned int slot, ULong64_t firstEntry) final;
246 void FinalizeSlot(unsigned int slot) final;
247 void Finalize() final;
248
249 std::unique_ptr<ROOT::Detail::RDF::RColumnReaderBase>
250 GetColumnReaders(unsigned int /*slot*/, std::string_view /*name*/, const std::type_info &) final;
251
252 ROOT::RDF::RSampleInfo
253 CreateSampleInfo(unsigned int,
254 const std::unordered_map<std::string, ROOT::RDF::Experimental::RSample *> &) const final;
255
256 // Old API, unused
257 bool SetEntry(unsigned int, ULong64_t) final { return true; }
258
259protected:
260 Record_t GetColumnReadersImpl(std::string_view name, const std::type_info &) final;
261};
262} // namespace ROOT::RDF
263
264namespace ROOT::RDF {
265RDataFrame FromRNTuple(std::string_view ntupleName, std::string_view fileName);
266RDataFrame FromRNTuple(std::string_view ntupleName, const std::vector<std::string> &fileNames);
267} // namespace ROOT::RDF
268
269#endif
unsigned long long ULong64_t
Portable unsigned long integer 8 bytes.
Definition RtypesCore.h:84
char name[80]
Definition TGX11.cxx:148
Pure virtual base class for all column reader types.
Every RDF column is represented by exactly one RNTuple field.
Abstract interface to read data from an ntuple.
RDataSource defines an API that RDataFrame can use to read arbitrary data formats.
friend ROOT::RDF::RSampleInfo ROOT::Internal::RDF::CreateSampleInfo(const ROOT::RDF::RDataSource &, unsigned int, const std::unordered_map< std::string, ROOT::RDF::Experimental::RSample * > &)
std::vector< void * > Record_t
The public interface to the RDataFrame federation of classes.
The RDataSource implementation for RNTuple.
Definition RNTupleDS.hxx:82
bool fHasNextSources
Is true when the staging thread has populated the next batch of files to fStagingArea.
const std::vector< std::string > & GetColumnNames() const final
Returns a reference to the collection of the dataset's column names.
void AddField(const ROOT::RNTupleDescriptor &desc, std::string_view colName, ROOT::DescriptorId_t fieldId, std::vector< RFieldInfo > fieldInfos, bool convertToRVec=true)
Provides the RDF column "colName" given the field identified by fieldID.
std::vector< std::pair< ULong64_t, ULong64_t > > GetEntryRanges() final
Return ranges of entries to distribute to tasks.
std::size_t GetNFiles() const final
Returns the number of files from which the dataset is constructed.
std::vector< REntryRangeDS > fNextRanges
Basis for the ranges populated by the PrepareNextRanges() call.
std::unordered_map< ULong64_t, std::size_t > fFirstEntry2RangeIdx
Maps the first entries from the ranges of the last GetEntryRanges() call to their corresponding index...
void ExecStaging()
The main function of the fThreadStaging background thread.
bool fStagingThreadShouldTerminate
Is true when the I/O thread should quit.
RNTupleDS(RNTupleDS &&)=delete
std::vector< std::vector< ROOT::Internal::RDF::RNTupleColumnReader * > > fActiveColumnReaders
List of column readers returned by GetColumnReaders() organized by slot.
std::vector< std::unique_ptr< ROOT::Internal::RPageSource > > fStagingArea
The staging area is relevant for chains of files, i.e.
std::vector< std::pair< ULong64_t, ULong64_t > > fOriginalRanges
std::unique_ptr< ROOT::Detail::RDF::RColumnReaderBase > GetColumnReaders(unsigned int, std::string_view, const std::type_info &) final
If the other GetColumnReaders overload returns an empty vector, this overload will be called instead.
std::vector< std::size_t > fSlotsToRangeIdxs
One element per slot, corresponding to the current range index for that slot, as filled by InitSlot.
std::vector< std::unique_ptr< ROOT::RFieldBase > > fProtoFields
We prepare a prototype field for every column.
void SetNSlots(unsigned int nSlots) final
Inform RDataSource of the number of processing slots (i.e.
ROOT::RFieldBase * GetFieldWithTypeChecks(std::string_view fieldName, const std::type_info &tid)
RNTupleDS & operator=(const RNTupleDS &)=delete
std::vector< std::string > fFileNames
bool fIsReadyForStaging
Is true when the staging thread should start working.
void InitSlot(unsigned int slot, ULong64_t firstEntry) final
Convenience method called at the start of the data processing associated to a slot.
ROOT::RNTupleDescriptor fPrincipalDescriptor
A clone of the first pages source's descriptor.
Definition RNTupleDS.hxx:97
ULong64_t fSeenEntriesNoGlobalRange
The number of entries seen so far in GetEntryRanges()
std::vector< REntryRangeDS > fCurrentRanges
Basis for the ranges returned by the last GetEntryRanges() call.
std::vector< std::string > fTopLevelFieldNames
RNTupleDS(std::unique_ptr< ROOT::Internal::RPageSource > pageSource)
std::string GetTypeName(std::string_view colName) const final
Type of a column as a string, e.g.
std::size_t fNextFileIndex
Index into fFileNames to the next file to process.
const std::vector< std::string > & GetTopLevelFieldNames() const final
std::unordered_map< ROOT::DescriptorId_t, std::string > fFieldId2QualifiedName
Connects the IDs of active proto fields and their subfields to their fully qualified name (a....
std::string fNTupleName
The data source may be constructed with an ntuple name and a list of files.
void PrepareNextRanges()
Populates fNextRanges with the next set of entry ranges.
void StageNextSources()
Starting from fNextFileIndex, opens the next fNSlots files.
std::condition_variable fCvStaging
Signal for the state information of fIsReadyForStaging and fHasNextSources.
RNTupleDS(const RNTupleDS &)=delete
void Finalize() final
Convenience method called after concluding an event-loop.
std::string GetLabel() final
Return a string representation of the datasource type.
RNTupleDS & operator=(RNTupleDS &&)=delete
std::thread fThreadStaging
The background thread that runs StageNextSources()
std::mutex fMutexStaging
Protects the shared state between the main thread and the I/O thread.
std::unordered_map< std::size_t, std::vector< std::unique_ptr< ROOT::RFieldBase > > > fAlternativeProtoFields
Columns may be requested with types other than with which they were initially added as proto fields.
bool SetEntry(unsigned int, ULong64_t) final
Advance the "cursors" returned by GetColumnReaders to the selected entry for a particular slot.
std::vector< std::string > fColumnTypes
void Initialize() final
Convenience method called before starting an event-loop.
std::vector< std::string > fColumnNames
bool HasColumn(std::string_view colName) const final
Checks if the dataset has a certain column.
Record_t GetColumnReadersImpl(std::string_view name, const std::type_info &) final
type-erased vector of pointers to pointers to column values - one per slot
void FinalizeSlot(unsigned int slot) final
Convenience method called at the end of the data processing associated to a slot.
This type represents a sample identifier, to be used in conjunction with RDataFrame features such as ...
ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree ,...
A field translates read and write calls from/to underlying columns to/from tree values.
The on-storage metadata of an RNTuple.
ROOT::RDataFrame FromRNTuple(std::string_view ntupleName, const std::vector< std::string > &fileNames, const std::pair< ULong64_t, ULong64_t > &range)
Internal overload of the function that allows passing a range of entries.
std::pair< std::vector< ROOT::Internal::RNTupleClusterBoundaries >, ROOT::NTupleSize_t > GetClustersAndEntries(std::string_view ntupleName, std::string_view location)
Retrieves the cluster boundaries and the number of entries for the input RNTuple.
std::vector< std::pair< std::uint64_t, std::uint64_t > > GetDatasetGlobalClusterBoundaries(const RNode &node)
Retrieve the cluster boundaries for each cluster in the dataset, across files, with a global offset.
std::uint64_t DescriptorId_t
Distriniguishes elements of the same type within a descriptor, e.g. different fields.
std::uint64_t NTupleSize_t
Integer type long enough to hold the maximum number of entries in a column.
The PrepareNextRanges() method populates the fNextRanges list with REntryRangeDS records.
Definition RNTupleDS.hxx:88
std::string_view fFileName
Storage location of the current RNTuple.
Definition RNTupleDS.hxx:93
ULong64_t fLastEntry
End entry index in fSource, e.g. the number of entries in the range is fLastEntry - fFirstEntry.
Definition RNTupleDS.hxx:92
std::unique_ptr< ROOT::Internal::RPageSource > fSource
Definition RNTupleDS.hxx:89
ULong64_t fFirstEntry
First entry index in fSource.
Definition RNTupleDS.hxx:90
Holds useful information about fields added to the RNTupleDS.
RFieldInfo(ROOT::DescriptorId_t fieldId, std::size_t nRepetitions)
ROOT::DescriptorId_t fFieldId