Logo ROOT  
Reference Guide
RLoopManager.cxx
Go to the documentation of this file.
1/*************************************************************************
2 * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. *
3 * All rights reserved. *
4 * *
5 * For the licensing terms see $ROOTSYS/LICENSE. *
6 * For the list of contributors see $ROOTSYS/README/CREDITS. *
7 *************************************************************************/
8
9#include "RConfigure.h" // R__USE_IMT
10#include "ROOT/RDataSource.hxx"
12#include "ROOT/InternalTreeUtils.hxx" // GetTreeFullPaths
18#include "ROOT/RLogger.hxx"
19#include "RtypesCore.h" // Long64_t
20#include "TStopwatch.h"
21#include "TBranchElement.h"
22#include "TBranchObject.h"
23#include "TChain.h"
24#include "TEntryList.h"
25#include "TFile.h"
26#include "TFriendElement.h"
27#include "TInterpreter.h"
28#include "TROOT.h" // IsImplicitMTEnabled
29#include "TTreeReader.h"
30#include "TTree.h" // For MaxTreeSizeRAII. Revert when #6640 will be solved.
31
32#ifdef R__USE_IMT
35#endif
36
37#include <algorithm>
38#include <atomic>
39#include <cassert>
40#include <exception>
41#include <functional>
42#include <iostream>
43#include <memory>
44#include <stdexcept>
45#include <string>
46#include <sstream>
47#include <thread>
48#include <unordered_map>
49#include <vector>
50#include <set>
51#include <limits> // For MaxTreeSizeRAII. Revert when #6640 will be solved.
52
53using namespace ROOT::Detail::RDF;
54using namespace ROOT::Internal::RDF;
55
56namespace {
57/// A helper function that returns all RDF code that is currently scheduled for just-in-time compilation.
58/// This allows different RLoopManager instances to share these data.
59/// We want RLoopManagers to be able to add their code to a global "code to execute via cling",
60/// so that, lazily, we can jit everything that's needed by all RDFs in one go, which is potentially
61/// much faster than jitting each RLoopManager's code separately.
62static std::string &GetCodeToJit()
63{
64 static std::string code;
65 return code;
66}
67
68static bool ContainsLeaf(const std::set<TLeaf *> &leaves, TLeaf *leaf)
69{
70 return (leaves.find(leaf) != leaves.end());
71}
72
73///////////////////////////////////////////////////////////////////////////////
74/// This overload does not check whether the leaf/branch is already in bNamesReg. In case this is a friend leaf/branch,
75/// `allowDuplicates` controls whether we add both `friendname.bname` and `bname` or just the shorter version.
76static void InsertBranchName(std::set<std::string> &bNamesReg, ColumnNames_t &bNames, const std::string &branchName,
77 const std::string &friendName, bool allowDuplicates)
78{
79 if (!friendName.empty()) {
80 // In case of a friend tree, users might prepend its name/alias to the branch names
81 const auto friendBName = friendName + "." + branchName;
82 if (bNamesReg.insert(friendBName).second)
83 bNames.push_back(friendBName);
84 }
85
86 if (allowDuplicates || friendName.empty()) {
87 if (bNamesReg.insert(branchName).second)
88 bNames.push_back(branchName);
89 }
90}
91
92///////////////////////////////////////////////////////////////////////////////
93/// This overload makes sure that the TLeaf has not been already inserted.
94static void InsertBranchName(std::set<std::string> &bNamesReg, ColumnNames_t &bNames, const std::string &branchName,
95 const std::string &friendName, std::set<TLeaf *> &foundLeaves, TLeaf *leaf,
96 bool allowDuplicates)
97{
98 const bool canAdd = allowDuplicates ? true : !ContainsLeaf(foundLeaves, leaf);
99 if (!canAdd) {
100 return;
101 }
102
103 InsertBranchName(bNamesReg, bNames, branchName, friendName, allowDuplicates);
104
105 foundLeaves.insert(leaf);
106}
107
108static void ExploreBranch(TTree &t, std::set<std::string> &bNamesReg, ColumnNames_t &bNames, TBranch *b,
109 std::string prefix, std::string &friendName, bool allowDuplicates)
110{
111 for (auto sb : *b->GetListOfBranches()) {
112 TBranch *subBranch = static_cast<TBranch *>(sb);
113 auto subBranchName = std::string(subBranch->GetName());
114 auto fullName = prefix + subBranchName;
115
116 std::string newPrefix;
117 if (!prefix.empty())
118 newPrefix = fullName + ".";
119
120 ExploreBranch(t, bNamesReg, bNames, subBranch, newPrefix, friendName, allowDuplicates);
121
122 auto branchDirectlyFromTree = t.GetBranch(fullName.c_str());
123 if (!branchDirectlyFromTree)
124 branchDirectlyFromTree = t.FindBranch(fullName.c_str()); // try harder
125 if (branchDirectlyFromTree)
126 InsertBranchName(bNamesReg, bNames, std::string(branchDirectlyFromTree->GetFullName()), friendName,
127 allowDuplicates);
128
129 if (t.GetBranch(subBranchName.c_str()))
130 InsertBranchName(bNamesReg, bNames, subBranchName, friendName, allowDuplicates);
131 }
132}
133
134static void GetBranchNamesImpl(TTree &t, std::set<std::string> &bNamesReg, ColumnNames_t &bNames,
135 std::set<TTree *> &analysedTrees, std::string &friendName, bool allowDuplicates)
136{
137 std::set<TLeaf *> foundLeaves;
138 if (!analysedTrees.insert(&t).second) {
139 return;
140 }
141
142 const auto branches = t.GetListOfBranches();
143 // Getting the branches here triggered the read of the first file of the chain if t is a chain.
144 // We check if a tree has been successfully read, otherwise we throw (see ROOT-9984) to avoid further
145 // operations
146 if (!t.GetTree()) {
147 std::string err("GetBranchNames: error in opening the tree ");
148 err += t.GetName();
149 throw std::runtime_error(err);
150 }
151 if (branches) {
152 for (auto b : *branches) {
153 TBranch *branch = static_cast<TBranch *>(b);
154 const auto branchName = std::string(branch->GetName());
155 if (branch->IsA() == TBranch::Class()) {
156 // Leaf list
157 auto listOfLeaves = branch->GetListOfLeaves();
158 if (listOfLeaves->GetEntriesUnsafe() == 1) {
159 auto leaf = static_cast<TLeaf *>(listOfLeaves->UncheckedAt(0));
160 InsertBranchName(bNamesReg, bNames, branchName, friendName, foundLeaves, leaf, allowDuplicates);
161 }
162
163 for (auto leaf : *listOfLeaves) {
164 auto castLeaf = static_cast<TLeaf *>(leaf);
165 const auto leafName = std::string(leaf->GetName());
166 const auto fullName = branchName + "." + leafName;
167 InsertBranchName(bNamesReg, bNames, fullName, friendName, foundLeaves, castLeaf, allowDuplicates);
168 }
169 } else if (branch->IsA() == TBranchObject::Class()) {
170 // TBranchObject
171 ExploreBranch(t, bNamesReg, bNames, branch, branchName + ".", friendName, allowDuplicates);
172 InsertBranchName(bNamesReg, bNames, branchName, friendName, allowDuplicates);
173 } else {
174 // TBranchElement
175 // Check if there is explicit or implicit dot in the name
176
177 bool dotIsImplied = false;
178 auto be = dynamic_cast<TBranchElement *>(b);
179 if (!be)
180 throw std::runtime_error("GetBranchNames: unsupported branch type");
181 // TClonesArray (3) and STL collection (4)
182 if (be->GetType() == 3 || be->GetType() == 4)
183 dotIsImplied = true;
184
185 if (dotIsImplied || branchName.back() == '.')
186 ExploreBranch(t, bNamesReg, bNames, branch, "", friendName, allowDuplicates);
187 else
188 ExploreBranch(t, bNamesReg, bNames, branch, branchName + ".", friendName, allowDuplicates);
189
190 InsertBranchName(bNamesReg, bNames, branchName, friendName, allowDuplicates);
191 }
192 }
193 }
194
195 // The list of friends needs to be accessed via GetTree()->GetListOfFriends()
196 // (and not via GetListOfFriends() directly), otherwise when `t` is a TChain we
197 // might not recover the list correctly (https://github.com/root-project/root/issues/6741).
198 auto friendTrees = t.GetTree()->GetListOfFriends();
199
200 if (!friendTrees)
201 return;
202
203 for (auto friendTreeObj : *friendTrees) {
204 auto friendTree = ((TFriendElement *)friendTreeObj)->GetTree();
205
206 std::string frName;
207 auto alias = t.GetFriendAlias(friendTree);
208 if (alias != nullptr)
209 frName = std::string(alias);
210 else
211 frName = std::string(friendTree->GetName());
212
213 GetBranchNamesImpl(*friendTree, bNamesReg, bNames, analysedTrees, frName, allowDuplicates);
214 }
215}
216
217static void ThrowIfNSlotsChanged(unsigned int nSlots)
218{
219 const auto currentSlots = RDFInternal::GetNSlots();
220 if (currentSlots != nSlots) {
221 std::string msg = "RLoopManager::Run: when the RDataFrame was constructed the number of slots required was " +
222 std::to_string(nSlots) + ", but when starting the event loop it was " +
223 std::to_string(currentSlots) + ".";
224 if (currentSlots > nSlots)
225 msg += " Maybe EnableImplicitMT() was called after the RDataFrame was constructed?";
226 else
227 msg += " Maybe DisableImplicitMT() was called after the RDataFrame was constructed?";
228 throw std::runtime_error(msg);
229 }
230}
231
232/**
233\struct MaxTreeSizeRAII
234\brief Scope-bound change of `TTree::fgMaxTreeSize`.
235
236This RAII object stores the current value result of `TTree::GetMaxTreeSize`,
237changes it to maximum at construction time and restores it back at destruction
238time. Needed for issue #6523 and should be reverted when #6640 will be solved.
239*/
240struct MaxTreeSizeRAII {
241 Long64_t fOldMaxTreeSize;
242
243 MaxTreeSizeRAII() : fOldMaxTreeSize(TTree::GetMaxTreeSize())
244 {
245 TTree::SetMaxTreeSize(std::numeric_limits<Long64_t>::max());
246 }
247
248 ~MaxTreeSizeRAII() { TTree::SetMaxTreeSize(fOldMaxTreeSize); }
249};
250
251struct DatasetLogInfo {
252 std::string fDataSet;
253 ULong64_t fRangeStart;
254 ULong64_t fRangeEnd;
255 unsigned int fSlot;
256};
257
258std::string LogRangeProcessing(const DatasetLogInfo &info)
259{
260 std::stringstream msg;
261 msg << "Processing " << info.fDataSet << ": entry range [" << info.fRangeStart << "," << info.fRangeEnd - 1
262 << "], using slot " << info.fSlot << " in thread " << std::this_thread::get_id() << '.';
263 return msg.str();
264}
265
266DatasetLogInfo TreeDatasetLogInfo(const TTreeReader &r, unsigned int slot)
267{
268 const auto tree = r.GetTree();
269 const auto chain = dynamic_cast<TChain *>(tree);
270 std::string what;
271 if (chain) {
272 auto files = chain->GetListOfFiles();
273 std::vector<std::string> treeNames;
274 std::vector<std::string> fileNames;
275 for (TObject *f : *files) {
276 treeNames.emplace_back(f->GetName());
277 fileNames.emplace_back(f->GetTitle());
278 }
279 what = "trees {";
280 for (const auto &t : treeNames) {
281 what += t + ",";
282 }
283 what.back() = '}';
284 what += " in files {";
285 for (const auto &f : fileNames) {
286 what += f + ",";
287 }
288 what.back() = '}';
289 } else {
290 assert(tree != nullptr); // to make clang-tidy happy
291 const auto treeName = tree->GetName();
292 what = std::string("tree \"") + treeName + "\"";
293 const auto file = tree->GetCurrentFile();
294 if (file)
295 what += std::string(" in file \"") + file->GetName() + "\"";
296 }
297 const auto entryRange = r.GetEntriesRange();
298 const ULong64_t end = entryRange.second == -1ll ? tree->GetEntries() : entryRange.second;
299 return {std::move(what), static_cast<ULong64_t>(entryRange.first), end, slot};
300}
301
302} // anonymous namespace
303
304namespace ROOT {
305namespace Detail {
306namespace RDF {
307
308/// A RAII object that calls RLoopManager::CleanUpTask at destruction
311 unsigned int fArg;
313
314 RCallCleanUpTask(RLoopManager &lm, unsigned int arg = 0u, TTreeReader *reader = nullptr)
315 : fLoopManager(lm), fArg(arg), fReader(reader)
316 {
317 }
319};
320
321} // namespace RDF
322} // namespace Detail
323} // namespace ROOT
324
325///////////////////////////////////////////////////////////////////////////////
326/// Get all the branches names, including the ones of the friend trees
328{
329 std::set<std::string> bNamesSet;
330 ColumnNames_t bNames;
331 std::set<TTree *> analysedTrees;
332 std::string emptyFrName = "";
333 GetBranchNamesImpl(t, bNamesSet, bNames, analysedTrees, emptyFrName, allowDuplicates);
334 return bNames;
335}
336
337RLoopManager::RLoopManager(TTree *tree, const ColumnNames_t &defaultBranches)
338 : fTree(std::shared_ptr<TTree>(tree, [](TTree *) {})), fDefaultColumns(defaultBranches),
339 fNSlots(RDFInternal::GetNSlots()),
340 fLoopType(ROOT::IsImplicitMTEnabled() ? ELoopType::kROOTFilesMT : ELoopType::kROOTFiles),
341 fNewSampleNotifier(fNSlots), fSampleInfos(fNSlots)
342{
343}
344
346 : fNEmptyEntries(nEmptyEntries), fNSlots(RDFInternal::GetNSlots()),
347 fLoopType(ROOT::IsImplicitMTEnabled() ? ELoopType::kNoFilesMT : ELoopType::kNoFiles), fNewSampleNotifier(fNSlots),
348 fSampleInfos(fNSlots)
349{
350}
351
352RLoopManager::RLoopManager(std::unique_ptr<RDataSource> ds, const ColumnNames_t &defaultBranches)
353 : fDefaultColumns(defaultBranches), fNSlots(RDFInternal::GetNSlots()),
354 fLoopType(ROOT::IsImplicitMTEnabled() ? ELoopType::kDataSourceMT : ELoopType::kDataSource),
355 fDataSource(std::move(ds)), fNewSampleNotifier(fNSlots), fSampleInfos(fNSlots)
356{
357 fDataSource->SetNSlots(fNSlots);
358}
359
360struct RSlotRAII {
362 unsigned int fSlot;
363 RSlotRAII(RSlotStack &slotStack) : fSlotStack(slotStack), fSlot(slotStack.GetSlot()) {}
364 ~RSlotRAII() { fSlotStack.ReturnSlot(fSlot); }
365};
366
367/// Run event loop with no source files, in parallel.
369{
370#ifdef R__USE_IMT
371 RSlotStack slotStack(fNSlots);
372 // Working with an empty tree.
373 // Evenly partition the entries according to fNSlots. Produce around 2 tasks per slot.
374 const auto nEntriesPerSlot = fNEmptyEntries / (fNSlots * 2);
375 auto remainder = fNEmptyEntries % (fNSlots * 2);
376 std::vector<std::pair<ULong64_t, ULong64_t>> entryRanges;
377 ULong64_t start = 0;
378 while (start < fNEmptyEntries) {
379 ULong64_t end = start + nEntriesPerSlot;
380 if (remainder > 0) {
381 ++end;
382 --remainder;
383 }
384 entryRanges.emplace_back(start, end);
385 start = end;
386 }
387
388 // Each task will generate a subrange of entries
389 auto genFunction = [this, &slotStack](const std::pair<ULong64_t, ULong64_t> &range) {
390 RSlotRAII slotRAII(slotStack);
391 auto slot = slotRAII.fSlot;
392 RCallCleanUpTask cleanup(*this, slot);
393 InitNodeSlots(nullptr, slot);
394 R__LOG_INFO(RDFLogChannel()) << LogRangeProcessing({"an empty source", range.first, range.second, slot});
395 try {
396 UpdateSampleInfo(slot, range);
397 for (auto currEntry = range.first; currEntry < range.second; ++currEntry) {
398 RunAndCheckFilters(slot, currEntry);
399 }
400 } catch (...) {
401 // Error might throw in experiment frameworks like CMSSW
402 std::cerr << "RDataFrame::Run: event loop was interrupted\n";
403 throw;
404 }
405 };
406
408 pool.Foreach(genFunction, entryRanges);
409
410#endif // not implemented otherwise
411}
412
413/// Run event loop with no source files, in sequence.
415{
416 InitNodeSlots(nullptr, 0);
417 R__LOG_INFO(RDFLogChannel()) << LogRangeProcessing({"an empty source", 0, fNEmptyEntries, 0u});
418 RCallCleanUpTask cleanup(*this);
419 try {
420 UpdateSampleInfo(/*slot*/0, {0, fNEmptyEntries});
421 for (ULong64_t currEntry = 0; currEntry < fNEmptyEntries && fNStopsReceived < fNChildren; ++currEntry) {
422 RunAndCheckFilters(0, currEntry);
423 }
424 } catch (...) {
425 std::cerr << "RDataFrame::Run: event loop was interrupted\n";
426 throw;
427 }
428}
429
430/// Run event loop over one or multiple ROOT files, in parallel.
432{
433#ifdef R__USE_IMT
434 RSlotStack slotStack(fNSlots);
435 const auto &entryList = fTree->GetEntryList() ? *fTree->GetEntryList() : TEntryList();
436 auto tp = std::make_unique<ROOT::TTreeProcessorMT>(*fTree, entryList, fNSlots);
437
438 std::atomic<ULong64_t> entryCount(0ull);
439
440 tp->Process([this, &slotStack, &entryCount](TTreeReader &r) -> void {
441 RSlotRAII slotRAII(slotStack);
442 auto slot = slotRAII.fSlot;
443 RCallCleanUpTask cleanup(*this, slot, &r);
444 InitNodeSlots(&r, slot);
445 R__LOG_INFO(RDFLogChannel()) << LogRangeProcessing(TreeDatasetLogInfo(r, slot));
446 const auto entryRange = r.GetEntriesRange(); // we trust TTreeProcessorMT to call SetEntriesRange
447 const auto nEntries = entryRange.second - entryRange.first;
448 auto count = entryCount.fetch_add(nEntries);
449 try {
450 // recursive call to check filters and conditionally execute actions
451 while (r.Next()) {
452 if (fNewSampleNotifier.CheckFlag(slot)) {
453 UpdateSampleInfo(slot, r);
454 }
455 RunAndCheckFilters(slot, count++);
456 }
457 } catch (...) {
458 std::cerr << "RDataFrame::Run: event loop was interrupted\n";
459 throw;
460 }
461 // fNStopsReceived < fNChildren is always true at the moment as we don't support event loop early quitting in
462 // multi-thread runs, but it costs nothing to be safe and future-proof in case we add support for that later.
463 if (r.GetEntryStatus() != TTreeReader::kEntryBeyondEnd && fNStopsReceived < fNChildren) {
464 // something went wrong in the TTreeReader event loop
465 throw std::runtime_error("An error was encountered while processing the data. TTreeReader status code is: " +
466 std::to_string(r.GetEntryStatus()));
467 }
468 });
469#endif // no-op otherwise (will not be called)
470}
471
472/// Run event loop over one or multiple ROOT files, in sequence.
474{
475 TTreeReader r(fTree.get(), fTree->GetEntryList());
476 if (0 == fTree->GetEntriesFast())
477 return;
478 RCallCleanUpTask cleanup(*this, 0u, &r);
479 InitNodeSlots(&r, 0);
480 R__LOG_INFO(RDFLogChannel()) << LogRangeProcessing(TreeDatasetLogInfo(r, 0u));
481
482 // recursive call to check filters and conditionally execute actions
483 // in the non-MT case processing can be stopped early by ranges, hence the check on fNStopsReceived
484 try {
485 while (r.Next() && fNStopsReceived < fNChildren) {
487 UpdateSampleInfo(/*slot*/0, r);
488 }
489 RunAndCheckFilters(0, r.GetCurrentEntry());
490 }
491 } catch (...) {
492 std::cerr << "RDataFrame::Run: event loop was interrupted\n";
493 throw;
494 }
495 if (r.GetEntryStatus() != TTreeReader::kEntryBeyondEnd && fNStopsReceived < fNChildren) {
496 // something went wrong in the TTreeReader event loop
497 throw std::runtime_error("An error was encountered while processing the data. TTreeReader status code is: " +
498 std::to_string(r.GetEntryStatus()));
499 }
500}
501
502/// Run event loop over data accessed through a DataSource, in sequence.
504{
505 assert(fDataSource != nullptr);
506 fDataSource->Initialise();
507 auto ranges = fDataSource->GetEntryRanges();
508 while (!ranges.empty() && fNStopsReceived < fNChildren) {
509 InitNodeSlots(nullptr, 0u);
510 fDataSource->InitSlot(0u, 0ull);
511 RCallCleanUpTask cleanup(*this);
512 try {
513 for (const auto &range : ranges) {
514 const auto start = range.first;
515 const auto end = range.second;
516 R__LOG_INFO(RDFLogChannel()) << LogRangeProcessing({fDataSource->GetLabel(), start, end, 0u});
517 for (auto entry = start; entry < end && fNStopsReceived < fNChildren; ++entry) {
518 if (fDataSource->SetEntry(0u, entry)) {
519 RunAndCheckFilters(0u, entry);
520 }
521 }
522 }
523 } catch (...) {
524 std::cerr << "RDataFrame::Run: event loop was interrupted\n";
525 throw;
526 }
527 fDataSource->FinaliseSlot(0u);
528 ranges = fDataSource->GetEntryRanges();
529 }
530 fDataSource->Finalise();
531}
532
533/// Run event loop over data accessed through a DataSource, in parallel.
535{
536#ifdef R__USE_IMT
537 assert(fDataSource != nullptr);
538 RSlotStack slotStack(fNSlots);
540
541 // Each task works on a subrange of entries
542 auto runOnRange = [this, &slotStack](const std::pair<ULong64_t, ULong64_t> &range) {
543 RSlotRAII slotRAII(slotStack);
544 const auto slot = slotRAII.fSlot;
545 InitNodeSlots(nullptr, slot);
546 RCallCleanUpTask cleanup(*this, slot);
547 fDataSource->InitSlot(slot, range.first);
548 const auto start = range.first;
549 const auto end = range.second;
550 R__LOG_INFO(RDFLogChannel()) << LogRangeProcessing({fDataSource->GetLabel(), start, end, slot});
551 try {
552 for (auto entry = start; entry < end; ++entry) {
553 if (fDataSource->SetEntry(slot, entry)) {
554 RunAndCheckFilters(slot, entry);
555 }
556 }
557 } catch (...) {
558 std::cerr << "RDataFrame::Run: event loop was interrupted\n";
559 throw;
560 }
561 fDataSource->FinaliseSlot(slot);
562 };
563
564 fDataSource->Initialise();
565 auto ranges = fDataSource->GetEntryRanges();
566 while (!ranges.empty()) {
567 pool.Foreach(runOnRange, ranges);
568 ranges = fDataSource->GetEntryRanges();
569 }
570 fDataSource->Finalise();
571#endif // not implemented otherwise (never called)
572}
573
574/// Execute actions and make sure named filters are called for each event.
575/// Named filters must be called even if the analysis logic would not require it, lest they report confusing results.
576void RLoopManager::RunAndCheckFilters(unsigned int slot, Long64_t entry)
577{
578 // data-block callbacks run before the rest of the graph
579 if (fNewSampleNotifier.CheckFlag(slot)) {
580 for (auto &callback : fSampleCallbacks) {
581 callback(slot, fSampleInfos[slot]);
582 }
584 }
585
586 for (auto &actionPtr : fBookedActions)
587 actionPtr->Run(slot, entry);
588 for (auto &namedFilterPtr : fBookedNamedFilters)
589 namedFilterPtr->CheckFilters(slot, entry);
590 for (auto &callback : fCallbacks)
591 callback(slot);
592}
593
594/// Build TTreeReaderValues for all nodes
595/// This method loops over all filters, actions and other booked objects and
596/// calls their `InitSlot` method, to get them ready for running a task.
598{
599 SetupSampleCallbacks(r, slot);
600 for (auto &ptr : fBookedActions)
601 ptr->InitSlot(r, slot);
602 for (auto &ptr : fBookedFilters)
603 ptr->InitSlot(r, slot);
604 for (auto &callback : fCallbacksOnce)
605 callback(slot);
606}
607
609 if (r != nullptr) {
610 // we need to set a notifier so that we run the callbacks every time we switch to a new TTree
611 // `PrependLink` inserts this notifier into the TTree/TChain's linked list of notifiers
612 fNewSampleNotifier.GetChainNotifyLink(slot).PrependLink(*r->GetTree());
613 }
614 // Whatever the data source, initially set the "new data block" flag:
615 // - for TChains, this ensures that we don't skip the first data block because
616 // the correct tree is already loaded
617 // - for RDataSources and empty sources, which currently don't have data blocks, this
618 // ensures that we run once per task
620}
621
622void RLoopManager::UpdateSampleInfo(unsigned int slot, const std::pair<ULong64_t, ULong64_t> &range) {
624 "Empty source, range: {" + std::to_string(range.first) + ", " + std::to_string(range.second) + "}", range);
625}
626
628 // one GetTree to retrieve the TChain, another to retrieve the underlying TTree
629 auto *tree = r.GetTree()->GetTree();
630 R__ASSERT(tree != nullptr);
631 const std::string treename = ROOT::Internal::TreeUtils::GetTreeFullPaths(*tree)[0];
632 auto *file = tree->GetCurrentFile();
633 const std::string fname = file != nullptr ? file->GetName() : "#inmemorytree#";
634
635
636 std::pair<Long64_t, Long64_t> range = r.GetEntriesRange();
637 R__ASSERT(range.first >= 0);
638 if (range.second == -1) {
639 range.second = tree->GetEntries(); // convert '-1', i.e. 'until the end', to the actual entry number
640 }
641
642 fSampleInfos[slot] = RSampleInfo(fname + "/" + treename, range);
643}
644
645/// Initialize all nodes of the functional graph before running the event loop.
646/// This method is called once per event-loop and performs generic initialization
647/// operations that do not depend on the specific processing slot (i.e. operations
648/// that are common for all threads).
650{
652 for (auto &filter : fBookedFilters)
653 filter->InitNode();
654 for (auto &range : fBookedRanges)
655 range->InitNode();
656 for (auto &ptr : fBookedActions)
657 ptr->Initialize();
658}
659
660/// Perform clean-up operations. To be called at the end of each event loop.
662{
663 fMustRunNamedFilters = false;
664
665 // forget RActions and detach TResultProxies
666 for (auto &ptr : fBookedActions)
667 ptr->Finalize();
668
669 fRunActions.insert(fRunActions.begin(), fBookedActions.begin(), fBookedActions.end());
670 fBookedActions.clear();
671
672 // reset children counts
673 fNChildren = 0;
674 fNStopsReceived = 0;
675 for (auto &ptr : fBookedFilters)
676 ptr->ResetChildrenCount();
677 for (auto &ptr : fBookedRanges)
678 ptr->ResetChildrenCount();
679
680 fCallbacks.clear();
681 fCallbacksOnce.clear();
682 fSampleCallbacks.clear();
683}
684
685/// Perform clean-up operations. To be called at the end of each task execution.
686void RLoopManager::CleanUpTask(TTreeReader *r, unsigned int slot)
687{
688 if (r != nullptr)
689 fNewSampleNotifier.GetChainNotifyLink(slot).RemoveLink(*r->GetTree());
690 for (auto &ptr : fBookedActions)
691 ptr->FinalizeSlot(slot);
692 for (auto &ptr : fBookedFilters)
693 ptr->FinaliseSlot(slot);
694}
695
696/// Add RDF nodes that require just-in-time compilation to the computation graph.
697/// This method also clears the contents of GetCodeToJit().
699{
700 // TODO this should be a read lock unless we find GetCodeToJit non-empty
702
703 const std::string code = std::move(GetCodeToJit());
704 if (code.empty()) {
705 R__LOG_INFO(RDFLogChannel()) << "Nothing to jit and execute.";
706 return;
707 }
708
710 s.Start();
711 RDFInternal::InterpreterCalc(code, "RLoopManager::Run");
712 s.Stop();
713 R__LOG_INFO(RDFLogChannel()) << "Just-in-time compilation phase completed"
714 << (s.RealTime() > 1e-3 ? " in " + std::to_string(s.RealTime()) + " seconds." : ".");
715}
716
717/// Trigger counting of number of children nodes for each node of the functional graph.
718/// This is done once before starting the event loop. Each action sends an `increase children count` signal
719/// upstream, which is propagated until RLoopManager. Each time a node receives the signal, in increments its
720/// children counter. Each node only propagates the signal once, even if it receives it multiple times.
721/// Named filters also send an `increase children count` signal, just like actions, as they always execute during
722/// the event loop so the graph branch they belong to must count as active even if it does not end in an action.
724{
725 for (auto &actionPtr : fBookedActions)
726 actionPtr->TriggerChildrenCount();
727 for (auto &namedFilterPtr : fBookedNamedFilters)
728 namedFilterPtr->TriggerChildrenCount();
729}
730
731/// Start the event loop with a different mechanism depending on IMT/no IMT, data source/no data source.
732/// Also perform a few setup and clean-up operations (jit actions if necessary, clear booked actions after the loop...).
734{
735 // Change value of TTree::GetMaxTreeSize only for this scope. Revert when #6640 will be solved.
736 MaxTreeSizeRAII ctxtmts;
737
738 R__LOG_INFO(RDFLogChannel()) << "Starting event loop number " << fNRuns << '.';
739
740 ThrowIfNSlotsChanged(GetNSlots());
741
742 Jit();
743
744 InitNodes();
745
747 s.Start();
748 switch (fLoopType) {
752 case ELoopType::kNoFiles: RunEmptySource(); break;
755 }
756 s.Stop();
757
758 CleanUpNodes();
759
760 fNRuns++;
761
762 R__LOG_INFO(RDFLogChannel()) << "Finished event loop number " << fNRuns - 1 << " (" << s.CpuTime() << "s CPU, "
763 << s.RealTime() << "s elapsed).";
764}
765
766/// Return the list of default columns -- empty if none was provided when constructing the RDataFrame
768{
769 return fDefaultColumns;
770}
771
773{
774 return fTree.get();
775}
776
778{
779 fBookedActions.emplace_back(actionPtr);
780}
781
783{
786}
787
789{
790 fBookedFilters.emplace_back(filterPtr);
791 if (filterPtr->HasName()) {
792 fBookedNamedFilters.emplace_back(filterPtr);
794 }
795}
796
798{
801}
802
804{
805 fBookedRanges.emplace_back(rangePtr);
806}
807
809{
811}
812
813// dummy call, end of recursive chain of calls
815{
816 return true;
817}
818
819/// Call `FillReport` on all booked filters
821{
822 for (const auto &fPtr : fBookedNamedFilters)
823 fPtr->FillReport(rep);
824}
825
826void RLoopManager::ToJitExec(const std::string &code) const
827{
829 GetCodeToJit().append(code);
830}
831
832void RLoopManager::RegisterCallback(ULong64_t everyNEvents, std::function<void(unsigned int)> &&f)
833{
834 if (everyNEvents == 0ull)
835 fCallbacksOnce.emplace_back(std::move(f), fNSlots);
836 else
837 fCallbacks.emplace_back(everyNEvents, std::move(f), fNSlots);
838}
839
840std::vector<std::string> RLoopManager::GetFiltersNames()
841{
842 std::vector<std::string> filters;
843 for (auto &filter : fBookedFilters) {
844 auto name = (filter->HasName() ? filter->GetName() : "Unnamed Filter");
845 filters.push_back(name);
846 }
847 return filters;
848}
849
850std::vector<RNodeBase *> RLoopManager::GetGraphEdges() const
851{
852 std::vector<RNodeBase *> nodes(fBookedFilters.size() + fBookedRanges.size());
853 auto it = std::copy(fBookedFilters.begin(), fBookedFilters.end(), nodes.begin());
854 std::copy(fBookedRanges.begin(), fBookedRanges.end(), it);
855 return nodes;
856}
857
858std::vector<RDFInternal::RActionBase *> RLoopManager::GetAllActions() const
859{
860 std::vector<RDFInternal::RActionBase *> actions(fBookedActions.size() + fRunActions.size());
861 auto it = std::copy(fBookedActions.begin(), fBookedActions.end(), actions.begin());
862 std::copy(fRunActions.begin(), fRunActions.end(), it);
863 return actions;
864}
865
866std::shared_ptr<ROOT::Internal::RDF::GraphDrawing::GraphNode> RLoopManager::GetGraph()
867{
868 std::string name;
869 if (fDataSource) {
870 name = fDataSource->GetLabel();
871 } else if (fTree) {
872 name = fTree->GetName();
873 } else {
874 name = std::to_string(fNEmptyEntries);
875 }
876
877 auto thisNode = std::make_shared<ROOT::Internal::RDF::GraphDrawing::GraphNode>(name);
878 thisNode->SetRoot();
879 thisNode->SetCounter(0);
880 return thisNode;
881}
882
883////////////////////////////////////////////////////////////////////////////
884/// Return all valid TTree::Branch names (caching results for subsequent calls).
885/// Never use fBranchNames directy, always request it through this method.
887{
888 if (fValidBranchNames.empty() && fTree) {
889 fValidBranchNames = RDFInternal::GetBranchNames(*fTree, /*allowRepetitions=*/true);
890 }
891 return fValidBranchNames;
892}
893
894bool RLoopManager::HasDSValuePtrs(const std::string &col) const
895{
896 return fDSValuePtrMap.find(col) != fDSValuePtrMap.end();
897}
898
899void RLoopManager::AddDSValuePtrs(const std::string &col, const std::vector<void *> ptrs)
900{
901 fDSValuePtrMap[col] = ptrs;
902}
903
905{
906 if (callback)
907 fSampleCallbacks.emplace_back(std::move(callback));
908}
void Class()
Definition: Class.C:29
ROOT::R::TRInterface & r
Definition: Object.C:4
#define R__LOG_INFO(...)
Definition: RLogger.hxx:364
#define b(i)
Definition: RSha256.hxx:100
#define f(i)
Definition: RSha256.hxx:104
#define e(i)
Definition: RSha256.hxx:103
long long Long64_t
Definition: RtypesCore.h:80
unsigned long long ULong64_t
Definition: RtypesCore.h:81
#define R__ASSERT(e)
Definition: TError.h:118
const char * filters[]
char name[80]
Definition: TGX11.cxx:110
R__EXTERN TVirtualMutex * gROOTMutex
Definition: TROOT.h:61
#define R__LOCKGUARD(mutex)
The head node of a RDF computation graph.
void UpdateSampleInfo(unsigned int slot, const std::pair< ULong64_t, ULong64_t > &range)
RLoopManager(TTree *tree, const ColumnNames_t &defaultBranches)
unsigned int fNRuns
Number of event loops run.
bool CheckFilters(unsigned int, Long64_t) final
void EvalChildrenCounts()
Trigger counting of number of children nodes for each node of the functional graph.
void CleanUpNodes()
Perform clean-up operations. To be called at the end of each event loop.
void RunEmptySource()
Run event loop with no source files, in sequence.
void Report(ROOT::RDF::RCutFlowReport &rep) const final
Call FillReport on all booked filters.
std::vector< RFilterBase * > fBookedNamedFilters
Contains a subset of fBookedFilters, i.e. only the named filters.
void RunEmptySourceMT()
Run event loop with no source files, in parallel.
void AddDSValuePtrs(const std::string &col, const std::vector< void * > ptrs)
const ColumnNames_t & GetBranchNames()
Return all valid TTree::Branch names (caching results for subsequent calls).
void ToJitExec(const std::string &) const
void AddSampleCallback(ROOT::RDF::SampleCallback_t &&callback)
std::vector< RDFInternal::RActionBase * > GetAllActions() const
Return all actions, either booked or already run.
std::vector< ROOT::RDF::RSampleInfo > fSampleInfos
std::shared_ptr< TTree > fTree
Shared pointer to the input TTree.
void RunTreeReader()
Run event loop over one or multiple ROOT files, in sequence.
std::vector< RDFInternal::RActionBase * > fRunActions
Non-owning pointers to actions already run.
void Run()
Start the event loop with a different mechanism depending on IMT/no IMT, data source/no data source.
std::vector< RRangeBase * > fBookedRanges
std::vector< ROOT::RDF::SampleCallback_t > fSampleCallbacks
Registered callbacks to call at the beginning of each "data block".
std::vector< std::string > ColumnNames_t
void RunAndCheckFilters(unsigned int slot, Long64_t entry)
Execute actions and make sure named filters are called for each event.
std::vector< RFilterBase * > fBookedFilters
std::vector< RDFInternal::RActionBase * > fBookedActions
Non-owning pointers to actions to be run.
std::vector< RDFInternal::RCallback > fCallbacks
Registered callbacks.
std::shared_ptr< ROOT::Internal::RDF::GraphDrawing::GraphNode > GetGraph()
const ELoopType fLoopType
The kind of event loop that is going to be run (e.g. on ROOT files, on no files)
void SetupSampleCallbacks(TTreeReader *r, unsigned int slot)
ColumnNames_t fValidBranchNames
Cache of the tree/chain branch names. Never access directy, always use GetBranchNames().
void CleanUpTask(TTreeReader *r, unsigned int slot)
Perform clean-up operations. To be called at the end of each task execution.
std::map< std::string, std::vector< void * > > fDSValuePtrMap
Registry of per-slot value pointers for booked data-source columns.
const ColumnNames_t & GetDefaultColumnNames() const
Return the list of default columns – empty if none was provided when constructing the RDataFrame.
std::vector< RNodeBase * > GetGraphEdges() const
Return all graph edges known to RLoopManager This includes Filters and Ranges but not Defines.
unsigned int GetNSlots() const
void RunDataSourceMT()
Run event loop over data accessed through a DataSource, in parallel.
bool HasDSValuePtrs(const std::string &col) const
std::vector< std::string > GetFiltersNames()
For each booked filter, returns either the name or "Unnamed Filter".
const std::unique_ptr< RDataSource > fDataSource
Owning pointer to a data-source object. Null if no data-source.
RDFInternal::RNewSampleNotifier fNewSampleNotifier
const ColumnNames_t fDefaultColumns
void Book(RDFInternal::RActionBase *actionPtr)
void InitNodeSlots(TTreeReader *r, unsigned int slot)
Build TTreeReaderValues for all nodes This method loops over all filters, actions and other booked ob...
std::vector< RDFInternal::ROneTimeCallback > fCallbacksOnce
Registered callbacks to invoke just once before running the loop.
void RegisterCallback(ULong64_t everyNEvents, std::function< void(unsigned int)> &&f)
void RunDataSource()
Run event loop over data accessed through a DataSource, in sequence.
void Jit()
Add RDF nodes that require just-in-time compilation to the computation graph.
void RunTreeProcessorMT()
Run event loop over one or multiple ROOT files, in parallel.
void Deregister(RDFInternal::RActionBase *actionPtr)
void InitNodes()
Initialize all nodes of the functional graph before running the event loop.
unsigned int fNStopsReceived
Number of times that a children node signaled to stop processing entries.
Definition: RNodeBase.hxx:45
unsigned int fNChildren
Number of nodes of the functional graph hanging from this object.
Definition: RNodeBase.hxx:44
bool CheckFlag(unsigned int slot) const
TNotifyLink< RNewSampleFlag > & GetChainNotifyLink(unsigned int slot)
This is an helper class to allow to pick a slot resorting to a map indexed by thread ids.
Definition: RSlotStack.hxx:26
void ReturnSlot(unsigned int slotNumber)
Definition: RSlotStack.cxx:23
This type represents a sample identifier, to be used in conjunction with RDataFrame features such as ...
Definition: RSampleInfo.hxx:32
This class provides a simple interface to execute the same task multiple times in parallel threads,...
void Foreach(F func, unsigned nTimes, unsigned nChunks=0)
Execute a function without arguments several times in parallel, dividing the execution in nChunks.
A Branch for the case of an object.
A TTree is a list of TBranches.
Definition: TBranch.h:89
TObjArray * GetListOfLeaves()
Definition: TBranch.h:243
A chain is a collection of files containing TTree objects.
Definition: TChain.h:33
A List of entry numbers in a TTree or TChain.
Definition: TEntryList.h:26
A TFriendElement TF describes a TTree object TF in a file.
A TLeaf describes individual elements of a TBranch See TBranch structure in TTree.
Definition: TLeaf.h:57
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
Mother of all ROOT objects.
Definition: TObject.h:37
Stopwatch class.
Definition: TStopwatch.h:28
A simple, robust and fast interface to read values from ROOT columnar datasets such as TTree,...
Definition: TTreeReader.h:44
@ kEntryBeyondEnd
last entry loop has reached its end
Definition: TTreeReader.h:133
A TTree represents a columnar dataset.
Definition: TTree.h:79
virtual TBranch * FindBranch(const char *name)
Return the branch that correspond to the path 'branchname', which can include the name of the tree or...
Definition: TTree.cxx:4810
virtual TBranch * GetBranch(const char *name)
Return pointer to the branch with the given name in this tree or its friends.
Definition: TTree.cxx:5257
static void SetMaxTreeSize(Long64_t maxsize=100000000000LL)
Set the maximum size in bytes of a Tree file (static function).
Definition: TTree.cxx:9147
virtual TObjArray * GetListOfBranches()
Definition: TTree.h:484
virtual TTree * GetTree() const
Definition: TTree.h:513
virtual TList * GetListOfFriends() const
Definition: TTree.h:486
virtual const char * GetFriendAlias(TTree *) const
If the 'tree' is a friend, this method returns its alias name.
Definition: TTree.cxx:6000
std::vector< std::string > GetTreeFullPaths(const TTree &tree)
Retrieve the full path(s) to a TTree or the trees in a TChain.
ROOT::Experimental::RLogChannel & RDFLogChannel()
Definition: RDFUtils.cxx:37
std::vector< std::string > GetBranchNames(TTree &t, bool allowDuplicates=true)
Get all the branches names, including the ones of the friend trees.
unsigned int GetNSlots()
Definition: RDFUtils.cxx:288
void Erase(const T &that, std::vector< T > &v)
Erase that element from vector v
Definition: Utils.hxx:187
Long64_t InterpreterCalc(const std::string &code, const std::string &context="")
Jit code in the interpreter with TInterpreter::Calc, throw in case of errors.
Definition: RDFUtils.cxx:332
std::vector< std::string > ColumnNames_t
Definition: Utils.hxx:35
std::function< void(unsigned int, const ROOT::RDF::RSampleInfo &)> SampleCallback_t
The type of a data-block callback, registered with a RDataFrame computation graph via e....
Definition: RSampleInfo.hxx:84
void function(const Char_t *name_, T fun, const Char_t *docstring=0)
Definition: RExports.h:150
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
Bool_t IsImplicitMTEnabled()
Returns true if the implicit multi-threading in ROOT is enabled.
Definition: TROOT.cxx:558
static constexpr double s
Definition: file.py:1
Definition: tree.py:1
static const char * what
Definition: stlLoader.cc:6
A RAII object that calls RLoopManager::CleanUpTask at destruction.
RCallCleanUpTask(RLoopManager &lm, unsigned int arg=0u, TTreeReader *reader=nullptr)
RSlotRAII(RSlotStack &slotStack)
RSlotStack & fSlotStack
unsigned int fSlot