Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
InterfaceUtils.hxx
Go to the documentation of this file.
1// Author: Enrico Guiraud, Danilo Piparo CERN 02/2018
2
3/*************************************************************************
4 * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *
5 * All rights reserved. *
6 * *
7 * For the licensing terms see $ROOTSYS/LICENSE. *
8 * For the list of contributors see $ROOTSYS/README/CREDITS. *
9 *************************************************************************/
10
11#ifndef ROOT_RDF_TINTERFACE_UTILS
12#define ROOT_RDF_TINTERFACE_UTILS
13
14#include <ROOT/RDF/RAction.hxx>
16#include <ROOT/RDF/ActionHelpers.hxx> // for BuildAction
19#include <ROOT/RDF/RDefine.hxx>
21#include <ROOT/RDF/RFilter.hxx>
22#include <ROOT/RDF/Utils.hxx>
28#include <string_view>
30#include <ROOT/TypeTraits.hxx>
31#include <TError.h> // gErrorIgnoreLevel
32#include <TH1.h>
33#include <TROOT.h> // IsImplicitMTEnabled
34
35#include <deque>
36#include <functional>
37#include <list>
38#include <memory>
39#include <string>
40#include <type_traits>
41#include <typeinfo>
42#include <vector>
43
44class TTree;
45namespace ROOT {
46namespace Detail {
47namespace RDF {
48class RNodeBase;
49}
50}
51namespace RDF {
52template<typename T, typename V>
53class RInterface;
55} // namespace RDF
56
57} // namespace ROOT
58
59/// \cond HIDDEN_SYMBOLS
60
61namespace ROOT {
62namespace Internal {
63namespace RDF {
64using namespace ROOT::Detail::RDF;
65using namespace ROOT::RDF;
66namespace TTraits = ROOT::TypeTraits;
67
68std::string DemangleTypeIdName(const std::type_info &typeInfo);
69
70ColumnNames_t
71ConvertRegexToColumns(const ColumnNames_t &colNames, std::string_view columnNameRegexp, std::string_view callerName);
72
73/// An helper object that sets and resets gErrorIgnoreLevel via RAII.
75private:
77
78public:
81};
82
83/****** BuildAction overloads *******/
84
85// clang-format off
86/// This namespace defines types to be used for tag dispatching in RInterface.
87namespace ActionTags {
88struct Histo1D{};
89struct Histo2D{};
90struct Histo3D{};
91struct HistoND{};
92struct HistoNSparseD{};
93struct Graph{};
94struct GraphAsymmErrors{};
95struct Profile1D{};
96struct Profile2D{};
97struct Min{};
98struct Max{};
99struct Sum{};
100struct Mean{};
101struct Fill{};
102struct StdDev{};
103struct Display{};
104struct Snapshot{};
105struct Book{};
106}
107// clang-format on
108
109template <typename T, bool ISV6HISTO = std::is_base_of<TH1, std::decay_t<T>>::value>
110struct HistoUtils {
111 static bool HasAxisLimits(T &h)
112 {
113 auto xaxis = h.GetXaxis();
114 return !(xaxis->GetXmin() == 0. && xaxis->GetXmax() == 0.);
115 }
116};
117
118template <typename T>
119struct HistoUtils<T, false> {
120 static bool HasAxisLimits(T &) { return true; }
121};
122
123// Generic filling (covers Histo2D, HistoND, HistoNSparseD, Profile1D and Profile2D actions, with and without weights)
124template <typename... ColTypes, typename ActionTag, typename ActionResultType, typename PrevNodeType>
125std::unique_ptr<RActionBase>
126BuildAction(const ColumnNames_t &bl, const std::shared_ptr<ActionResultType> &h, const unsigned int nSlots,
127 std::shared_ptr<PrevNodeType> prevNode, ActionTag, const RColumnRegister &colRegister)
128{
130 using Action_t = RAction<Helper_t, PrevNodeType, TTraits::TypeList<ColTypes...>>;
131 return std::make_unique<Action_t>(Helper_t(h, nSlots), bl, std::move(prevNode), colRegister);
132}
133
134// Histo1D filling (must handle the special case of distinguishing FillHelper and BufferedFillHelper
135template <typename... ColTypes, typename PrevNodeType>
136std::unique_ptr<RActionBase>
137BuildAction(const ColumnNames_t &bl, const std::shared_ptr<::TH1D> &h, const unsigned int nSlots,
138 std::shared_ptr<PrevNodeType> prevNode, ActionTags::Histo1D, const RColumnRegister &colRegister)
139{
141
144 using Action_t = RAction<Helper_t, PrevNodeType, TTraits::TypeList<ColTypes...>>;
145 return std::make_unique<Action_t>(Helper_t(h, nSlots), bl, std::move(prevNode), colRegister);
146 } else {
148 using Action_t = RAction<Helper_t, PrevNodeType, TTraits::TypeList<ColTypes...>>;
149 return std::make_unique<Action_t>(Helper_t(h, nSlots), bl, std::move(prevNode), colRegister);
150 }
151}
152
153// Action for Histo3D, where thread safe filling might be supported to save memory
154template <typename... ColTypes, typename ActionResultType, typename PrevNodeType>
155std::unique_ptr<RActionBase>
156BuildAction(const ColumnNames_t &bl, const std::shared_ptr<ActionResultType> &h, const unsigned int nSlots,
157 std::shared_ptr<PrevNodeType> prevNode, ActionTags::Histo3D, const RColumnRegister &colRegister)
158{
159 if (RDFInternal::NThreadPerTH3() <= 1 || nSlots == 1) {
161 using Action_t = RAction<Helper_t, PrevNodeType, TTraits::TypeList<ColTypes...>>;
162 return std::make_unique<Action_t>(Helper_t(h, nSlots), bl, std::move(prevNode), colRegister);
163 } else {
165 using Action_t = RAction<Helper_t, PrevNodeType, TTraits::TypeList<ColTypes...>>;
166 if constexpr (sizeof...(ColTypes) > 3) {
167 h->Sumw2();
168 }
169 const auto histoSlots = std::max(nSlots / RDFInternal::NThreadPerTH3(), 1u);
170 return std::make_unique<Action_t>(Helper_t(h, histoSlots), bl, std::move(prevNode), colRegister);
171 }
172}
173
174template <typename... ColTypes, typename PrevNodeType>
175std::unique_ptr<RActionBase>
176BuildAction(const ColumnNames_t &bl, const std::shared_ptr<TGraph> &g, const unsigned int nSlots,
177 std::shared_ptr<PrevNodeType> prevNode, ActionTags::Graph, const RColumnRegister &colRegister)
178{
180 using Action_t = RAction<Helper_t, PrevNodeType, TTraits::TypeList<ColTypes...>>;
181 return std::make_unique<Action_t>(Helper_t(g, nSlots), bl, std::move(prevNode), colRegister);
182}
183
184template <typename... ColTypes, typename PrevNodeType>
185std::unique_ptr<RActionBase>
186BuildAction(const ColumnNames_t &bl, const std::shared_ptr<TGraphAsymmErrors> &g, const unsigned int nSlots,
187 std::shared_ptr<PrevNodeType> prevNode, ActionTags::GraphAsymmErrors, const RColumnRegister &colRegister)
188{
190 using Action_t = RAction<Helper_t, PrevNodeType, TTraits::TypeList<ColTypes...>>;
191 return std::make_unique<Action_t>(Helper_t(g, nSlots), bl, std::move(prevNode), colRegister);
192}
193
194// Min action
195template <typename ColType, typename PrevNodeType, typename ActionResultType>
196std::unique_ptr<RActionBase>
197BuildAction(const ColumnNames_t &bl, const std::shared_ptr<ActionResultType> &minV, const unsigned int nSlots,
198 std::shared_ptr<PrevNodeType> prevNode, ActionTags::Min, const RColumnRegister &colRegister)
199{
202 return std::make_unique<Action_t>(Helper_t(minV, nSlots), bl, std::move(prevNode), colRegister);
203}
204
205// Max action
206template <typename ColType, typename PrevNodeType, typename ActionResultType>
207std::unique_ptr<RActionBase>
208BuildAction(const ColumnNames_t &bl, const std::shared_ptr<ActionResultType> &maxV, const unsigned int nSlots,
209 std::shared_ptr<PrevNodeType> prevNode, ActionTags::Max, const RColumnRegister &colRegister)
210{
213 return std::make_unique<Action_t>(Helper_t(maxV, nSlots), bl, std::move(prevNode), colRegister);
214}
215
216// Sum action
217template <typename ColType, typename PrevNodeType, typename ActionResultType>
218std::unique_ptr<RActionBase>
219BuildAction(const ColumnNames_t &bl, const std::shared_ptr<ActionResultType> &sumV, const unsigned int nSlots,
220 std::shared_ptr<PrevNodeType> prevNode, ActionTags::Sum, const RColumnRegister &colRegister)
221{
224 return std::make_unique<Action_t>(Helper_t(sumV, nSlots), bl, std::move(prevNode), colRegister);
225}
226
227// Mean action
228template <typename ColType, typename PrevNodeType>
229std::unique_ptr<RActionBase>
230BuildAction(const ColumnNames_t &bl, const std::shared_ptr<double> &meanV, const unsigned int nSlots,
231 std::shared_ptr<PrevNodeType> prevNode, ActionTags::Mean, const RColumnRegister &colRegister)
232{
233 using Helper_t = MeanHelper;
235 return std::make_unique<Action_t>(Helper_t(meanV, nSlots), bl, std::move(prevNode), colRegister);
236}
237
238// Standard Deviation action
239template <typename ColType, typename PrevNodeType>
240std::unique_ptr<RActionBase>
241BuildAction(const ColumnNames_t &bl, const std::shared_ptr<double> &stdDeviationV, const unsigned int nSlots,
242 std::shared_ptr<PrevNodeType> prevNode, ActionTags::StdDev, const RColumnRegister &colRegister)
243{
244 using Helper_t = StdDevHelper;
246 return std::make_unique<Action_t>(Helper_t(stdDeviationV, nSlots), bl, prevNode, colRegister);
247}
248
249using displayHelperArgs_t = std::pair<size_t, std::shared_ptr<ROOT::RDF::RDisplay>>;
250
251// Display action
252template <typename... ColTypes, typename PrevNodeType>
253std::unique_ptr<RActionBase>
254BuildAction(const ColumnNames_t &bl, const std::shared_ptr<displayHelperArgs_t> &helperArgs, const unsigned int,
255 std::shared_ptr<PrevNodeType> prevNode, ActionTags::Display, const RColumnRegister &colRegister)
256{
258 using Action_t = RAction<Helper_t, PrevNodeType, TTraits::TypeList<ColTypes...>>;
259 return std::make_unique<Action_t>(Helper_t(helperArgs->first, helperArgs->second, prevNode), bl, prevNode,
261}
262
263struct SnapshotHelperArgs {
264 std::string fFileName;
265 std::string fDirName;
266 std::string fTreeName;
267 std::vector<std::string> fOutputColNames;
269 ROOT::Detail::RDF::RLoopManager *fOutputLoopManager;
270 ROOT::Detail::RDF::RLoopManager *fInputLoopManager;
271 bool fToNTuple;
272 bool fIncludeVariations;
273};
274
275template <typename PrevNodeType>
276std::unique_ptr<RActionBase>
277BuildAction(const ColumnNames_t &colNames, const std::shared_ptr<SnapshotHelperArgs> &snapHelperArgs,
278 const unsigned int nSlots, std::shared_ptr<PrevNodeType> prevNode, const RColumnRegister &colRegister,
279 const std::vector<const std::type_info *> &colTypeIDs)
280{
281 const auto &filename = snapHelperArgs->fFileName;
282 const auto &dirname = snapHelperArgs->fDirName;
283 const auto &treename = snapHelperArgs->fTreeName;
284 const auto &outputColNames = snapHelperArgs->fOutputColNames;
285 const auto &options = snapHelperArgs->fOptions;
286 const auto &outputLM = snapHelperArgs->fOutputLoopManager;
287 const auto &inputLM = snapHelperArgs->fInputLoopManager;
288
289 auto sz = colNames.size();
290 std::vector<bool> isDefine(sz);
291 for (auto i = 0u; i < sz; ++i)
292 isDefine[i] = colRegister.IsDefineOrAlias(colNames[i]);
293
294 std::unique_ptr<RActionBase> actionPtr;
295 if (snapHelperArgs->fToNTuple) {
296 // We use the same helper for single- and multi-thread snapshot.
297 using Helper_t = UntypedSnapshotRNTupleHelper;
299
302 colNames, colTypeIDs, prevNode, colRegister));
303 } else {
305 // single-thread snapshot
306 if (snapHelperArgs->fIncludeVariations) {
307 using Helper_t = SnapshotHelperWithVariations;
310 std::move(isDefine), outputLM, inputLM, colTypeIDs),
311 colNames, colTypeIDs, prevNode, colRegister));
312 } else {
313 using Helper_t = UntypedSnapshotTTreeHelper;
316 std::move(isDefine), outputLM, inputLM, colTypeIDs),
317 colNames, colTypeIDs, prevNode, colRegister));
318 }
319 } else {
320 if (snapHelperArgs->fIncludeVariations) {
321 throw std::invalid_argument("Multi-threaded snapshot with variations is not supported yet.");
322 }
323 // multi-thread snapshot
324 using Helper_t = UntypedSnapshotTTreeHelperMT;
327 std::move(isDefine), outputLM, inputLM, colTypeIDs),
328 colNames, colTypeIDs, prevNode, colRegister));
329 }
330 }
331
332 return actionPtr;
333}
334
335// Book with custom helper type
336template <typename... ColTypes, typename PrevNodeType, typename Helper_t>
337std::unique_ptr<RActionBase>
338BuildAction(const ColumnNames_t &bl, const std::shared_ptr<Helper_t> &h, const unsigned int /*nSlots*/,
339 std::shared_ptr<PrevNodeType> prevNode, ActionTags::Book, const RColumnRegister &colRegister)
340{
341 using Action_t = RAction<Helper_t, PrevNodeType, TTraits::TypeList<ColTypes...>>;
342 return std::make_unique<Action_t>(Helper_t(std::move(*h)), bl, std::move(prevNode), colRegister);
343}
344
345/****** end BuildAndBook ******/
346
347template <typename Filter>
348void CheckFilter(Filter &)
349{
350 using FilterRet_t = typename RDF::CallableTraits<Filter>::ret_type;
351 static_assert(std::is_convertible<FilterRet_t, bool>::value,
352 "filter expression returns a type that is not convertible to bool");
353}
354
355ColumnNames_t FilterArraySizeColNames(const ColumnNames_t &columnNames, const std::string &action);
356
357void CheckValidCppVarName(std::string_view var, const std::string &where);
358
359void CheckForRedefinition(const std::string &where, std::string_view definedCol, const RColumnRegister &colRegister,
360 const ColumnNames_t &dataSourceColumns);
361
362void CheckForDefinition(const std::string &where, std::string_view definedColView, const RColumnRegister &colRegister,
363 const ColumnNames_t &dataSourceColumns);
364
365void CheckForNoVariations(const std::string &where, std::string_view definedColView,
366 const RColumnRegister &colRegister);
367
368std::string PrettyPrintAddr(const void *const addr);
369
370std::shared_ptr<RJittedFilter> BookFilterJit(std::shared_ptr<RNodeBase> *prevNodeOnHeap, std::string_view name,
371 std::string_view expression, const RColumnRegister &colRegister,
372 TTree *tree, RDataSource *ds);
373
374std::shared_ptr<RJittedDefine> BookDefineJit(std::string_view name, std::string_view expression, RLoopManager &lm,
375 RDataSource *ds, const RColumnRegister &colRegister,
376 std::shared_ptr<RNodeBase> *prevNodeOnHeap);
377
378std::shared_ptr<RJittedDefine> BookDefinePerSampleJit(std::string_view name, std::string_view expression,
379 RLoopManager &lm, const RColumnRegister &colRegister,
380 std::shared_ptr<RNodeBase> *upcastNodeOnHeap);
381
382std::shared_ptr<RJittedVariation>
383BookVariationJit(const std::vector<std::string> &colNames, std::string_view variationName,
384 const std::vector<std::string> &variationTags, std::string_view expression, RLoopManager &lm,
385 RDataSource *ds, const RColumnRegister &colRegister, std::shared_ptr<RNodeBase> *upcastNodeOnHeap,
386 bool isSingleColumn);
387
388std::string JitBuildAction(const ColumnNames_t &bl, std::shared_ptr<RDFDetail::RNodeBase> *prevNode,
389 const std::type_info &art, const std::type_info &at, void *rOnHeap, TTree *tree,
390 const unsigned int nSlots, const RColumnRegister &colRegister, RDataSource *ds,
391 std::weak_ptr<RJittedAction> *jittedActionOnHeap, const bool vector2RVec = true);
392
393// Allocate a weak_ptr on the heap, return a pointer to it. The user is responsible for deleting this weak_ptr.
394// This function is meant to be used by RInterface's methods that book code for jitting.
395// The problem it solves is that we generate code to be lazily jitted with the addresses of certain objects in them,
396// and we need to check those objects are still alive when the generated code is finally jitted and executed.
397// So we pass addresses to weak_ptrs allocated on the heap to the jitted code, which is then responsible for
398// the deletion of the weak_ptr object.
399template <typename T>
400std::weak_ptr<T> *MakeWeakOnHeap(const std::shared_ptr<T> &shPtr)
401{
402 return new std::weak_ptr<T>(shPtr);
403}
404
405// Same as MakeWeakOnHeap, but create a shared_ptr that makes sure the object is definitely kept alive.
406template <typename T>
407std::shared_ptr<T> *MakeSharedOnHeap(const std::shared_ptr<T> &shPtr)
408{
409 return new std::shared_ptr<T>(shPtr);
410}
411
412bool AtLeastOneEmptyString(const std::vector<std::string_view> strings);
413
414/// Take a shared_ptr<AnyNodeType> and return a shared_ptr<RNodeBase>.
415/// This works for RLoopManager nodes as well as filters and ranges.
416std::shared_ptr<RNodeBase> UpcastNode(std::shared_ptr<RNodeBase> ptr);
417
418ColumnNames_t GetValidatedColumnNames(RLoopManager &lm, const unsigned int nColumns, const ColumnNames_t &columns,
419 const RColumnRegister &validDefines, RDataSource *ds);
420
421std::vector<std::string> GetValidatedArgTypes(const ColumnNames_t &colNames, const RColumnRegister &colRegister,
422 TTree *tree, RDataSource *ds, const std::string &context,
423 bool vector2RVec);
424
425template <typename T>
426void AddDSColumnsHelper(const std::string &colName, RLoopManager &lm, RDataSource &ds, RColumnRegister &colRegister)
427{
428
429 if (colRegister.IsDefineOrAlias(colName))
430 return;
431
432 if (lm.HasDataSourceColumnReaders(colName, typeid(T)))
433 return;
434
435 if (!ds.HasColumn(colName) &&
436 lm.GetSuppressErrorsForMissingBranches().find(colName) == lm.GetSuppressErrorsForMissingBranches().end())
437 return;
438
439 const auto nSlots = lm.GetNSlots();
440 std::vector<std::unique_ptr<RColumnReaderBase>> colReaders;
441 colReaders.reserve(nSlots);
442
443 const auto valuePtrs = ds.GetColumnReaders<T>(colName);
444 if (!valuePtrs.empty()) { // we are using the old GetColumnReaders mechanism in this RDataSource
445 for (auto *ptr : valuePtrs)
446 colReaders.emplace_back(new RDSColumnReader<T>(ptr));
447
448 } else { // using the new GetColumnReaders mechanism
449 // TODO consider changing the interface so we return all of these for all slots in one go
450 for (auto slot = 0u; slot < lm.GetNSlots(); ++slot)
451 colReaders.emplace_back(
452 ROOT::Internal::RDF::CreateColumnReader(ds, slot, colName, typeid(T), /*treeReader*/ nullptr));
453 }
454
455 lm.AddDataSourceColumnReaders(colName, std::move(colReaders), typeid(T));
456}
457
458/// Take list of column names that must be defined, current map of custom columns, current list of defined column names,
459/// and return a new map of custom columns (with the new datasource columns added to it)
460template <typename... ColumnTypes>
461void AddDSColumns(const std::vector<std::string> &requiredCols, RLoopManager &lm, RDataSource &ds,
463{
464 // hack to expand a template parameter pack without c++17 fold expressions.
465 using expander = int[];
466 int i = 0;
468}
469
470void AddDSColumns(const std::vector<std::string> &requiredCols, ROOT::Detail::RDF::RLoopManager &lm,
471 ROOT::RDF::RDataSource &ds, const std::vector<const std::type_info *> &colTypeIDs,
473
474// this function is meant to be called by the jitted code generated by BookFilterJit
475template <typename F, typename PrevNode>
476void JitFilterHelper(F &&f, const char **colsPtr, std::size_t colsSize, std::string_view name,
477 std::weak_ptr<RJittedFilter> *wkJittedFilter, std::shared_ptr<PrevNode> *prevNodeOnHeap,
478 RColumnRegister *colRegister) noexcept
479{
480 if (wkJittedFilter->expired()) {
481 // The branch of the computation graph that needed this jitted code went out of scope between the type
482 // jitting was booked and the time jitting actually happened. Nothing to do other than cleaning up.
483 delete wkJittedFilter;
484 delete colRegister;
485 delete prevNodeOnHeap;
486 return;
487 }
488
489 const ColumnNames_t cols(colsPtr, colsPtr + colsSize);
490 delete[] colsPtr;
491
492 const auto jittedFilter = wkJittedFilter->lock();
493
494 // mock Filter logic -- validity checks and Define-ition of RDataSource columns
495 using Callable_t = std::decay_t<F>;
497 using ColTypes_t = typename TTraits::CallableTraits<Callable_t>::arg_types;
498 constexpr auto nColumns = ColTypes_t::list_size;
499 CheckFilter(f);
500
501 auto &lm = *jittedFilter->GetLoopManagerUnchecked(); // RLoopManager must exist at this time
502 auto ds = lm.GetDataSource();
503
504 if (ds != nullptr)
506
507 jittedFilter->SetFilter(
508 std::unique_ptr<RFilterBase>(new F_t(std::forward<F>(f), cols, *prevNodeOnHeap, *colRegister, name)));
509 // colRegister points to the columns structure in the heap, created before the jitted call so that the jitter can
510 // share data after it has lazily compiled the code. Here the data has been used and the memory can be freed.
511 delete colRegister;
512 delete prevNodeOnHeap;
513 delete wkJittedFilter;
514}
515
516namespace DefineTypes {
517struct RDefineTag {};
518struct RDefinePerSampleTag {};
519}
520
521template <typename F>
522auto MakeDefineNode(DefineTypes::RDefineTag, std::string_view name, std::string_view dummyType, F &&f,
523 const ColumnNames_t &cols, RColumnRegister &colRegister, RLoopManager &lm)
524{
525 return std::unique_ptr<RDefineBase>(new RDefine<std::decay_t<F>, ExtraArgsForDefine::None>(
526 name, dummyType, std::forward<F>(f), cols, colRegister, lm));
527}
528
529template <typename F>
530auto MakeDefineNode(DefineTypes::RDefinePerSampleTag, std::string_view name, std::string_view dummyType, F &&f,
531 const ColumnNames_t &, RColumnRegister &, RLoopManager &lm)
532{
533 return std::unique_ptr<RDefineBase>(
534 new RDefinePerSample<std::decay_t<F>>(name, dummyType, std::forward<F>(f), lm));
535}
536
537// Build a RDefine or a RDefinePerSample object and attach it to an existing RJittedDefine
538// This function is meant to be called by jitted code right before starting the event loop.
539// If colsPtr is null, build a RDefinePerSample (it has no input columns), otherwise a RDefine.
540template <typename RDefineTypeTag, typename F>
541void JitDefineHelper(F &&f, const char **colsPtr, std::size_t colsSize, std::string_view name, RLoopManager *lm,
542 std::weak_ptr<RJittedDefine> *wkJittedDefine, RColumnRegister *colRegister,
543 std::shared_ptr<RNodeBase> *prevNodeOnHeap) noexcept
544{
545 // a helper to delete objects allocated before jitting, so that the jitter can share data with lazily jitted code
546 auto doDeletes = [&] {
547 delete wkJittedDefine;
548 delete colRegister;
549 delete prevNodeOnHeap;
550 delete[] colsPtr;
551 };
552
553 if (wkJittedDefine->expired()) {
554 // The branch of the computation graph that needed this jitted code went out of scope between the type
555 // jitting was booked and the time jitting actually happened. Nothing to do other than cleaning up.
556 doDeletes();
557 return;
558 }
559
560 const ColumnNames_t cols(colsPtr, colsPtr + colsSize);
561
562 auto jittedDefine = wkJittedDefine->lock();
563
564 using Callable_t = std::decay_t<F>;
565 using ColTypes_t = typename TTraits::CallableTraits<Callable_t>::arg_types;
566
567 auto ds = lm->GetDataSource();
568 if (ds != nullptr && colsPtr)
570
571 // will never actually be used (trumped by jittedDefine->GetTypeName()), but we set it to something meaningful
572 // to help devs debugging
573 const auto dummyType = "jittedCol_t";
574 // use unique_ptr<RDefineBase> instead of make_unique<NewCol_t> to reduce jit/compile-times
575 std::unique_ptr<RDefineBase> newCol{
576 MakeDefineNode(RDefineTypeTag{}, name, dummyType, std::forward<F>(f), cols, *colRegister, *lm)};
577 jittedDefine->SetDefine(std::move(newCol));
578
579 doDeletes();
580}
581
582template <bool IsSingleColumn, typename F>
583void JitVariationHelper(F &&f, const char **colsPtr, std::size_t colsSize, const char **variedCols,
584 std::size_t variedColsSize, const char **variationTags, std::size_t variationTagsSize,
585 std::string_view variationName, RLoopManager *lm,
586 std::weak_ptr<RJittedVariation> *wkJittedVariation, RColumnRegister *colRegister,
587 std::shared_ptr<RNodeBase> *prevNodeOnHeap) noexcept
588{
589 // a helper to delete objects allocated before jitting, so that the jitter can share data with lazily jitted code
590 auto doDeletes = [&] {
591 delete[] colsPtr;
592 delete[] variedCols;
593 delete[] variationTags;
594
595 delete wkJittedVariation;
596 delete colRegister;
597 delete prevNodeOnHeap;
598 };
599
600 if (wkJittedVariation->expired()) {
601 // The branch of the computation graph that needed this jitted variation went out of scope between the type
602 // jitting was booked and the time jitting actually happened. Nothing to do other than cleaning up.
603 doDeletes();
604 return;
605 }
606
607 const ColumnNames_t inputColNames(colsPtr, colsPtr + colsSize);
608 std::vector<std::string> variedColNames(variedCols, variedCols + variedColsSize);
609 std::vector<std::string> tags(variationTags, variationTags + variationTagsSize);
610
611 auto jittedVariation = wkJittedVariation->lock();
612
613 using Callable_t = std::decay_t<F>;
614 using ColTypes_t = typename TTraits::CallableTraits<Callable_t>::arg_types;
615
616 auto ds = lm->GetDataSource();
617 if (ds != nullptr)
619
620 // use unique_ptr<RDefineBase> instead of make_unique<NewCol_t> to reduce jit/compile-times
621 std::unique_ptr<RVariationBase> newVariation{new RVariation<std::decay_t<F>, IsSingleColumn>(
622 std::move(variedColNames), variationName, std::forward<F>(f), std::move(tags), jittedVariation->GetTypeName(),
624 jittedVariation->SetVariation(std::move(newVariation));
625
626 doDeletes();
627}
628
629/// Convenience function invoked by jitted code to build action nodes at runtime
630template <typename ActionTag, typename... ColTypes, typename PrevNodeType, typename HelperArgType>
631void CallBuildAction(std::shared_ptr<PrevNodeType> *prevNodeOnHeap, const char **colsPtr, std::size_t colsSize,
632 const unsigned int nSlots, std::shared_ptr<HelperArgType> *helperArgOnHeap,
633 std::weak_ptr<RJittedAction> *wkJittedActionOnHeap, RColumnRegister *colRegister) noexcept
634{
635 // a helper to delete objects allocated before jitting, so that the jitter can share data with lazily jitted code
636 auto doDeletes = [&] {
637 delete[] colsPtr;
638 delete helperArgOnHeap;
640 // colRegister must be deleted before prevNodeOnHeap because their dtor needs the RLoopManager to be alive
641 // and prevNodeOnHeap is what keeps it alive if the rest of the computation graph is already out of scope
642 delete colRegister;
643 delete prevNodeOnHeap;
644 };
645
646 if (wkJittedActionOnHeap->expired()) {
647 // The branch of the computation graph that needed this jitted variation went out of scope between the type
648 // jitting was booked and the time jitting actually happened. Nothing to do other than cleaning up.
649 doDeletes();
650 return;
651 }
652
653 const ColumnNames_t cols(colsPtr, colsPtr + colsSize);
654
656
657 // if we are here it means we are jitting, if we are jitting the loop manager must be alive
659 auto &loopManager = *prevNodePtr->GetLoopManagerUnchecked();
660 using ColTypes_t = TypeList<ColTypes...>;
661 constexpr auto nColumns = ColTypes_t::list_size;
662 auto ds = loopManager.GetDataSource();
663 if (ds != nullptr)
665
666 auto actionPtr = BuildAction<ColTypes...>(cols, std::move(*helperArgOnHeap), nSlots, std::move(prevNodePtr),
668 jittedActionOnHeap->SetAction(std::move(actionPtr));
669
670 doDeletes();
671}
672
673/// The contained `type` alias is `double` if `T == RInferredType`, `U` if `T == std::container<U>`, `T` otherwise.
674template <typename T, bool Container = IsDataContainer<T>::value && !std::is_same<T, std::string>::value>
675struct RMinReturnType {
676 using type = T;
677};
678
679template <>
681 using type = double;
682};
683
684template <typename T>
685struct RMinReturnType<T, true> {
686 using type = TTraits::TakeFirstParameter_t<T>;
687};
688
689// return wrapper around f that prepends an `unsigned int slot` parameter
690template <typename R, typename F, typename... Args>
691std::function<R(unsigned int, Args...)> AddSlotParameter(F &f, TypeList<Args...>)
692{
693 return [f](unsigned int, Args... a) mutable -> R { return f(a...); };
694}
695
696template <typename ColType, typename... Rest>
697struct RNeedJittingHelper {
698 static constexpr bool value = RNeedJittingHelper<Rest...>::value;
699};
700
701template <typename... Rest>
703 static constexpr bool value = true;
704};
705
706template <typename T>
707struct RNeedJittingHelper<T> {
708 static constexpr bool value = false;
709};
710
711template <>
713 static constexpr bool value = true;
714};
715
716template <typename ...ColTypes>
717struct RNeedJitting {
718 static constexpr bool value = RNeedJittingHelper<ColTypes...>::value;
719};
720
721template <>
722struct RNeedJitting<> {
723 static constexpr bool value = false;
724};
725
726///////////////////////////////////////////////////////////////////////////////
727/// Check preconditions for RInterface::Aggregate:
728/// - the aggregator callable must have signature `U(U,T)` or `void(U&,T)`.
729/// - the merge callable must have signature `U(U,U)` or `void(std::vector<U>&)`
730template <typename R, typename Merge, typename U, typename T, typename decayedU = std::decay_t<U>,
731 typename mergeArgsNoDecay_t = typename CallableTraits<Merge>::arg_types_nodecay,
732 typename mergeArgs_t = typename CallableTraits<Merge>::arg_types,
733 typename mergeRet_t = typename CallableTraits<Merge>::ret_type>
735{
736 constexpr bool isAggregatorOk =
737 (std::is_same<R, decayedU>::value) || (std::is_same<R, void>::value && std::is_lvalue_reference<U>::value);
738 static_assert(isAggregatorOk, "aggregator function must have signature `U(U,T)` or `void(U&,T)`");
739 constexpr bool isMergeOk =
740 (std::is_same<TypeList<decayedU, decayedU>, mergeArgs_t>::value && std::is_same<decayedU, mergeRet_t>::value) ||
741 (std::is_same<TypeList<std::vector<decayedU> &>, mergeArgsNoDecay_t>::value &&
742 std::is_same<void, mergeRet_t>::value);
743 static_assert(isMergeOk, "merge function must have signature `U(U,U)` or `void(std::vector<U>&)`");
744}
745
746///////////////////////////////////////////////////////////////////////////////
747/// This overload of CheckAggregate is called when the aggregator takes more than two arguments
748template <typename R, typename T>
749void CheckAggregate(T)
750{
751 static_assert(sizeof(T) == 0, "aggregator function must take exactly two arguments");
752}
753
754///////////////////////////////////////////////////////////////////////////////
755/// Check as many template parameters were passed as the number of column names, throw if this is not the case.
756void CheckTypesAndPars(unsigned int nTemplateParams, unsigned int nColumnNames);
757
758/// Return local BranchNames or default BranchNames according to which one should be used
759const ColumnNames_t SelectColumns(unsigned int nArgs, const ColumnNames_t &bl, const ColumnNames_t &defBl);
760
761/// Check whether column names refer to a valid branch of a TTree or have been `Define`d. Return invalid column names.
762ColumnNames_t FindUnknownColumns(const ColumnNames_t &requiredCols, const RColumnRegister &definedCols,
763 const ColumnNames_t &dataSourceColumns);
764
765/// Returns the list of Filters defined in the whole graph
766std::vector<std::string> GetFilterNames(const std::shared_ptr<RLoopManager> &loopManager);
767
768/// Returns the list of Filters defined in the branch
769template <typename NodeType>
770std::vector<std::string> GetFilterNames(const std::shared_ptr<NodeType> &node)
771{
772 std::vector<std::string> filterNames;
773 node->AddFilterName(filterNames);
774 return filterNames;
775}
776
777struct ParsedTreePath {
778 std::string fTreeName;
779 std::string fDirName;
780};
781
783
784// Check if a condition is true for all types
785template <bool...>
786struct TBoolPack;
787
788template <bool... bs>
789using IsTrueForAllImpl_t = typename std::is_same<TBoolPack<bs..., true>, TBoolPack<true, bs...>>;
790
791template <bool... Conditions>
792struct TEvalAnd {
793 static constexpr bool value = IsTrueForAllImpl_t<Conditions...>::value;
794};
795
796// Check if a class is a specialisation of stl containers templates
797// clang-format off
798
799template <typename>
800struct IsList_t : std::false_type {};
801
802template <typename T>
803struct IsList_t<std::list<T>> : std::true_type {};
804
805template <typename>
806struct IsDeque_t : std::false_type {};
807
808template <typename T>
809struct IsDeque_t<std::deque<T>> : std::true_type {};
810// clang-format on
811
812void CheckForDuplicateSnapshotColumns(const ColumnNames_t &cols);
813
814template <typename T>
815struct InnerValueType {
816 using type = T; // fallback for when T is not a nested RVec
817};
818
819template <typename Elem>
820struct InnerValueType<ROOT::VecOps::RVec<ROOT::VecOps::RVec<Elem>>> {
821 using type = Elem;
822};
823
824template <typename T>
826
827std::pair<std::vector<std::string>, std::vector<std::string>>
829 std::vector<std::string> &&colsWithAliases);
830
831void RemoveDuplicates(ColumnNames_t &columnNames);
832void RemoveRNTupleSubFields(ColumnNames_t &columnNames);
833
834} // namespace RDF
835} // namespace Internal
836
837namespace Detail {
838namespace RDF {
839
840/// The aliased type is `double` if `T == RInferredType`, `U` if `T == container<U>`, `T` otherwise.
841template <typename T>
842using MinReturnType_t = typename RDFInternal::RMinReturnType<T>::type;
843
844template <typename T>
846
847template <typename T>
849
850} // namespace RDF
851} // namespace Detail
852} // namespace ROOT
853
854/// \endcond
855
856#endif
#define f(i)
Definition RSha256.hxx:104
#define g(i)
Definition RSha256.hxx:105
#define a(i)
Definition RSha256.hxx:99
#define h(i)
Definition RSha256.hxx:106
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Int_t gErrorIgnoreLevel
errors with level below this value will be ignored. Default is kUnset.
Definition TError.cxx:33
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
char name[80]
Definition TGX11.cxx:110
Int_t Fill(Double_t x) override
The head node of a RDF computation graph.
A binder for user-defined columns, variations and aliases.
RDataSource defines an API that RDataFrame can use to read arbitrary data formats.
The public interface to the RDataFrame federation of classes.
const_iterator end() const
A "std::vector"-like collection of values implementing handy operation to analyse them.
Definition RVec.hxx:1526
A TTree represents a columnar dataset.
Definition TTree.h:89
#define F(x, y, z)
const ColumnNames_t SelectColumns(unsigned int nRequiredNames, const ColumnNames_t &names, const ColumnNames_t &defaultNames)
Choose between local column names or default column names, throw in case of errors.
void CheckForNoVariations(const std::string &where, std::string_view definedColView, const RColumnRegister &colRegister)
Throw if the column has systematic variations attached.
ParsedTreePath ParseTreePath(std::string_view fullTreeName)
std::shared_ptr< RJittedDefine > BookDefineJit(std::string_view name, std::string_view expression, RLoopManager &lm, RDataSource *ds, const RColumnRegister &colRegister, std::shared_ptr< RNodeBase > *upcastNodeOnHeap)
Book the jitting of a Define call.
void CheckValidCppVarName(std::string_view var, const std::string &where)
void RemoveDuplicates(ColumnNames_t &columnNames)
ColumnNames_t GetValidatedColumnNames(RLoopManager &lm, const unsigned int nColumns, const ColumnNames_t &columns, const RColumnRegister &colRegister, RDataSource *ds)
Given the desired number of columns and the user-provided list of columns:
std::shared_ptr< RNodeBase > UpcastNode(std::shared_ptr< RNodeBase > ptr)
std::shared_ptr< RDFDetail::RJittedFilter > BookFilterJit(std::shared_ptr< RDFDetail::RNodeBase > *prevNodeOnHeap, std::string_view name, std::string_view expression, const RColumnRegister &colRegister, TTree *tree, RDataSource *ds)
Book the jitting of a Filter call.
void CheckForDefinition(const std::string &where, std::string_view definedColView, const RColumnRegister &colRegister, const ColumnNames_t &dataSourceColumns)
Throw if column definedColView is not already there.
std::vector< std::string > GetFilterNames(const std::shared_ptr< RLoopManager > &loopManager)
std::string PrettyPrintAddr(const void *const addr)
void CheckTypesAndPars(unsigned int nTemplateParams, unsigned int nColumnNames)
std::string DemangleTypeIdName(const std::type_info &typeInfo)
bool AtLeastOneEmptyString(const std::vector< std::string_view > strings)
std::unique_ptr< ROOT::Detail::RDF::RColumnReaderBase > CreateColumnReader(ROOT::RDF::RDataSource &ds, unsigned int slot, std::string_view col, const std::type_info &tid, TTreeReader *treeReader)
Definition RDFUtils.cxx:671
std::pair< std::vector< std::string >, std::vector< std::string > > AddSizeBranches(ROOT::RDF::RDataSource *ds, std::vector< std::string > &&colsWithoutAliases, std::vector< std::string > &&colsWithAliases)
Return copies of colsWithoutAliases and colsWithAliases with size branches for variable-sized array b...
void RemoveRNTupleSubFields(ColumnNames_t &columnNames)
ColumnNames_t FilterArraySizeColNames(const ColumnNames_t &columnNames, const std::string &action)
Take a list of column names, return that list with entries starting by '#' filtered out.
std::vector< std::string > GetValidatedArgTypes(const ColumnNames_t &colNames, const RColumnRegister &colRegister, TTree *tree, RDataSource *ds, const std::string &context, bool vector2RVec)
std::shared_ptr< RJittedVariation > BookVariationJit(const std::vector< std::string > &colNames, std::string_view variationName, const std::vector< std::string > &variationTags, std::string_view expression, RLoopManager &lm, RDataSource *ds, const RColumnRegister &colRegister, std::shared_ptr< RNodeBase > *upcastNodeOnHeap, bool isSingleColumn)
Book the jitting of a Vary call.
void CheckForDuplicateSnapshotColumns(const ColumnNames_t &cols)
ColumnNames_t ConvertRegexToColumns(const ColumnNames_t &colNames, std::string_view columnNameRegexp, std::string_view callerName)
ColumnNames_t FindUnknownColumns(const ColumnNames_t &requiredCols, const RColumnRegister &definedCols, const ColumnNames_t &dataSourceColumns)
unsigned int & NThreadPerTH3()
Obtain or set the number of threads that will share a clone of a thread-safe 3D histogram.
Definition RDFUtils.cxx:63
std::shared_ptr< RJittedDefine > BookDefinePerSampleJit(std::string_view name, std::string_view expression, RLoopManager &lm, const RColumnRegister &colRegister, std::shared_ptr< RNodeBase > *upcastNodeOnHeap)
Book the jitting of a DefinePerSample call.
void CheckForRedefinition(const std::string &where, std::string_view definedColView, const RColumnRegister &colRegister, const ColumnNames_t &dataSourceColumns)
Throw if column definedColView is already there.
std::string JitBuildAction(const ColumnNames_t &cols, std::shared_ptr< RDFDetail::RNodeBase > *prevNode, const std::type_info &helperArgType, const std::type_info &at, void *helperArgOnHeap, TTree *tree, const unsigned int nSlots, const RColumnRegister &colRegister, RDataSource *ds, std::weak_ptr< RJittedAction > *jittedActionOnHeap, const bool vector2RVec)
ROOT type_traits extensions.
Bool_t IsImplicitMTEnabled()
Returns true if the implicit multi-threading in ROOT is enabled.
Definition TROOT.cxx:600
A collection of options to steer the creation of the dataset on file.
Lightweight storage for a collection of types.