Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RNTupleReader.cxx
Go to the documentation of this file.
1/// \file RNTupleReader.cxx
2/// \author Jakob Blomer <jblomer@cern.ch>
3/// \date 2024-02-20
4
5/*************************************************************************
6 * Copyright (C) 1995-2024, Rene Brun and Fons Rademakers. *
7 * All rights reserved. *
8 * *
9 * For the licensing terms see $ROOTSYS/LICENSE. *
10 * For the list of contributors see $ROOTSYS/README/CREDITS. *
11 *************************************************************************/
12
14
15#include <ROOT/RField.hxx>
19#include <ROOT/RNTuple.hxx>
20#include <ROOT/RNTupleModel.hxx>
21#include <ROOT/RNTupleUtils.hxx>
23
24#include <TROOT.h>
25
26#include <cassert>
27
29{
31 auto descGuard = fPtrControlBlock->fPageSource->FindClusterId(entryNumber, clusterId);
32 if (clusterId == kInvalidDescriptorId)
33 throw RException(R__FAIL(std::string("entry number ") + std::to_string(entryNumber) + " out of range"));
34
35 auto [itr, _] = fPtrControlBlock->fActiveClusters.try_emplace(clusterId, 0);
36 if (itr->second++ == 0)
37 fPtrControlBlock->fPageSource->PinCluster(clusterId);
38}
39
41{
43 auto descGuard = fPtrControlBlock->fPageSource->FindClusterId(entryNumber, clusterId);
44 // We acquired the given entry number so we must be able to find it back
45 R__ASSERT(clusterId != kInvalidDescriptorId);
46
47 auto itr = fPtrControlBlock->fActiveClusters.find(clusterId);
48 assert(itr != fPtrControlBlock->fActiveClusters.end());
49
50 if (--(itr->second) == 0) {
51 fPtrControlBlock->fActiveClusters.erase(itr);
52 fPtrControlBlock->fPageSource->UnpinCluster(clusterId);
53 }
54}
55
57{
58 if (entryNumber == fEntryNumber || entryNumber == kInvalidNTupleIndex)
59 return;
60
61 const std::lock_guard<std::mutex> _(fPtrControlBlock->fLock);
62 if (fPtrControlBlock->fPageSource) {
63 ActivateEntry(entryNumber);
64 if (fEntryNumber != kInvalidNTupleIndex)
65 DeactivateEntry(fEntryNumber);
66 }
67 fEntryNumber = entryNumber;
68}
69
71{
72 if (fEntryNumber == kInvalidNTupleIndex)
73 return;
74
75 const std::lock_guard<std::mutex> _(fPtrControlBlock->fLock);
76 if (fPtrControlBlock->fPageSource) {
77 DeactivateEntry(fEntryNumber);
78 }
79 fEntryNumber = kInvalidNTupleIndex;
80}
81
83{
84 fPtrControlBlock = other.fPtrControlBlock;
85 SetEntryNumber(other.fEntryNumber);
86}
87
89{
90 std::swap(fEntryNumber, other.fEntryNumber);
91 std::swap(fPtrControlBlock, other.fPtrControlBlock);
92 assert(other.fEntryNumber == kInvalidNTupleIndex);
93 assert(!other.fPtrControlBlock);
94}
95
98{
99 if (this == &other)
100 return *this;
101 if (other.fPtrControlBlock.get() != fPtrControlBlock.get()) {
102 Reset();
103 fPtrControlBlock = other.fPtrControlBlock;
104 }
105 SetEntryNumber(other.fEntryNumber);
106 return *this;
107}
108
111{
112 std::swap(fEntryNumber, other.fEntryNumber);
113 std::swap(fPtrControlBlock, other.fPtrControlBlock);
114 return *this;
115}
116
117void ROOT::RNTupleReader::ConnectModel(ROOT::RNTupleModel &model, bool allowFieldSubstitutions)
118{
119 auto &fieldZero = ROOT::Internal::GetFieldZeroOfModel(model);
120 ROOT::Internal::SetAllowFieldSubstitutions(fieldZero, allowFieldSubstitutions);
121 // We must not use the descriptor guard to prevent recursive locking in field.ConnectPageSource
122 ROOT::DescriptorId_t fieldZeroId = fSource->GetSharedDescriptorGuard()->GetFieldZeroId();
123 fieldZero.SetOnDiskId(fieldZeroId);
124 // Iterate only over fieldZero's direct subfields; their descendants are recursively handled in
125 // RFieldBase::ConnectPageSource
126 for (auto &field : fieldZero.GetMutableSubfields()) {
127 // If the model has been created from the descriptor, the on-disk IDs are already set.
128 // User-provided models instead need to find their corresponding IDs in the descriptor.
129 if (field->GetOnDiskId() == ROOT::kInvalidDescriptorId) {
130 field->SetOnDiskId(fSource->GetSharedDescriptorGuard()->FindFieldId(field->GetFieldName(), fieldZeroId));
131 }
133 }
135}
136
138{
139#ifdef R__USE_IMT
140 if (IsImplicitMTEnabled() &&
141 fSource->GetReadOptions().GetUseImplicitMT() == ROOT::RNTupleReadOptions::EImplicitMT::kDefault) {
142 fUnzipTasks = std::make_unique<Experimental::Internal::RNTupleImtTaskScheduler>();
143 fSource->SetTaskScheduler(fUnzipTasks.get());
144 }
145#endif
146 fMetrics.ObserveMetrics(fSource->GetMetrics());
147 if (enableMetrics)
149 fSource->Attach();
150 fNEntries = fSource->GetNEntries();
151 fActiveEntriesControlBlock = std::make_shared<RActiveEntriesControlBlock>(fSource.get());
152}
153
154ROOT::RNTupleReader::RNTupleReader(std::unique_ptr<ROOT::RNTupleModel> model,
155 std::unique_ptr<ROOT::Internal::RPageSource> source,
156 const ROOT::RNTupleReadOptions &options)
157 : fSource(std::move(source)), fModel(std::move(model)), fMetrics("RNTupleReader", fSource->GetNTupleName())
158{
159 // TODO(jblomer): properly support projected fields
160 auto &projectedFields = ROOT::Internal::GetProjectedFieldsOfModel(*fModel);
161 if (!projectedFields.IsEmpty()) {
162 throw RException(R__FAIL("model has projected fields, which is incompatible with providing a read model"));
163 }
164 fModel->Freeze();
166 ConnectModel(*fModel, false /* allowFieldSubstitutions */);
167}
168
169ROOT::RNTupleReader::RNTupleReader(std::unique_ptr<ROOT::Internal::RPageSource> source,
170 const ROOT::RNTupleReadOptions &options)
171 : fSource(std::move(source)),
172 fModel(nullptr),
173 fStringPool(std::make_shared<Internal::RStringPool>()),
174 fMetrics("RNTupleReader", fSource->GetNTupleName())
175{
177}
178
180{
181 const std::lock_guard<std::mutex> _(fActiveEntriesControlBlock->fLock);
182 fActiveEntriesControlBlock->fPageSource = nullptr;
183}
184
185std::unique_ptr<ROOT::RNTupleReader> ROOT::RNTupleReader::Open(std::unique_ptr<ROOT::RNTupleModel> model,
186 std::string_view ntupleName, std::string_view storage,
187 const ROOT::RNTupleReadOptions &options)
188{
189 return std::unique_ptr<RNTupleReader>(
190 new RNTupleReader(std::move(model), Internal::RPageSource::Create(ntupleName, storage, options), options));
191}
192
193std::unique_ptr<ROOT::RNTupleReader> ROOT::RNTupleReader::Open(std::string_view ntupleName, std::string_view storage,
194 const ROOT::RNTupleReadOptions &options)
195{
196 return std::unique_ptr<RNTupleReader>(
197 new RNTupleReader(Internal::RPageSource::Create(ntupleName, storage, options), options));
198}
199
200std::unique_ptr<ROOT::RNTupleReader>
202{
203 return std::unique_ptr<RNTupleReader>(
204 new RNTupleReader(Internal::RPageSourceFile::CreateFromAnchor(ntuple, options), options));
205}
206
207std::unique_ptr<ROOT::RNTupleReader> ROOT::RNTupleReader::Open(std::unique_ptr<ROOT::RNTupleModel> model,
208 const ROOT::RNTuple &ntuple,
209 const ROOT::RNTupleReadOptions &options)
210{
211 return std::unique_ptr<RNTupleReader>(
212 new RNTupleReader(std::move(model), Internal::RPageSourceFile::CreateFromAnchor(ntuple, options), options));
213}
214
215std::unique_ptr<ROOT::RNTupleReader>
217 std::string_view ntupleName, std::string_view storage,
218 const ROOT::RNTupleReadOptions &options)
219{
220 auto reader = std::unique_ptr<RNTupleReader>(
221 new RNTupleReader(Internal::RPageSource::Create(ntupleName, storage, options), options));
222 reader->fCreateModelOptions = createModelOpts;
223 return reader;
224}
225
226std::unique_ptr<ROOT::RNTupleReader>
228 const ROOT::RNTuple &ntuple, const ROOT::RNTupleReadOptions &options)
229{
230 auto reader = std::unique_ptr<RNTupleReader>(
231 new RNTupleReader(Internal::RPageSourceFile::CreateFromAnchor(ntuple, options), options));
232 reader->fCreateModelOptions = createModelOpts;
233 return reader;
234}
235
237{
238 if (!fModel) {
239 Internal::RFieldSharedStringPoolRaii stringPoolRaii(fStringPool);
240 fModel = fSource->GetSharedDescriptorGuard()->CreateModel(
241 fCreateModelOptions.value_or(ROOT::RNTupleDescriptor::RCreateModelOptions{}));
242 ConnectModel(*fModel, true /* allowFieldSubstitutions */);
243 }
244 return *fModel;
245}
246
247std::unique_ptr<ROOT::REntry> ROOT::RNTupleReader::CreateEntry()
248{
249 return GetModel().CreateEntry();
250}
251
252void ROOT::RNTupleReader::PrintInfo(const ENTupleInfo what, std::ostream &output) const
253{
254 using namespace ROOT::Internal;
255
256 switch (what) {
258 std::string name;
259 std::unique_ptr<ROOT::RNTupleModel> fullModel;
260 {
261 auto descriptorGuard = fSource->GetSharedDescriptorGuard();
262 name = descriptorGuard->GetName();
264 opts.SetCreateBare(true);
265 // When printing the schema we always try to reconstruct the whole thing even when we are missing the
266 // dictionaries.
267 opts.SetEmulateUnknownTypes(true);
268 fullModel = descriptorGuard->CreateModel(opts);
269 }
270
271 // FitString defined in RFieldVisitor.cxx
272 output << "RNTuple : " << name << "\n";
273 output << "Entries : " << GetNEntries() << "\n\n";
274
275 // Traverses through all fields to gather information needed for printing.
276 RPrepareVisitor prepVisitor;
277 // Traverses through all fields to do the actual printing.
278 RPrintSchemaVisitor printVisitor(output);
279
280 // Note that we do not need to connect the model, we are only looking at its tree of fields
281 fullModel->GetConstFieldZero().AcceptVisitor(prepVisitor);
282
283 printVisitor.SetDeepestLevel(prepVisitor.GetDeepestLevel());
284 printVisitor.SetNumFields(prepVisitor.GetNumFields());
285
286 fullModel->GetConstFieldZero().AcceptVisitor(printVisitor);
287 output << std::flush;
288 break;
289 }
291 fSource->LoadAllPageLists();
292 fSource->GetSharedDescriptorGuard()->PrintInfo(output);
293 break;
294 case ENTupleInfo::kMetrics: fMetrics.Print(output); break;
295 default:
296 // Unhandled case, internal error
297 R__ASSERT(false);
298 }
299}
300
302{
303 if (!fDisplayReader) {
304 Internal::RFieldSharedStringPoolRaii stringPoolRaii(fStringPool);
306 opts.SetEmulateUnknownTypes(true);
307 auto fullModel = fSource->GetSharedDescriptorGuard()->CreateModel(opts);
308 fDisplayReader = std::unique_ptr<RNTupleReader>(
309 new RNTupleReader(std::move(fullModel), fSource->Clone(), ROOT::RNTupleReadOptions{}));
310 fDisplayReader->fStringPool = fStringPool;
311 }
312 return fDisplayReader.get();
313}
314
316{
317 auto reader = GetDisplayReader();
318 const auto &entry = reader->GetModel().GetDefaultEntry();
319
320 reader->LoadEntry(index);
321 output << "{";
322 for (auto iValue = entry.begin(); iValue != entry.end();) {
323 output << '\n';
324 ROOT::Internal::RPrintValueVisitor visitor(*iValue, output, 1 /* level */);
325 iValue->GetField().AcceptVisitor(visitor);
326
327 if (++iValue == entry.end()) {
328 output << '\n';
329 break;
330 } else {
331 output << ",";
332 }
333 }
334 output << "}\n";
335}
336
338{
339 auto descriptorGuard = fSource->GetSharedDescriptorGuard();
340 if (!fCachedDescriptor || fCachedDescriptor->GetGeneration() != descriptorGuard->GetGeneration())
341 fCachedDescriptor = descriptorGuard->Clone();
342 return *fCachedDescriptor;
343}
344
346{
347 auto fieldId = fSource->GetSharedDescriptorGuard()->FindFieldId(fieldName);
348 if (fieldId == ROOT::kInvalidDescriptorId) {
349 throw RException(R__FAIL("no field named '" + std::string(fieldName) + "' in RNTuple '" +
350 fSource->GetSharedDescriptorGuard()->GetName() + "'"));
351 }
352 return fieldId;
353}
354
355std::unique_ptr<ROOT::RNTupleAttrSetReader>
356ROOT::RNTupleReader::OpenAttributeSet(std::string_view attrSetName, const ROOT::RNTupleReadOptions &readOpts)
357{
358 auto attrSets = GetDescriptor().GetAttrSetIterable();
359 const auto it =
360 std::find_if(attrSets.begin(), attrSets.end(), [&](const auto &d) { return d.GetName() == attrSetName; });
361 if (it == attrSets.end())
362 throw ROOT::RException(R__FAIL(std::string("No such attribute set: ") + std::string(attrSetName)));
363
364 auto attrSource = fSource->OpenWithDifferentAnchor({it->GetAnchorLocator(), it->GetAnchorLength()}, readOpts);
365 auto newReader = std::unique_ptr<RNTupleReader>(new RNTupleReader(std::move(attrSource), readOpts));
366 R__ASSERT(newReader);
367 auto attrSetReader = std::unique_ptr<ROOT::RNTupleAttrSetReader>(
368 new ROOT::RNTupleAttrSetReader(std::move(newReader), it->GetSchemaVersionMajor()));
369 return attrSetReader;
370}
#define R__FAIL(msg)
Short-hand to return an RResult<T> in an error state; the RError is implicitly converted into RResult...
Definition RError.hxx:322
#define d(i)
Definition RSha256.hxx:102
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:139
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
char name[80]
Definition TGX11.cxx:142
#define _(A, B)
Definition cfortran.h:112
void ObserveMetrics(RNTupleMetrics &observee)
Set a common string pool for all field (hierarchies) created in a block.
static std::unique_ptr< RPageSourceFile > CreateFromAnchor(const RNTuple &anchor, const ROOT::RNTupleReadOptions &options=ROOT::RNTupleReadOptions())
Used from the RNTuple class to build a datasource if the anchor is already available.
static std::unique_ptr< RPageSource > Create(std::string_view ntupleName, std::string_view location, const ROOT::RNTupleReadOptions &options=ROOT::RNTupleReadOptions())
Guess the concrete derived page source from the file name (location)
Visitor used for a pre-processing run to collect information needed by another visitor class.
unsigned int GetDeepestLevel() const
unsigned int GetNumFields() const
Contains settings for printing and prints a summary of an RField instance.
Renders a JSON value corresponding to the field.
Used for string interning of repeated type names, field names, etc.
Base class for all ROOT issued exceptions.
Definition RError.hxx:78
Class used to read a RNTupleAttrSet in the context of a RNTupleReader.
The on-storage metadata of an RNTuple.
ROOT::DescriptorId_t FindFieldId(std::string_view fieldName, ROOT::DescriptorId_t parentId) const
RNTupleDescriptor Clone() const
The RNTupleModel encapulates the schema of an RNTuple.
Common user-tunable settings for reading RNTuples.
An active entry token is a pledge for the data of a certain entry number not to be evicted from the p...
std::shared_ptr< RActiveEntriesControlBlock > fPtrControlBlock
RActiveEntryToken & operator=(const RActiveEntryToken &other)
void ActivateEntry(NTupleSize_t entryNumber)
void Reset()
Release the entry number, i.e.
RActiveEntryToken(std::shared_ptr< RActiveEntriesControlBlock > ptrControlBlock)
void DeactivateEntry(NTupleSize_t entryNumber)
void SetEntryNumber(NTupleSize_t entryNumber)
Set or replace the entry number.
Reads RNTuple data from storage.
std::unique_ptr< Internal::RNTupleTaskScheduler > fUnzipTasks
Set as the page source's scheduler for parallel page decompression if implicit multi-threading (IMT) ...
std::unique_ptr< ROOT::REntry > CreateEntry()
static std::unique_ptr< RNTupleReader > Open(std::string_view ntupleName, std::string_view storage, const ROOT::RNTupleReadOptions &options=ROOT::RNTupleReadOptions())
Open an RNTuple for reading.
void InitPageSource(bool enableMetrics)
std::unique_ptr< RNTupleAttrSetReader > OpenAttributeSet(std::string_view attrSetName, const ROOT::RNTupleReadOptions &options={})
Looks for an attribute set with the given name and creates an RNTupleAttrSetReader for it,...
ROOT::NTupleSize_t fNEntries
We know that the RNTupleReader is always reading a single RNTuple, so the number of entries is fixed.
std::unique_ptr< ROOT::RNTupleModel > fModel
Needs to be destructed before fSource.
const ROOT::RNTupleDescriptor & GetDescriptor()
Returns a cached copy of the page source descriptor.
void PrintInfo(const ENTupleInfo what=ENTupleInfo::kSummary, std::ostream &output=std::cout) const
Prints a detailed summary of the RNTuple, including a list of fields.
std::unique_ptr< Internal::RPageSource > fSource
RNTupleReader(std::unique_ptr< ROOT::RNTupleModel > model, std::unique_ptr< Internal::RPageSource > source, const ROOT::RNTupleReadOptions &options)
const ROOT::RNTupleModel & GetModel()
std::shared_ptr< RActiveEntriesControlBlock > fActiveEntriesControlBlock
Initialized when the page source is connected.
void ConnectModel(ROOT::RNTupleModel &model, bool allowFieldSubstitutions)
ROOT::DescriptorId_t RetrieveFieldId(std::string_view fieldName) const
void Show(ROOT::NTupleSize_t index, std::ostream &output=std::cout)
Shows the values of the i-th entry/row, starting with 0 for the first entry.
RNTupleReader * GetDisplayReader()
Experimental::Detail::RNTupleMetrics fMetrics
void EnableMetrics()
Enable performance measurements (decompression time, bytes read from storage, etc....
Representation of an RNTuple data set in a ROOT file.
Definition RNTuple.hxx:67
void SetAllowFieldSubstitutions(RFieldZero &fieldZero, bool val)
Definition RField.cxx:35
ROOT::RFieldZero & GetFieldZeroOfModel(RNTupleModel &model)
void CallConnectPageSourceOnField(RFieldBase &, ROOT::Internal::RPageSource &)
RProjectedFields & GetProjectedFieldsOfModel(RNTupleModel &model)
Bool_t IsImplicitMTEnabled()
Returns true if the implicit multi-threading in ROOT is enabled.
Definition TROOT.cxx:673
std::uint64_t DescriptorId_t
Distriniguishes elements of the same type within a descriptor, e.g. different fields.
constexpr NTupleSize_t kInvalidNTupleIndex
ENTupleInfo
Listing of the different options that can be printed by RNTupleReader::GetInfo()
std::uint64_t NTupleSize_t
Integer type long enough to hold the maximum number of entries in a column.
constexpr DescriptorId_t kInvalidDescriptorId
static const char * what
Definition stlLoader.cc:5