Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RInterface.hxx
Go to the documentation of this file.
1// Author: Enrico Guiraud, Danilo Piparo CERN 03/2017
2
3/*************************************************************************
4 * Copyright (C) 1995-2021, 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
12#define ROOT_RDF_TINTERFACE
13
14#include "ROOT/RDataSource.hxx"
19#include "ROOT/RDF/RDefine.hxx"
21#include "ROOT/RDF/RFilter.hxx"
26#include "ROOT/RDF/RRange.hxx"
27#include "ROOT/RDF/Utils.hxx"
30#include "ROOT/RResultPtr.hxx"
32#include "ROOT/RStringView.hxx"
33#include "ROOT/RVec.hxx"
34#include "ROOT/TypeTraits.hxx"
35#include "RtypesCore.h" // for ULong64_t
36#include "TDirectory.h"
37#include "TH1.h" // For Histo actions
38#include "TH2.h" // For Histo actions
39#include "TH3.h" // For Histo actions
40#include "THn.h"
41#include "TProfile.h"
42#include "TProfile2D.h"
43#include "TStatistic.h"
44
45#include <algorithm>
46#include <cstddef>
47#include <initializer_list>
48#include <iterator> // std::back_insterter
49#include <limits>
50#include <memory>
51#include <set>
52#include <sstream>
53#include <stdexcept>
54#include <string>
55#include <type_traits> // is_same, enable_if
56#include <typeinfo>
57#include <unordered_set>
58#include <utility> // std::index_sequence
59#include <vector>
60
61class TGraph;
62
63// Windows requires a forward decl of printValue to accept it as a valid friend function in RInterface
64namespace ROOT {
67void EnableImplicitMT(UInt_t numthreads);
68class RDataFrame;
69namespace Internal {
70namespace RDF {
72}
73} // namespace Internal
74} // namespace ROOT
75namespace cling {
76std::string printValue(ROOT::RDataFrame *tdf);
77}
78
79namespace ROOT {
80namespace RDF {
83namespace TTraits = ROOT::TypeTraits;
84
85template <typename Proxied, typename DataSource>
86class RInterface;
87
88using RNode = RInterface<::ROOT::Detail::RDF::RNodeBase, void>;
89
90// clang-format off
91/**
92 * \class ROOT::RDF::RInterface
93 * \ingroup dataframe
94 * \brief The public interface to the RDataFrame federation of classes.
95 * \tparam Proxied One of the "node" base types (e.g. RLoopManager, RFilterBase). The user never specifies this type manually.
96 * \tparam DataSource The type of the RDataSource which is providing the data to the data frame. There is no source by default.
97 *
98 * The documentation of each method features a one liner illustrating how to use the method, for example showing how
99 * the majority of the template parameters are automatically deduced requiring no or very little effort by the user.
100 */
101// clang-format on
102template <typename Proxied, typename DataSource = void>
104 using DS_t = DataSource;
108 friend std::string cling::printValue(::ROOT::RDataFrame *tdf); // For a nice printing at the prompt
110
111 template <typename T, typename W>
112 friend class RInterface;
113
114 friend void RDFInternal::TriggerRun(RNode &node);
115
116 std::shared_ptr<Proxied> fProxiedPtr; ///< Smart pointer to the graph node encapsulated by this RInterface.
117
118public:
119 ////////////////////////////////////////////////////////////////////////////
120 /// \brief Copy-assignment operator for RInterface.
121 RInterface &operator=(const RInterface &) = default;
122
123 ////////////////////////////////////////////////////////////////////////////
124 /// \brief Copy-ctor for RInterface.
125 RInterface(const RInterface &) = default;
126
127 ////////////////////////////////////////////////////////////////////////////
128 /// \brief Move-ctor for RInterface.
129 RInterface(RInterface &&) = default;
130
131 ////////////////////////////////////////////////////////////////////////////
132 /// \brief Move-assignment operator for RInterface.
134
135 ////////////////////////////////////////////////////////////////////////////
136 /// \brief Build a RInterface from a RLoopManager.
137 /// This constructor is only available for RInterface<RLoopManager>.
138 template <typename T = Proxied, typename = std::enable_if_t<std::is_same<T, RLoopManager>::value, int>>
139 RInterface(const std::shared_ptr<RLoopManager> &proxied) : RInterfaceBase(proxied), fProxiedPtr(proxied)
140 {
141 }
142
143 ////////////////////////////////////////////////////////////////////////////
144 /// \brief Cast any RDataFrame node to a common type ROOT::RDF::RNode.
145 /// Different RDataFrame methods return different C++ types. All nodes, however,
146 /// can be cast to this common type at the cost of a small performance penalty.
147 /// This allows, for example, storing RDataFrame nodes in a vector, or passing them
148 /// around via (non-template, C++11) helper functions.
149 /// Example usage:
150 /// ~~~{.cpp}
151 /// // a function that conditionally adds a Range to a RDataFrame node.
152 /// RNode MaybeAddRange(RNode df, bool mustAddRange)
153 /// {
154 /// return mustAddRange ? df.Range(1) : df;
155 /// }
156 /// // use as :
157 /// ROOT::RDataFrame df(10);
158 /// auto maybeRanged = MaybeAddRange(df, true);
159 /// ~~~
160 /// Note that it is not a problem to pass RNode's by value.
161 operator RNode() const
162 {
163 return RNode(std::static_pointer_cast<::ROOT::Detail::RDF::RNodeBase>(fProxiedPtr), *fLoopManager, fColRegister);
164 }
165
166 ////////////////////////////////////////////////////////////////////////////
167 /// \brief Append a filter to the call graph.
168 /// \param[in] f Function, lambda expression, functor class or any other callable object. It must return a `bool`
169 /// signalling whether the event has passed the selection (true) or not (false).
170 /// \param[in] columns Names of the columns/branches in input to the filter function.
171 /// \param[in] name Optional name of this filter. See `Report`.
172 /// \return the filter node of the computation graph.
173 ///
174 /// Append a filter node at the point of the call graph corresponding to the
175 /// object this method is called on.
176 /// The callable `f` should not have side-effects (e.g. modification of an
177 /// external or static variable) to ensure correct results when implicit
178 /// multi-threading is active.
179 ///
180 /// RDataFrame only evaluates filters when necessary: if multiple filters
181 /// are chained one after another, they are executed in order and the first
182 /// one returning false causes the event to be discarded.
183 /// Even if multiple actions or transformations depend on the same filter,
184 /// it is executed once per entry. If its result is requested more than
185 /// once, the cached result is served.
186 ///
187 /// ### Example usage:
188 /// ~~~{.cpp}
189 /// // C++ callable (function, functor class, lambda...) that takes two parameters of the types of "x" and "y"
190 /// auto filtered = df.Filter(myCut, {"x", "y"});
191 ///
192 /// // String: it must contain valid C++ except that column names can be used instead of variable names
193 /// auto filtered = df.Filter("x*y > 0");
194 /// ~~~
195 ///
196 /// \note If the body of the string expression contains an explicit `return` statement (even if it is in a nested
197 /// scope), RDataFrame _will not_ add another one in front of the expression. So this will not work:
198 /// ~~~{.cpp}
199 /// df.Filter("Sum(Map(vec, [](float e) { return e*e > 0.5; }))")
200 /// ~~~
201 /// but instead this will:
202 /// ~~~{.cpp}
203 /// df.Filter("return Sum(Map(vec, [](float e) { return e*e > 0.5; }))")
204 /// ~~~
205 template <typename F, std::enable_if_t<!std::is_convertible<F, std::string>::value, int> = 0>
207 Filter(F f, const ColumnNames_t &columns = {}, std::string_view name = "")
208 {
209 RDFInternal::CheckFilter(f);
210 using ColTypes_t = typename TTraits::CallableTraits<F>::arg_types;
211 constexpr auto nColumns = ColTypes_t::list_size;
212 const auto validColumnNames = GetValidatedColumnNames(nColumns, columns);
213 CheckAndFillDSColumns(validColumnNames, ColTypes_t());
214
216
217 auto filterPtr = std::make_shared<F_t>(std::move(f), validColumnNames, fProxiedPtr, fColRegister, name);
218 return RInterface<F_t, DS_t>(std::move(filterPtr), *fLoopManager, fColRegister);
219 }
220
221 ////////////////////////////////////////////////////////////////////////////
222 /// \brief Append a filter to the call graph.
223 /// \param[in] f Function, lambda expression, functor class or any other callable object. It must return a `bool`
224 /// signalling whether the event has passed the selection (true) or not (false).
225 /// \param[in] name Optional name of this filter. See `Report`.
226 /// \return the filter node of the computation graph.
227 ///
228 /// Refer to the first overload of this method for the full documentation.
229 template <typename F, std::enable_if_t<!std::is_convertible<F, std::string>::value, int> = 0>
231 {
232 // The sfinae is there in order to pick up the overloaded method which accepts two strings
233 // rather than this template method.
234 return Filter(f, {}, name);
235 }
236
237 ////////////////////////////////////////////////////////////////////////////
238 /// \brief Append a filter to the call graph.
239 /// \param[in] f Function, lambda expression, functor class or any other callable object. It must return a `bool`
240 /// signalling whether the event has passed the selection (true) or not (false).
241 /// \param[in] columns Names of the columns/branches in input to the filter function.
242 /// \return the filter node of the computation graph.
243 ///
244 /// Refer to the first overload of this method for the full documentation.
245 template <typename F>
246 RInterface<RDFDetail::RFilter<F, Proxied>, DS_t> Filter(F f, const std::initializer_list<std::string> &columns)
247 {
248 return Filter(f, ColumnNames_t{columns});
249 }
250
251 ////////////////////////////////////////////////////////////////////////////
252 /// \brief Append a filter to the call graph.
253 /// \param[in] expression The filter expression in C++
254 /// \param[in] name Optional name of this filter. See `Report`.
255 /// \return the filter node of the computation graph.
256 ///
257 /// The expression is just-in-time compiled and used to filter entries. It must
258 /// be valid C++ syntax in which variable names are substituted with the names
259 /// of branches/columns.
260 ///
261 /// ### Example usage:
262 /// ~~~{.cpp}
263 /// auto filtered_df = df.Filter("myCollection.size() > 3");
264 /// auto filtered_name_df = df.Filter("myCollection.size() > 3", "Minumum collection size");
265 /// ~~~
266 ///
267 /// \note If the body of the string expression contains an explicit `return` statement (even if it is in a nested
268 /// scope), RDataFrame _will not_ add another one in front of the expression. So this will not work:
269 /// ~~~{.cpp}
270 /// df.Filter("Sum(Map(vec, [](float e) { return e*e > 0.5; }))")
271 /// ~~~
272 /// but instead this will:
273 /// ~~~{.cpp}
274 /// df.Filter("return Sum(Map(vec, [](float e) { return e*e > 0.5; }))")
275 /// ~~~
276 RInterface<RDFDetail::RJittedFilter, DS_t> Filter(std::string_view expression, std::string_view name = "")
277 {
278 // deleted by the jitted call to JitFilterHelper
279 auto upcastNodeOnHeap = RDFInternal::MakeSharedOnHeap(RDFInternal::UpcastNode(fProxiedPtr));
280 using BaseNodeType_t = typename std::remove_pointer_t<decltype(upcastNodeOnHeap)>::element_type;
281 RInterface<BaseNodeType_t> upcastInterface(*upcastNodeOnHeap, *fLoopManager, fColRegister);
282 const auto jittedFilter =
285
287 }
288
289 // clang-format off
290 ////////////////////////////////////////////////////////////////////////////
291 /// \brief Define a new column.
292 /// \param[in] name The name of the defined column.
293 /// \param[in] expression Function, lambda expression, functor class or any other callable object producing the defined value. Returns the value that will be assigned to the defined column.
294 /// \param[in] columns Names of the columns/branches in input to the producer function.
295 /// \return the first node of the computation graph for which the new quantity is defined.
296 ///
297 /// Define a column that will be visible from all subsequent nodes
298 /// of the functional chain. The `expression` is only evaluated for entries that pass
299 /// all the preceding filters.
300 /// A new variable is created called `name`, accessible as if it was contained
301 /// in the dataset from subsequent transformations/actions.
302 ///
303 /// Use cases include:
304 /// * caching the results of complex calculations for easy and efficient multiple access
305 /// * extraction of quantities of interest from complex objects
306 ///
307 /// An exception is thrown if the name of the new column is already in use in this branch of the computation graph.
308 ///
309 /// ### Example usage:
310 /// ~~~{.cpp}
311 /// // assuming a function with signature:
312 /// double myComplexCalculation(const RVec<float> &muon_pts);
313 /// // we can pass it directly to Define
314 /// auto df_with_define = df.Define("newColumn", myComplexCalculation, {"muon_pts"});
315 /// // alternatively, we can pass the body of the function as a string, as in Filter:
316 /// auto df_with_define = df.Define("newColumn", "x*x + y*y");
317 /// ~~~
318 ///
319 /// \note If the body of the string expression contains an explicit `return` statement (even if it is in a nested
320 /// scope), RDataFrame _will not_ add another one in front of the expression. So this will not work:
321 /// ~~~{.cpp}
322 /// df.Define("x2", "Map(v, [](float e) { return e*e; })")
323 /// ~~~
324 /// but instead this will:
325 /// ~~~{.cpp}
326 /// df.Define("x2", "return Map(v, [](float e) { return e*e; })")
327 /// ~~~
328 template <typename F, typename std::enable_if_t<!std::is_convertible<F, std::string>::value, int> = 0>
329 RInterface<Proxied, DS_t> Define(std::string_view name, F expression, const ColumnNames_t &columns = {})
330 {
331 return DefineImpl<F, RDFDetail::ExtraArgsForDefine::None>(name, std::move(expression), columns, "Define");
332 }
333 // clang-format on
334
335 // clang-format off
336 ////////////////////////////////////////////////////////////////////////////
337 /// \brief Define a new column with a value dependent on the processing slot.
338 /// \param[in] name The name of the defined column.
339 /// \param[in] expression Function, lambda expression, functor class or any other callable object producing the defined value. Returns the value that will be assigned to the defined column.
340 /// \param[in] columns Names of the columns/branches in input to the producer function (excluding the slot number).
341 /// \return the first node of the computation graph for which the new quantity is defined.
342 ///
343 /// This alternative implementation of `Define` is meant as a helper to evaluate new column values in a thread-safe manner.
344 /// The expression must be a callable of signature R(unsigned int, T1, T2, ...) where `T1, T2...` are the types
345 /// of the columns that the expression takes as input. The first parameter is reserved for an unsigned integer
346 /// representing a "slot number". RDataFrame guarantees that different threads will invoke the expression with
347 /// different slot numbers - slot numbers will range from zero to ROOT::GetThreadPoolSize()-1.
348 ///
349 /// The following two calls are equivalent, although `DefineSlot` is slightly more performant:
350 /// ~~~{.cpp}
351 /// int function(unsigned int, double, double);
352 /// df.Define("x", function, {"rdfslot_", "column1", "column2"})
353 /// df.DefineSlot("x", function, {"column1", "column2"})
354 /// ~~~
355 ///
356 /// See Define() for more information.
357 template <typename F>
358 RInterface<Proxied, DS_t> DefineSlot(std::string_view name, F expression, const ColumnNames_t &columns = {})
359 {
360 return DefineImpl<F, RDFDetail::ExtraArgsForDefine::Slot>(name, std::move(expression), columns, "DefineSlot");
361 }
362 // clang-format on
363
364 // clang-format off
365 ////////////////////////////////////////////////////////////////////////////
366 /// \brief Define a new column with a value dependent on the processing slot and the current entry.
367 /// \param[in] name The name of the defined column.
368 /// \param[in] expression Function, lambda expression, functor class or any other callable object producing the defined value. Returns the value that will be assigned to the defined column.
369 /// \param[in] columns Names of the columns/branches in input to the producer function (excluding slot and entry).
370 /// \return the first node of the computation graph for which the new quantity is defined.
371 ///
372 /// This alternative implementation of `Define` is meant as a helper in writing entry-specific, thread-safe custom
373 /// columns. The expression must be a callable of signature R(unsigned int, ULong64_t, T1, T2, ...) where `T1, T2...`
374 /// are the types of the columns that the expression takes as input. The first parameter is reserved for an unsigned
375 /// integer representing a "slot number". RDataFrame guarantees that different threads will invoke the expression with
376 /// different slot numbers - slot numbers will range from zero to ROOT::GetThreadPoolSize()-1. The second parameter
377 /// is reserved for a `ULong64_t` representing the current entry being processed by the current thread.
378 ///
379 /// The following two `Define`s are equivalent, although `DefineSlotEntry` is slightly more performant:
380 /// ~~~{.cpp}
381 /// int function(unsigned int, ULong64_t, double, double);
382 /// Define("x", function, {"rdfslot_", "rdfentry_", "column1", "column2"})
383 /// DefineSlotEntry("x", function, {"column1", "column2"})
384 /// ~~~
385 ///
386 /// See Define() for more information.
387 template <typename F>
388 RInterface<Proxied, DS_t> DefineSlotEntry(std::string_view name, F expression, const ColumnNames_t &columns = {})
389 {
390 return DefineImpl<F, RDFDetail::ExtraArgsForDefine::SlotAndEntry>(name, std::move(expression), columns,
391 "DefineSlotEntry");
392 }
393 // clang-format on
394
395 ////////////////////////////////////////////////////////////////////////////
396 /// \brief Define a new column.
397 /// \param[in] name The name of the defined column.
398 /// \param[in] expression An expression in C++ which represents the defined value
399 /// \return the first node of the computation graph for which the new quantity is defined.
400 ///
401 /// The expression is just-in-time compiled and used to produce the column entries.
402 /// It must be valid C++ syntax in which variable names are substituted with the names
403 /// of branches/columns.
404 ///
405 /// \note If the body of the string expression contains an explicit `return` statement (even if it is in a nested
406 /// scope), RDataFrame _will not_ add another one in front of the expression. So this will not work:
407 /// ~~~{.cpp}
408 /// df.Define("x2", "Map(v, [](float e) { return e*e; })")
409 /// ~~~
410 /// but instead this will:
411 /// ~~~{.cpp}
412 /// df.Define("x2", "return Map(v, [](float e) { return e*e; })")
413 /// ~~~
414 ///
415 /// Refer to the first overload of this method for the full documentation.
416 RInterface<Proxied, DS_t> Define(std::string_view name, std::string_view expression)
417 {
418 constexpr auto where = "Define";
420 // these checks must be done before jitting lest we throw exceptions in jitted code
423
424 auto upcastNodeOnHeap = RDFInternal::MakeSharedOnHeap(RDFInternal::UpcastNode(fProxiedPtr));
425 auto jittedDefine = RDFInternal::BookDefineJit(name, expression, *fLoopManager, fDataSource, fColRegister,
426 fLoopManager->GetBranchNames(), upcastNodeOnHeap);
427
429 newCols.AddDefine(std::move(jittedDefine));
430
431 RInterface<Proxied, DS_t> newInterface(fProxiedPtr, *fLoopManager, std::move(newCols));
432
433 return newInterface;
434 }
435
436 ////////////////////////////////////////////////////////////////////////////
437 /// \brief Overwrite the value and/or type of an existing column.
438 /// \param[in] name The name of the column to redefine.
439 /// \param[in] expression Function, lambda expression, functor class or any other callable object producing the defined value. Returns the value that will be assigned to the defined column.
440 /// \param[in] columns Names of the columns/branches in input to the expression.
441 /// \return the first node of the computation graph for which the quantity is redefined.
442 ///
443 /// The old value of the column can be used as an input for the expression.
444 ///
445 /// An exception is thrown in case the column to redefine does not already exist.
446 /// See Define() for more information.
447 template <typename F, std::enable_if_t<!std::is_convertible<F, std::string>::value, int> = 0>
448 RInterface<Proxied, DS_t> Redefine(std::string_view name, F expression, const ColumnNames_t &columns = {})
449 {
450 return DefineImpl<F, RDFDetail::ExtraArgsForDefine::None>(name, std::move(expression), columns, "Redefine");
451 }
452
453 // clang-format off
454 ////////////////////////////////////////////////////////////////////////////
455 /// \brief Overwrite the value and/or type of an existing column.
456 /// \param[in] name The name of the column to redefine.
457 /// \param[in] expression Function, lambda expression, functor class or any other callable object producing the defined value. Returns the value that will be assigned to the defined column.
458 /// \param[in] columns Names of the columns/branches in input to the producer function (excluding slot).
459 /// \return the first node of the computation graph for which the new quantity is defined.
460 ///
461 /// The old value of the column can be used as an input for the expression.
462 /// An exception is thrown in case the column to redefine does not already exist.
463 ///
464 /// See DefineSlot() for more information.
465 // clang-format on
466 template <typename F>
467 RInterface<Proxied, DS_t> RedefineSlot(std::string_view name, F expression, const ColumnNames_t &columns = {})
468 {
469 return DefineImpl<F, RDFDetail::ExtraArgsForDefine::Slot>(name, std::move(expression), columns, "RedefineSlot");
470 }
471
472 // clang-format off
473 ////////////////////////////////////////////////////////////////////////////
474 /// \brief Overwrite the value and/or type of an existing column.
475 /// \param[in] name The name of the column to redefine.
476 /// \param[in] expression Function, lambda expression, functor class or any other callable object producing the defined value. Returns the value that will be assigned to the defined column.
477 /// \param[in] columns Names of the columns/branches in input to the producer function (excluding slot and entry).
478 /// \return the first node of the computation graph for which the new quantity is defined.
479 ///
480 /// The old value of the column can be used as an input for the expression.
481 /// An exception is thrown in case the column to re-define does not already exist.
482 ///
483 /// See DefineSlotEntry() for more information.
484 // clang-format on
485 template <typename F>
486 RInterface<Proxied, DS_t> RedefineSlotEntry(std::string_view name, F expression, const ColumnNames_t &columns = {})
487 {
488 return DefineImpl<F, RDFDetail::ExtraArgsForDefine::SlotAndEntry>(name, std::move(expression), columns,
489 "RedefineSlotEntry");
490 }
491
492 ////////////////////////////////////////////////////////////////////////////
493 /// \brief Overwrite the value and/or type of an existing column.
494 /// \param[in] name The name of the column to redefine.
495 /// \param[in] expression An expression in C++ which represents the defined value
496 /// \return the first node of the computation graph for which the new quantity is defined.
497 ///
498 /// The expression is just-in-time compiled and used to produce the column entries.
499 /// It must be valid C++ syntax in which variable names are substituted with the names
500 /// of branches/columns.
501 ///
502 /// The old value of the column can be used as an input for the expression.
503 /// An exception is thrown in case the column to re-define does not already exist.
504 ///
505 /// Aliases cannot be overridden. See the corresponding Define() overload for more information.
506 RInterface<Proxied, DS_t> Redefine(std::string_view name, std::string_view expression)
507 {
508 constexpr auto where = "Redefine";
513
514 auto upcastNodeOnHeap = RDFInternal::MakeSharedOnHeap(RDFInternal::UpcastNode(fProxiedPtr));
515 auto jittedDefine = RDFInternal::BookDefineJit(name, expression, *fLoopManager, fDataSource, fColRegister,
516 fLoopManager->GetBranchNames(), upcastNodeOnHeap);
517
519 newCols.AddDefine(std::move(jittedDefine));
520
521 RInterface<Proxied, DS_t> newInterface(fProxiedPtr, *fLoopManager, std::move(newCols));
522
523 return newInterface;
524 }
525
526 // clang-format off
527 ////////////////////////////////////////////////////////////////////////////
528 /// \brief Define a new column that is updated when the input sample changes.
529 /// \param[in] name The name of the defined column.
530 /// \param[in] expression A C++ callable that computes the new value of the defined column.
531 /// \return the first node of the computation graph for which the new quantity is defined.
532 ///
533 /// The signature of the callable passed as second argument should be `T(unsigned int slot, const ROOT::RDF::RSampleInfo &id)`
534 /// where:
535 /// - `T` is the type of the defined column
536 /// - `slot` is a number in the range [0, nThreads) that is different for each processing thread. This can simplify
537 /// the definition of thread-safe callables if you are interested in using parallel capabilities of RDataFrame.
538 /// - `id` is an instance of a ROOT::RDF::RSampleInfo object which contains information about the sample which is
539 /// being processed (see the class docs for more information).
540 ///
541 /// DefinePerSample() is useful to e.g. define a quantity that depends on which TTree in which TFile is being
542 /// processed or to inject a callback into the event loop that is only called when the processing of a new sample
543 /// starts rather than at every entry.
544 ///
545 /// The callable will be invoked once per input TTree or once per multi-thread task, whichever is more often.
546 ///
547 /// ### Example usage:
548 /// ~~~{.cpp}
549 /// ROOT::RDataFrame df{"mytree", {"sample1.root","sample2.root"}};
550 /// df.DefinePerSample("weightbysample",
551 /// [](unsigned int slot, const ROOT::RDF::RSampleInfo &id)
552 /// { return id.Contains("sample1") ? 1.0f : 2.0f; });
553 /// ~~~
554 // clang-format on
555 // TODO we could SFINAE on F's signature to provide friendlier compilation errors in case of signature mismatch
556 template <typename F, typename RetType_t = typename TTraits::CallableTraits<F>::ret_type>
557 RInterface<Proxied, DS_t> DefinePerSample(std::string_view name, F expression)
558 {
559 RDFInternal::CheckValidCppVarName(name, "DefinePerSample");
562
563 auto retTypeName = RDFInternal::TypeID2TypeName(typeid(RetType_t));
564 if (retTypeName.empty()) {
565 // The type is not known to the interpreter.
566 // We must not error out here, but if/when this column is used in jitted code
567 const auto demangledType = RDFInternal::DemangleTypeIdName(typeid(RetType_t));
568 retTypeName = "CLING_UNKNOWN_TYPE_" + demangledType;
569 }
570
571 auto newColumn =
572 std::make_shared<RDFDetail::RDefinePerSample<F>>(name, retTypeName, std::move(expression), *fLoopManager);
573
575 newCols.AddDefine(std::move(newColumn));
576 RInterface<Proxied> newInterface(fProxiedPtr, *fLoopManager, std::move(newCols));
577 return newInterface;
578 }
579
580 // clang-format off
581 ////////////////////////////////////////////////////////////////////////////
582 /// \brief Define a new column that is updated when the input sample changes.
583 /// \param[in] name The name of the defined column.
584 /// \param[in] expression A valid C++ expression as a string, which will be used to compute the defined value.
585 /// \return the first node of the computation graph for which the new quantity is defined.
586 ///
587 /// The expression is just-in-time compiled and used to produce the column entries.
588 /// It must be valid C++ syntax and the usage of the special variable names `rdfslot_` and `rdfsampleinfo_` is
589 /// permitted, where these variables will take the same values as the `slot` and `id` parameters described at the
590 /// DefinePerSample(std::string_view name, F expression) overload. See the documentation of that overload for more information.
591 ///
592 /// ### Example usage:
593 /// ~~~{.py}
594 /// df = ROOT.RDataFrame('mytree', ['sample1.root','sample2.root'])
595 /// df.DefinePerSample('weightbysample', 'rdfsampleinfo_.Contains("sample1") ? 1.0f : 2.0f')
596 /// ~~~
597 ///
598 /// \note
599 /// If you have declared some C++ function to the interpreter, the correct syntax to call that function with this
600 /// overload of DefinePerSample is by calling it explicitly with the special names `rdfslot_` and `rdfsampleinfo_` as
601 /// input parameters. This is for example the correct way to call this overload when working in PyROOT:
602 /// ~~~{.py}
603 /// ROOT.gInterpreter.Declare(
604 /// """
605 /// float weights(unsigned int slot, const ROOT::RDF::RSampleInfo &id){
606 /// return id.Contains("sample1") ? 1.0f : 2.0f;
607 /// }
608 /// """)
609 /// df = ROOT.RDataFrame("mytree", ["sample1.root","sample2.root"])
610 /// df.DefinePerSample("weightsbysample", "weights(rdfslot_, rdfsampleinfo_)")
611 /// ~~~
612 ///
613 /// \note
614 /// Differently from what happens in Define(), the string expression passed to DefinePerSample cannot contain
615 /// column names other than those mentioned above: the expression is evaluated once before the processing of the
616 /// sample even starts, so column values are not accessible.
617 // clang-format on
618 RInterface<Proxied, DS_t> DefinePerSample(std::string_view name, std::string_view expression)
619 {
620 RDFInternal::CheckValidCppVarName(name, "DefinePerSample");
621 // these checks must be done before jitting lest we throw exceptions in jitted code
624
625 auto upcastNodeOnHeap = RDFInternal::MakeSharedOnHeap(RDFInternal::UpcastNode(fProxiedPtr));
626 auto jittedDefine =
627 RDFInternal::BookDefinePerSampleJit(name, expression, *fLoopManager, fColRegister, upcastNodeOnHeap);
628
630 newCols.AddDefine(std::move(jittedDefine));
631
632 RInterface<Proxied, DS_t> newInterface(fProxiedPtr, *fLoopManager, std::move(newCols));
633
634 return newInterface;
635 }
636
637 /// \brief Register systematic variations for an existing column.
638 /// \param[in] colName name of the column for which varied values are provided.
639 /// \param[in] expression a callable that evaluates the varied values for the specified columns. The callable can
640 /// take any column values as input, similarly to what happens with Filter and Define calls. It must
641 /// return an RVec of varied values, one for each variation tag, in the same order as the tags.
642 /// \param[in] inputColumns the names of the columns to be passed to the callable.
643 /// \param[in] variationTags names for each of the varied values, e.g. "up" and "down".
644 /// \param[in] variationName a generic name for this set of varied values, e.g. "ptvariation".
645 ///
646 /// Vary provides a natural and flexible syntax to define systematic variations that automatically propagate to
647 /// Filters, Defines and results. RDataFrame usage of columns with attached variations does not change, but for
648 /// results that depend on any varied quantity a map/dictionary of varied results can be produced with
649 /// ROOT::RDF::Experimental::VariationsFor (see the example below).
650 ///
651 /// The dictionary will contain a "nominal" value (accessed with the "nominal" key) for the unchanged result, and
652 /// values for each of the systematic variations that affected the result (via upstream Filters or via direct or
653 /// indirect dependencies of the column values on some registered variations). The keys will be a composition of
654 /// variation names and tags, e.g. "pt:up" and "pt:down" for the example below.
655 ///
656 /// In the following example we add up/down variations of pt and fill a histogram with a quantity that depends on pt.
657 /// We automatically obtain three histograms in output ("nominal", "pt:up" and "pt:down"):
658 /// ~~~{.cpp}
659 /// auto nominal_hx =
660 /// df.Vary("pt", [] (double pt) { return RVecD{pt*0.9, pt*1.1}; }, {"down", "up"})
661 /// .Filter("pt > k")
662 /// .Define("x", someFunc, {"pt"})
663 /// .Histo1D("x");
664 ///
665 /// auto hx = ROOT::RDF::VariationsFor(nominal_hx);
666 /// hx["nominal"].Draw();
667 /// hx["pt:down"].Draw("SAME");
668 /// ~~~
669 template <typename F>
670 RInterface<Proxied, DS_t> Vary(std::string_view colName, F &&expression, const ColumnNames_t &inputColumns,
671 const std::vector<std::string> &variationTags, std::string_view variationName = "")
672 {
673 std::vector<std::string> colNames{{std::string(colName)}};
674 const std::string theVariationName{variationName.empty() ? colName : variationName};
675
676 return VaryImpl<true>(std::move(colNames), std::forward<F>(expression), inputColumns, variationTags,
677 theVariationName);
678 }
679
680 /// \brief Register systematic variations for an existing columns using auto-generated variation tags.
681 /// This overload of Vary takes a nVariations parameter instead of a list of tag names. Tag names
682 /// will be auto-generated as the sequence 0...nVariations-1.
683 /// See the documentation of the previous overload for more information.
684 template <typename F>
685 RInterface<Proxied, DS_t> Vary(std::string_view colName, F &&expression, const ColumnNames_t &inputColumns,
686 std::size_t nVariations, std::string_view variationName = "")
687 {
688 R__ASSERT(nVariations > 0 && "Must have at least one variation.");
689
690 std::vector<std::string> variationTags;
691 variationTags.reserve(nVariations);
692 for (std::size_t i = 0u; i < nVariations; ++i)
693 variationTags.emplace_back(std::to_string(i));
694
695 const std::string theVariationName{variationName.empty() ? colName : variationName};
696
697 return Vary(colName, std::forward<F>(expression), inputColumns, std::move(variationTags), theVariationName);
698 }
699
700 /// \brief Register a systematic variation that affects multiple columns simultaneously.
701 /// This overload of Vary takes a list of column names as first argument rather than a single name and
702 /// requires that the expression returns an RVec of RVecs of values: one inner RVec for the variations of each
703 /// affected column.
704 /// See the documentation of the first Vary overload for more information.
705 ///
706 /// Example usage:
707 /// ~~~{.cpp}
708 /// // produce variations "ptAndEta:down" and "ptAndEta:up"
709 /// df.Vary({"pt", "eta"},
710 /// [](double pt, double eta) { return RVec<RVecF>{{pt*0.9, pt*1.1}, {eta*0.9, eta*1.1}}; },
711 /// {"down", "up"},
712 /// "ptAndEta");
713 /// ~~~
714 template <typename F>
716 Vary(const std::vector<std::string> &colNames, F &&expression, const ColumnNames_t &inputColumns,
717 const std::vector<std::string> &variationTags, std::string_view variationName)
718 {
719 return VaryImpl<false>(colNames, std::forward<F>(expression), inputColumns, variationTags, variationName);
720 }
721
722 /// Overload to avoid ambiguity between C++20 string, vector<string> construction from init list.
723 template <typename F>
725 Vary(std::initializer_list<std::string> colNames, F &&expression, const ColumnNames_t &inputColumns,
726 const std::vector<std::string> &variationTags, std::string_view variationName)
727 {
728 return Vary(std::vector<std::string>(colNames), std::forward<F>(expression), inputColumns, variationTags, variationName);
729 }
730
731 /// \brief Register systematic variations for one or more existing columns using auto-generated tags.
732 /// This overload of Vary takes a nVariations parameter instead of a list of tag names. Tag names
733 /// will be auto-generated as the sequence 0...nVariations-1.
734 /// See the documentation of the previous overload for more information.
735 template <typename F>
737 Vary(const std::vector<std::string> &colNames, F &&expression, const ColumnNames_t &inputColumns,
738 std::size_t nVariations, std::string_view variationName)
739 {
740 R__ASSERT(nVariations > 0 && "Must have at least one variation.");
741
742 std::vector<std::string> variationTags;
743 variationTags.reserve(nVariations);
744 for (std::size_t i = 0u; i < nVariations; ++i)
745 variationTags.emplace_back(std::to_string(i));
746
747 return Vary(colNames, std::forward<F>(expression), inputColumns, std::move(variationTags), variationName);
748 }
749
750 /// Overload to avoid ambiguity between C++20 string, vector<string> construction from init list.
751 template <typename F>
753 Vary(std::initializer_list<std::string> colNames, F &&expression, const ColumnNames_t &inputColumns,
754 std::size_t nVariations, std::string_view variationName)
755 {
756 return Vary(std::vector<std::string>(colNames), std::forward<F>(expression), inputColumns, nVariations, variationName);
757 }
758
759 /// \brief Register systematic variations for an existing column.
760 /// \param[in] colName name of the column for which varied values are provided.
761 /// \param[in] expression a string containing valid C++ code that evaluates to an RVec containing the varied
762 /// values for the specified column.
763 /// \param[in] variationTags names for each of the varied values, e.g. "up" and "down".
764 /// \param[in] variationName a generic name for this set of varied values, e.g. "ptvariation".
765 /// colName is used if none is provided.
766 ///
767 /// ~~~{.cpp}
768 /// auto nominal_hx =
769 /// df.Vary("pt", "ROOT::RVecD{pt*0.9, pt*1.1}", {"down", "up"})
770 /// .Filter("pt > k")
771 /// .Define("x", someFunc, {"pt"})
772 /// .Histo1D("x");
773 ///
774 /// auto hx = ROOT::RDF::VariationsFor(nominal_hx);
775 /// hx["nominal"].Draw();
776 /// hx["pt:down"].Draw("SAME");
777 /// ~~~
778 RInterface<Proxied, DS_t> Vary(std::string_view colName, std::string_view expression,
779 const std::vector<std::string> &variationTags, std::string_view variationName = "")
780 {
781 std::vector<std::string> colNames{{std::string(colName)}};
782 const std::string theVariationName{variationName.empty() ? colName : variationName};
783
784 return JittedVaryImpl(colNames, expression, variationTags, theVariationName, /*isSingleColumn=*/true);
785 }
786
787 /// \brief Register systematic variations for an existing column.
788 /// \param[in] colName name of the column for which varied values are provided.
789 /// \param[in] expression a string containing valid C++ code that evaluates to an RVec containing the varied
790 /// values for the specified column.
791 /// \param[in] nVariations number of variations returned by the expression. The corresponding tags will be "0", "1", etc.
792 /// \param[in] variationName a generic name for this set of varied values, e.g. "ptvariation".
793 /// colName is used if none is provided.
794 ///
795 /// See the documentation for the previous overload for more information.
796 RInterface<Proxied, DS_t> Vary(std::string_view colName, std::string_view expression, std::size_t nVariations,
797 std::string_view variationName = "")
798 {
799 std::vector<std::string> variationTags;
800 variationTags.reserve(nVariations);
801 for (std::size_t i = 0u; i < nVariations; ++i)
802 variationTags.emplace_back(std::to_string(i));
803
804 return Vary(colName, expression, std::move(variationTags), variationName);
805 }
806
807 /// \brief Register systematic variations for one or more existing columns.
808 /// \param[in] colNames names of the columns for which varied values are provided.
809 /// \param[in] expression a string containing valid C++ code that evaluates to an RVec or RVecs containing the varied
810 /// values for the specified columns.
811 /// \param[in] nVariations number of variations returned by the expression. The corresponding tags will be "0", "1", etc.
812 /// \param[in] variationName a generic name for this set of varied values, e.g. "ptvariation".
813 ///
814 /// ~~~{.cpp}
815 /// auto nominal_hx =
816 /// df.Vary({"x", "y"}, "ROOT::RVec<ROOT::RVecD>{{x*0.9, x*1.1}, {y*0.9, y*1.1}}", 2, "xy")
817 /// .Histo1D("x", "y");
818 ///
819 /// auto hx = ROOT::RDF::VariationsFor(nominal_hx);
820 /// hx["nominal"].Draw();
821 /// hx["xy:0"].Draw("SAME");
822 /// hx["xy:1"].Draw("SAME");
823 /// ~~~
824 RInterface<Proxied, DS_t> Vary(const std::vector<std::string> &colNames, std::string_view expression,
825 std::size_t nVariations, std::string_view variationName)
826 {
827 std::vector<std::string> variationTags;
828 variationTags.reserve(nVariations);
829 for (std::size_t i = 0u; i < nVariations; ++i)
830 variationTags.emplace_back(std::to_string(i));
831
832 return Vary(colNames, expression, std::move(variationTags), variationName);
833 }
834
835 /// Overload to avoid ambiguity between C++20 string, vector<string> construction from init list.
836 RInterface<Proxied, DS_t> Vary(std::initializer_list<std::string> colNames, std::string_view expression,
837 std::size_t nVariations, std::string_view variationName)
838 {
839 return Vary(std::vector<std::string>(colNames), expression, nVariations, variationName);
840 }
841
842 /// \brief Register systematic variations for one or more existing columns.
843 /// \param[in] colNames names of the columns for which varied values are provided.
844 /// \param[in] expression a string containing valid C++ code that evaluates to an RVec or RVecs containing the varied
845 /// values for the specified columns.
846 /// \param[in] variationTags names for each of the varied values, e.g. "up" and "down".
847 /// \param[in] variationName a generic name for this set of varied values, e.g. "ptvariation".
848 ///
849 /// ~~~{.cpp}
850 /// auto nominal_hx =
851 /// df.Vary({"x", "y"}, "ROOT::RVec<ROOT::RVecD>{{x*0.9, x*1.1}, {y*0.9, y*1.1}}", {"down", "up"}, "xy")
852 /// .Histo1D("x", "y");
853 ///
854 /// auto hx = ROOT::RDF::VariationsFor(nominal_hx);
855 /// hx["nominal"].Draw();
856 /// hx["xy:down"].Draw("SAME");
857 /// hx["xy:up"].Draw("SAME");
858 /// ~~~
859 RInterface<Proxied, DS_t> Vary(const std::vector<std::string> &colNames, std::string_view expression,
860 const std::vector<std::string> &variationTags, std::string_view variationName)
861 {
862 return JittedVaryImpl(colNames, expression, variationTags, variationName, /*isSingleColumn=*/false);
863 }
864
865 ////////////////////////////////////////////////////////////////////////////
866 /// \brief Allow to refer to a column with a different name.
867 /// \param[in] alias name of the column alias
868 /// \param[in] columnName of the column to be aliased
869 /// \return the first node of the computation graph for which the alias is available.
870 ///
871 /// Aliasing an alias is supported.
872 ///
873 /// ### Example usage:
874 /// ~~~{.cpp}
875 /// auto df_with_alias = df.Alias("simple_name", "very_long&complex_name!!!");
876 /// ~~~
877 RInterface<Proxied, DS_t> Alias(std::string_view alias, std::string_view columnName)
878 {
879 // The symmetry with Define is clear. We want to:
880 // - Create globally the alias and return this very node, unchanged
881 // - Make aliases accessible based on chains and not globally
882
883 // Helper to find out if a name is a column
884 auto &dsColumnNames = fDataSource ? fDataSource->GetColumnNames() : ColumnNames_t{};
885
886 constexpr auto where = "Alias";
888 // If the alias name is a column name, there is a problem
890
891 const auto validColumnName = GetValidatedColumnNames(1, {std::string(columnName)})[0];
892
894 newCols.AddAlias(alias, validColumnName);
895
896 RInterface<Proxied, DS_t> newInterface(fProxiedPtr, *fLoopManager, std::move(newCols));
897
898 return newInterface;
899 }
900
901 ////////////////////////////////////////////////////////////////////////////
902 /// \brief Save selected columns to disk, in a new TTree `treename` in file `filename`.
903 /// \tparam ColumnTypes variadic list of branch/column types.
904 /// \param[in] treename The name of the output TTree.
905 /// \param[in] filename The name of the output TFile.
906 /// \param[in] columnList The list of names of the columns/branches to be written.
907 /// \param[in] options RSnapshotOptions struct with extra options to pass to TFile and TTree.
908 /// \return a `RDataFrame` that wraps the snapshotted dataset.
909 ///
910 /// Support for writing of nested branches is limited (although RDataFrame is able to read them) and dot ('.')
911 /// characters in input column names will be replaced by underscores ('_') in the branches produced by Snapshot.
912 /// When writing a variable size array through Snapshot, it is required that the column indicating its size is also
913 /// written out and it appears before the array in the columnList.
914 ///
915 /// By default, in case of TTree or TChain inputs, Snapshot will try to write out all top-level branches. For other
916 /// types of inputs, all columns returned by GetColumnNames() will be written out. If friend trees or chains are
917 /// present, by default all friend top-level branches that have names that do not collide with
918 /// names of branches in the main TTree/TChain will be written out. Since v6.24, Snapshot will also write out
919 /// friend branches with the same names of branches in the main TTree/TChain with names of the form
920 /// `<friendname>_<branchname>` in order to differentiate them from the branches in the main tree/chain.
921 ///
922 /// ### Writing to a sub-directory
923 ///
924 /// Snapshot supports writing the TTree in a sub-directory inside the TFile. It is sufficient to specify the path to
925 /// the TTree as part of the TTree name, e.g. `df.Snapshot("subdir/t", "f.root")` write TTree `t` in the
926 /// sub-directory `subdir` of file `f.root` (creating file and sub-directory as needed).
927 ///
928 /// \attention In multi-thread runs (i.e. when EnableImplicitMT() has been called) threads will loop over clusters of
929 /// entries in an undefined order, so Snapshot will produce outputs in which (clusters of) entries will be shuffled with
930 /// respect to the input TTree. Using such "shuffled" TTrees as friends of the original trees would result in wrong
931 /// associations between entries in the main TTree and entries in the "shuffled" friend. Since v6.22, ROOT will
932 /// error out if such a "shuffled" TTree is used in a friendship.
933 ///
934 /// \note In case no events are written out (e.g. because no event passes all filters) the behavior of Snapshot in
935 /// single-thread and multi-thread runs is different: in single-thread runs, Snapshot will write out a TTree with
936 /// the specified name and zero entries; in multi-thread runs, no TTree object will be written out to disk.
937 ///
938 /// \note Snapshot will refuse to process columns with names of the form `#columnname`. These are special columns
939 /// made available by some data sources (e.g. RNTupleDS) that represent the size of column `columnname`, and are
940 /// not meant to be written out with that name (which is not a valid C++ variable name). Instead, go through an
941 /// Alias(): `df.Alias("nbar", "#bar").Snapshot(..., {"nbar"})`.
942 ///
943 /// ### Example invocations:
944 ///
945 /// ~~~{.cpp}
946 /// // without specifying template parameters (column types automatically deduced)
947 /// df.Snapshot("outputTree", "outputFile.root", {"x", "y"});
948 ///
949 /// // specifying template parameters ("x" is `int`, "y" is `float`)
950 /// df.Snapshot<int, float>("outputTree", "outputFile.root", {"x", "y"});
951 /// ~~~
952 ///
953 /// To book a Snapshot without triggering the event loop, one needs to set the appropriate flag in
954 /// `RSnapshotOptions`:
955 /// ~~~{.cpp}
956 /// RSnapshotOptions opts;
957 /// opts.fLazy = true;
958 /// df.Snapshot("outputTree", "outputFile.root", {"x"}, opts);
959 /// ~~~
960 template <typename... ColumnTypes>
962 Snapshot(std::string_view treename, std::string_view filename, const ColumnNames_t &columnList,
963 const RSnapshotOptions &options = RSnapshotOptions())
964 {
965 return SnapshotImpl<ColumnTypes...>(treename, filename, columnList, options);
966 }
967
968 ////////////////////////////////////////////////////////////////////////////
969 /// \brief Save selected columns to disk, in a new TTree `treename` in file `filename`.
970 /// \param[in] treename The name of the output TTree.
971 /// \param[in] filename The name of the output TFile.
972 /// \param[in] columnList The list of names of the columns/branches to be written.
973 /// \param[in] options RSnapshotOptions struct with extra options to pass to TFile and TTree.
974 /// \return a `RDataFrame` that wraps the snapshotted dataset.
975 ///
976 /// This function returns a `RDataFrame` built with the output tree as a source.
977 /// The types of the columns are automatically inferred and do not need to be specified.
978 ///
979 /// See above for a more complete description and example usages.
980 RResultPtr<RInterface<RLoopManager>> Snapshot(std::string_view treename, std::string_view filename,
981 const ColumnNames_t &columnList,
982 const RSnapshotOptions &options = RSnapshotOptions())
983 {
984 // like columnList but with `#var` columns removed
985 auto colListNoPoundSizes = RDFInternal::FilterArraySizeColNames(columnList, "Snapshot");
986 // like columnListWithoutSizeColumns but with aliases resolved
987 auto colListNoAliases = GetValidatedColumnNames(colListNoPoundSizes.size(), colListNoPoundSizes);
989 // like validCols but with missing size branches required by array branches added in the right positions
990 const auto pairOfColumnLists =
992 std::move(colListNoAliases), std::move(colListNoPoundSizes));
993 const auto &colListNoAliasesWithSizeBranches = pairOfColumnLists.first;
994 const auto &colListWithAliasesAndSizeBranches = pairOfColumnLists.second;
995
996
997 const auto fullTreeName = treename;
998 const auto parsedTreePath = RDFInternal::ParseTreePath(fullTreeName);
999 treename = parsedTreePath.fTreeName;
1000 const auto &dirname = parsedTreePath.fDirName;
1001
1002 auto snapHelperArgs = std::make_shared<RDFInternal::SnapshotHelperArgs>(
1003 RDFInternal::SnapshotHelperArgs{std::string(filename), std::string(dirname), std::string(treename),
1004 colListWithAliasesAndSizeBranches, options});
1005
1007 auto newRDF = std::make_shared<ROOT::RDataFrame>(fullTreeName, filename, colListNoAliasesWithSizeBranches);
1008
1009 auto resPtr = CreateAction<RDFInternal::ActionTags::Snapshot, RDFDetail::RInferredType>(
1010 colListNoAliasesWithSizeBranches, newRDF, snapHelperArgs, fProxiedPtr,
1011 colListNoAliasesWithSizeBranches.size());
1012
1013 if (!options.fLazy)
1014 *resPtr;
1015 return resPtr;
1016 }
1017
1018 // clang-format off
1019 ////////////////////////////////////////////////////////////////////////////
1020 /// \brief Save selected columns to disk, in a new TTree `treename` in file `filename`.
1021 /// \param[in] treename The name of the output TTree.
1022 /// \param[in] filename The name of the output TFile.
1023 /// \param[in] columnNameRegexp The regular expression to match the column names to be selected. The presence of a '^' and a '$' at the end of the string is implicitly assumed if they are not specified. The dialect supported is PCRE via the TPRegexp class. An empty string signals the selection of all columns.
1024 /// \param[in] options RSnapshotOptions struct with extra options to pass to TFile and TTree
1025 /// \return a `RDataFrame` that wraps the snapshotted dataset.
1026 ///
1027 /// This function returns a `RDataFrame` built with the output tree as a source.
1028 /// The types of the columns are automatically inferred and do not need to be specified.
1029 ///
1030 /// See above for a more complete description and example usages.
1031 RResultPtr<RInterface<RLoopManager>> Snapshot(std::string_view treename, std::string_view filename,
1032 std::string_view columnNameRegexp = "",
1033 const RSnapshotOptions &options = RSnapshotOptions())
1034 {
1035 const auto definedColumns = fColRegister.GetNames();
1036 auto *tree = fLoopManager->GetTree();
1037 const auto treeBranchNames = tree != nullptr ? ROOT::Internal::TreeUtils::GetTopLevelBranchNames(*tree) : ColumnNames_t{};
1038 const auto dsColumns = fDataSource ? fDataSource->GetColumnNames() : ColumnNames_t{};
1039 // Ignore R_rdf_sizeof_* columns coming from datasources: we don't want to Snapshot those
1040 ColumnNames_t dsColumnsWithoutSizeColumns;
1041 std::copy_if(dsColumns.begin(), dsColumns.end(), std::back_inserter(dsColumnsWithoutSizeColumns),
1042 [](const std::string &name) { return name.size() < 13 || name.substr(0, 13) != "R_rdf_sizeof_"; });
1043 ColumnNames_t columnNames;
1044 columnNames.reserve(definedColumns.size() + treeBranchNames.size() + dsColumnsWithoutSizeColumns.size());
1045 columnNames.insert(columnNames.end(), definedColumns.begin(), definedColumns.end());
1046 columnNames.insert(columnNames.end(), treeBranchNames.begin(), treeBranchNames.end());
1047 columnNames.insert(columnNames.end(), dsColumnsWithoutSizeColumns.begin(), dsColumnsWithoutSizeColumns.end());
1048
1049 // The only way we can get duplicate entries is if a column coming from a tree or data-source is Redefine'd.
1050 // RemoveDuplicates should preserve ordering of the columns: it might be meaningful.
1051 RDFInternal::RemoveDuplicates(columnNames);
1052
1053 const auto selectedColumns = RDFInternal::ConvertRegexToColumns(columnNames, columnNameRegexp, "Snapshot");
1054 return Snapshot(treename, filename, selectedColumns, options);
1055 }
1056 // clang-format on
1057
1058 // clang-format off
1059 ////////////////////////////////////////////////////////////////////////////
1060 /// \brief Save selected columns to disk, in a new TTree `treename` in file `filename`.
1061 /// \param[in] treename The name of the output TTree.
1062 /// \param[in] filename The name of the output TFile.
1063 /// \param[in] columnList The list of names of the columns/branches to be written.
1064 /// \param[in] options RSnapshotOptions struct with extra options to pass to TFile and TTree.
1065 /// \return a `RDataFrame` that wraps the snapshotted dataset.
1066 ///
1067 /// This function returns a `RDataFrame` built with the output tree as a source.
1068 /// The types of the columns are automatically inferred and do not need to be specified.
1069 ///
1070 /// See above for a more complete description and example usages.
1071 RResultPtr<RInterface<RLoopManager>> Snapshot(std::string_view treename, std::string_view filename,
1072 std::initializer_list<std::string> columnList,
1073 const RSnapshotOptions &options = RSnapshotOptions())
1074 {
1075 ColumnNames_t selectedColumns(columnList);
1076 return Snapshot(treename, filename, selectedColumns, options);
1077 }
1078 // clang-format on
1079
1080 ////////////////////////////////////////////////////////////////////////////
1081 /// \brief Save selected columns in memory.
1082 /// \tparam ColumnTypes variadic list of branch/column types.
1083 /// \param[in] columnList columns to be cached in memory.
1084 /// \return a `RDataFrame` that wraps the cached dataset.
1085 ///
1086 /// This action returns a new `RDataFrame` object, completely detached from
1087 /// the originating `RDataFrame`. The new dataframe only contains the cached
1088 /// columns and stores their content in memory for fast, zero-copy subsequent access.
1089 ///
1090 /// Use `Cache` if you know you will only need a subset of the (`Filter`ed) data that
1091 /// fits in memory and that will be accessed many times.
1092 ///
1093 /// \note Cache will refuse to process columns with names of the form `#columnname`. These are special columns
1094 /// made available by some data sources (e.g. RNTupleDS) that represent the size of column `columnname`, and are
1095 /// not meant to be written out with that name (which is not a valid C++ variable name). Instead, go through an
1096 /// Alias(): `df.Alias("nbar", "#bar").Cache<std::size_t>(..., {"nbar"})`.
1097 ///
1098 /// ### Example usage:
1099 ///
1100 /// **Types and columns specified:**
1101 /// ~~~{.cpp}
1102 /// auto cache_some_cols_df = df.Cache<double, MyClass, int>({"col0", "col1", "col2"});
1103 /// ~~~
1104 ///
1105 /// **Types inferred and columns specified (this invocation relies on jitting):**
1106 /// ~~~{.cpp}
1107 /// auto cache_some_cols_df = df.Cache({"col0", "col1", "col2"});
1108 /// ~~~
1109 ///
1110 /// **Types inferred and columns selected with a regexp (this invocation relies on jitting):**
1111 /// ~~~{.cpp}
1112 /// auto cache_all_cols_df = df.Cache(myRegexp);
1113 /// ~~~
1114 template <typename... ColumnTypes>
1116 {
1117 auto staticSeq = std::make_index_sequence<sizeof...(ColumnTypes)>();
1118 return CacheImpl<ColumnTypes...>(columnList, staticSeq);
1119 }
1120
1121 ////////////////////////////////////////////////////////////////////////////
1122 /// \brief Save selected columns in memory.
1123 /// \param[in] columnList columns to be cached in memory
1124 /// \return a `RDataFrame` that wraps the cached dataset.
1125 ///
1126 /// See the previous overloads for more information.
1128 {
1129 // Early return: if the list of columns is empty, just return an empty RDF
1130 // If we proceed, the jitted call will not compile!
1131 if (columnList.empty()) {
1132 auto nEntries = *this->Count();
1133 RInterface<RLoopManager> emptyRDF(std::make_shared<RLoopManager>(nEntries));
1134 return emptyRDF;
1135 }
1136
1137 std::stringstream cacheCall;
1138 auto upcastNode = RDFInternal::UpcastNode(fProxiedPtr);
1139 RInterface<TTraits::TakeFirstParameter_t<decltype(upcastNode)>> upcastInterface(fProxiedPtr, *fLoopManager,
1140 fColRegister);
1141 // build a string equivalent to
1142 // "(RInterface<nodetype*>*)(this)->Cache<Ts...>(*(ColumnNames_t*)(&columnList))"
1143 RInterface<RLoopManager> resRDF(std::make_shared<ROOT::Detail::RDF::RLoopManager>(0));
1144 cacheCall << "*reinterpret_cast<ROOT::RDF::RInterface<ROOT::Detail::RDF::RLoopManager>*>("
1146 << ") = reinterpret_cast<ROOT::RDF::RInterface<ROOT::Detail::RDF::RNodeBase>*>("
1147 << RDFInternal::PrettyPrintAddr(&upcastInterface) << ")->Cache<";
1148
1149 const auto columnListWithoutSizeColumns = RDFInternal::FilterArraySizeColNames(columnList, "Cache");
1150
1151 const auto validColumnNames =
1152 GetValidatedColumnNames(columnListWithoutSizeColumns.size(), columnListWithoutSizeColumns);
1153 const auto colTypes = GetValidatedArgTypes(validColumnNames, fColRegister, fLoopManager->GetTree(), fDataSource,
1154 "Cache", /*vector2rvec=*/false);
1155 for (const auto &colType : colTypes)
1156 cacheCall << colType << ", ";
1157 if (!columnListWithoutSizeColumns.empty())
1158 cacheCall.seekp(-2, cacheCall.cur); // remove the last ",
1159 cacheCall << ">(*reinterpret_cast<std::vector<std::string>*>(" // vector<string> should be ColumnNames_t
1160 << RDFInternal::PrettyPrintAddr(&columnListWithoutSizeColumns) << "));";
1161
1162 // book the code to jit with the RLoopManager and trigger the event loop
1163 fLoopManager->ToJitExec(cacheCall.str());
1164 fLoopManager->Jit();
1165
1166 return resRDF;
1167 }
1168
1169 ////////////////////////////////////////////////////////////////////////////
1170 /// \brief Save selected columns in memory.
1171 /// \param[in] columnNameRegexp The regular expression to match the column names to be selected. The presence of a '^' and a '$' at the end of the string is implicitly assumed if they are not specified. The dialect supported is PCRE via the TPRegexp class. An empty string signals the selection of all columns.
1172 /// \return a `RDataFrame` that wraps the cached dataset.
1173 ///
1174 /// The existing columns are matched against the regular expression. If the string provided
1175 /// is empty, all columns are selected. See the previous overloads for more information.
1176 RInterface<RLoopManager> Cache(std::string_view columnNameRegexp = "")
1177 {
1178 const auto definedColumns = fColRegister.GetNames();
1179 auto *tree = fLoopManager->GetTree();
1180 const auto treeBranchNames =
1182 const auto dsColumns = fDataSource ? fDataSource->GetColumnNames() : ColumnNames_t{};
1183 // Ignore R_rdf_sizeof_* columns coming from datasources: we don't want to Snapshot those
1184 ColumnNames_t dsColumnsWithoutSizeColumns;
1185 std::copy_if(dsColumns.begin(), dsColumns.end(), std::back_inserter(dsColumnsWithoutSizeColumns),
1186 [](const std::string &name) { return name.size() < 13 || name.substr(0, 13) != "R_rdf_sizeof_"; });
1187 ColumnNames_t columnNames;
1188 columnNames.reserve(definedColumns.size() + treeBranchNames.size() + dsColumns.size());
1189 columnNames.insert(columnNames.end(), definedColumns.begin(), definedColumns.end());
1190 columnNames.insert(columnNames.end(), treeBranchNames.begin(), treeBranchNames.end());
1191 columnNames.insert(columnNames.end(), dsColumns.begin(), dsColumns.end());
1192 const auto selectedColumns = RDFInternal::ConvertRegexToColumns(columnNames, columnNameRegexp, "Cache");
1193 return Cache(selectedColumns);
1194 }
1195
1196 ////////////////////////////////////////////////////////////////////////////
1197 /// \brief Save selected columns in memory.
1198 /// \param[in] columnList columns to be cached in memory.
1199 /// \return a `RDataFrame` that wraps the cached dataset.
1200 ///
1201 /// See the previous overloads for more information.
1202 RInterface<RLoopManager> Cache(std::initializer_list<std::string> columnList)
1203 {
1204 ColumnNames_t selectedColumns(columnList);
1205 return Cache(selectedColumns);
1206 }
1207
1208 // clang-format off
1209 ////////////////////////////////////////////////////////////////////////////
1210 /// \brief Creates a node that filters entries based on range: [begin, end).
1211 /// \param[in] begin Initial entry number considered for this range.
1212 /// \param[in] end Final entry number (excluded) considered for this range. 0 means that the range goes until the end of the dataset.
1213 /// \param[in] stride Process one entry of the [begin, end) range every `stride` entries. Must be strictly greater than 0.
1214 /// \return the first node of the computation graph for which the event loop is limited to a certain range of entries.
1215 ///
1216 /// Note that in case of previous Ranges and Filters the selected range refers to the transformed dataset.
1217 /// Ranges are only available if EnableImplicitMT has _not_ been called. Multi-thread ranges are not supported.
1218 ///
1219 /// ### Example usage:
1220 /// ~~~{.cpp}
1221 /// auto d_0_30 = d.Range(0, 30); // Pick the first 30 entries
1222 /// auto d_15_end = d.Range(15, 0); // Pick all entries from 15 onwards
1223 /// auto d_15_end_3 = d.Range(15, 0, 3); // Stride: from event 15, pick an event every 3
1224 /// ~~~
1225 // clang-format on
1226 RInterface<RDFDetail::RRange<Proxied>, DS_t> Range(unsigned int begin, unsigned int end, unsigned int stride = 1)
1227 {
1228 // check invariants
1229 if (stride == 0 || (end != 0 && end < begin))
1230 throw std::runtime_error("Range: stride must be strictly greater than 0 and end must be greater than begin.");
1231 CheckIMTDisabled("Range");
1232
1233 using Range_t = RDFDetail::RRange<Proxied>;
1234 auto rangePtr = std::make_shared<Range_t>(begin, end, stride, fProxiedPtr);
1235 RInterface<RDFDetail::RRange<Proxied>, DS_t> newInterface(std::move(rangePtr), *fLoopManager, fColRegister);
1236 return newInterface;
1237 }
1238
1239 // clang-format off
1240 ////////////////////////////////////////////////////////////////////////////
1241 /// \brief Creates a node that filters entries based on range.
1242 /// \param[in] end Final entry number (excluded) considered for this range. 0 means that the range goes until the end of the dataset.
1243 /// \return a node of the computation graph for which the range is defined.
1244 ///
1245 /// See the other Range overload for a detailed description.
1246 // clang-format on
1247 RInterface<RDFDetail::RRange<Proxied>, DS_t> Range(unsigned int end) { return Range(0, end, 1); }
1248
1249 // clang-format off
1250 ////////////////////////////////////////////////////////////////////////////
1251 /// \brief Execute a user-defined function on each entry (*instant action*).
1252 /// \param[in] f Function, lambda expression, functor class or any other callable object performing user defined calculations.
1253 /// \param[in] columns Names of the columns/branches in input to the user function.
1254 ///
1255 /// The callable `f` is invoked once per entry. This is an *instant action*:
1256 /// upon invocation, an event loop as well as execution of all scheduled actions
1257 /// is triggered.
1258 /// Users are responsible for the thread-safety of this callable when executing
1259 /// with implicit multi-threading enabled (i.e. ROOT::EnableImplicitMT).
1260 ///
1261 /// ### Example usage:
1262 /// ~~~{.cpp}
1263 /// myDf.Foreach([](int i){ std::cout << i << std::endl;}, {"myIntColumn"});
1264 /// ~~~
1265 // clang-format on
1266 template <typename F>
1267 void Foreach(F f, const ColumnNames_t &columns = {})
1268 {
1269 using arg_types = typename TTraits::CallableTraits<decltype(f)>::arg_types_nodecay;
1270 using ret_type = typename TTraits::CallableTraits<decltype(f)>::ret_type;
1271 ForeachSlot(RDFInternal::AddSlotParameter<ret_type>(f, arg_types()), columns);
1272 }
1273
1274 // clang-format off
1275 ////////////////////////////////////////////////////////////////////////////
1276 /// \brief Execute a user-defined function requiring a processing slot index on each entry (*instant action*).
1277 /// \param[in] f Function, lambda expression, functor class or any other callable object performing user defined calculations.
1278 /// \param[in] columns Names of the columns/branches in input to the user function.
1279 ///
1280 /// Same as `Foreach`, but the user-defined function takes an extra
1281 /// `unsigned int` as its first parameter, the *processing slot index*.
1282 /// This *slot index* will be assigned a different value, `0` to `poolSize - 1`,
1283 /// for each thread of execution.
1284 /// This is meant as a helper in writing thread-safe `Foreach`
1285 /// actions when using `RDataFrame` after `ROOT::EnableImplicitMT()`.
1286 /// The user-defined processing callable is able to follow different
1287 /// *streams of processing* indexed by the first parameter.
1288 /// `ForeachSlot` works just as well with single-thread execution: in that
1289 /// case `slot` will always be `0`.
1290 ///
1291 /// ### Example usage:
1292 /// ~~~{.cpp}
1293 /// myDf.ForeachSlot([](unsigned int s, int i){ std::cout << "Slot " << s << ": "<< i << std::endl;}, {"myIntColumn"});
1294 /// ~~~
1295 // clang-format on
1296 template <typename F>
1297 void ForeachSlot(F f, const ColumnNames_t &columns = {})
1298 {
1300 constexpr auto nColumns = ColTypes_t::list_size;
1301
1302 const auto validColumnNames = GetValidatedColumnNames(nColumns, columns);
1303 CheckAndFillDSColumns(validColumnNames, ColTypes_t());
1304
1305 using Helper_t = RDFInternal::ForeachSlotHelper<F>;
1307
1308 auto action = std::make_unique<Action_t>(Helper_t(std::move(f)), validColumnNames, fProxiedPtr, fColRegister);
1309
1310 fLoopManager->Run();
1311 }
1312
1313 // clang-format off
1314 ////////////////////////////////////////////////////////////////////////////
1315 /// \brief Execute a user-defined reduce operation on the values of a column.
1316 /// \tparam F The type of the reduce callable. Automatically deduced.
1317 /// \tparam T The type of the column to apply the reduction to. Automatically deduced.
1318 /// \param[in] f A callable with signature `T(T,T)`
1319 /// \param[in] columnName The column to be reduced. If omitted, the first default column is used instead.
1320 /// \return the reduced quantity wrapped in a ROOT::RDF:RResultPtr.
1321 ///
1322 /// A reduction takes two values of a column and merges them into one (e.g.
1323 /// by summing them, taking the maximum, etc). This action performs the
1324 /// specified reduction operation on all processed column values, returning
1325 /// a single value of the same type. The callable f must satisfy the general
1326 /// requirements of a *processing function* besides having signature `T(T,T)`
1327 /// where `T` is the type of column columnName.
1328 ///
1329 /// The returned reduced value of each thread (e.g. the initial value of a sum) is initialized to a
1330 /// default-constructed T object. This is commonly expected to be the neutral/identity element for the specific
1331 /// reduction operation `f` (e.g. 0 for a sum, 1 for a product). If a default-constructed T does not satisfy this
1332 /// requirement, users should explicitly specify an initialization value for T by calling the appropriate `Reduce`
1333 /// overload.
1334 ///
1335 /// ### Example usage:
1336 /// ~~~{.cpp}
1337 /// auto sumOfIntCol = d.Reduce([](int x, int y) { return x + y; }, "intCol");
1338 /// ~~~
1339 ///
1340 /// This action is *lazy*: upon invocation of this method the calculation is
1341 /// booked but not executed. Also see RResultPtr.
1342 // clang-format on
1343 template <typename F, typename T = typename TTraits::CallableTraits<F>::ret_type>
1344 RResultPtr<T> Reduce(F f, std::string_view columnName = "")
1345 {
1346 static_assert(
1347 std::is_default_constructible<T>::value,
1348 "reduce object cannot be default-constructed. Please provide an initialisation value (redIdentity)");
1349 return Reduce(std::move(f), columnName, T());
1350 }
1351
1352 ////////////////////////////////////////////////////////////////////////////
1353 /// \brief Execute a user-defined reduce operation on the values of a column.
1354 /// \tparam F The type of the reduce callable. Automatically deduced.
1355 /// \tparam T The type of the column to apply the reduction to. Automatically deduced.
1356 /// \param[in] f A callable with signature `T(T,T)`
1357 /// \param[in] columnName The column to be reduced. If omitted, the first default column is used instead.
1358 /// \param[in] redIdentity The reduced object of each thread is initialized to this value.
1359 /// \return the reduced quantity wrapped in a RResultPtr.
1360 ///
1361 /// ### Example usage:
1362 /// ~~~{.cpp}
1363 /// auto sumOfIntColWithOffset = d.Reduce([](int x, int y) { return x + y; }, "intCol", 42);
1364 /// ~~~
1365 /// See the description of the first Reduce overload for more information.
1366 template <typename F, typename T = typename TTraits::CallableTraits<F>::ret_type>
1367 RResultPtr<T> Reduce(F f, std::string_view columnName, const T &redIdentity)
1368 {
1369 return Aggregate(f, f, columnName, redIdentity);
1370 }
1371
1372 ////////////////////////////////////////////////////////////////////////////
1373 /// \brief Return the number of entries processed (*lazy action*).
1374 /// \return the number of entries wrapped in a RResultPtr.
1375 ///
1376 /// Useful e.g. for counting the number of entries passing a certain filter (see also `Report`).
1377 /// This action is *lazy*: upon invocation of this method the calculation is
1378 /// booked but not executed. Also see RResultPtr.
1379 ///
1380 /// ### Example usage:
1381 /// ~~~{.cpp}
1382 /// auto nEntriesAfterCuts = myFilteredDf.Count();
1383 /// ~~~
1384 ///
1386 {
1387 const auto nSlots = fLoopManager->GetNSlots();
1388 auto cSPtr = std::make_shared<ULong64_t>(0);
1389 using Helper_t = RDFInternal::CountHelper;
1391 auto action = std::make_unique<Action_t>(Helper_t(cSPtr, nSlots), ColumnNames_t({}), fProxiedPtr,
1393 return MakeResultPtr(cSPtr, *fLoopManager, std::move(action));
1394 }
1395
1396 ////////////////////////////////////////////////////////////////////////////
1397 /// \brief Return a collection of values of a column (*lazy action*, returns a std::vector by default).
1398 /// \tparam T The type of the column.
1399 /// \tparam COLL The type of collection used to store the values.
1400 /// \param[in] column The name of the column to collect the values of.
1401 /// \return the content of the selected column wrapped in a RResultPtr.
1402 ///
1403 /// The collection type to be specified for C-style array columns is `RVec<T>`:
1404 /// in this case the returned collection is a `std::vector<RVec<T>>`.
1405 /// ### Example usage:
1406 /// ~~~{.cpp}
1407 /// // In this case intCol is a std::vector<int>
1408 /// auto intCol = rdf.Take<int>("integerColumn");
1409 /// // Same content as above but in this case taken as a RVec<int>
1410 /// auto intColAsRVec = rdf.Take<int, RVec<int>>("integerColumn");
1411 /// // In this case intCol is a std::vector<RVec<int>>, a collection of collections
1412 /// auto cArrayIntCol = rdf.Take<RVec<int>>("cArrayInt");
1413 /// ~~~
1414 /// This action is *lazy*: upon invocation of this method the calculation is
1415 /// booked but not executed. Also see RResultPtr.
1416 template <typename T, typename COLL = std::vector<T>>
1417 RResultPtr<COLL> Take(std::string_view column = "")
1418 {
1419 const auto columns = column.empty() ? ColumnNames_t() : ColumnNames_t({std::string(column)});
1420
1421 const auto validColumnNames = GetValidatedColumnNames(1, columns);
1422 CheckAndFillDSColumns(validColumnNames, TTraits::TypeList<T>());
1423
1424 using Helper_t = RDFInternal::TakeHelper<T, T, COLL>;
1426 auto valuesPtr = std::make_shared<COLL>();
1427 const auto nSlots = fLoopManager->GetNSlots();
1428
1429 auto action =
1430 std::make_unique<Action_t>(Helper_t(valuesPtr, nSlots), validColumnNames, fProxiedPtr, fColRegister);
1431 return MakeResultPtr(valuesPtr, *fLoopManager, std::move(action));
1432 }
1433
1434 ////////////////////////////////////////////////////////////////////////////
1435 /// \brief Fill and return a one-dimensional histogram with the values of a column (*lazy action*).
1436 /// \tparam V The type of the column used to fill the histogram.
1437 /// \param[in] model The returned histogram will be constructed using this as a model.
1438 /// \param[in] vName The name of the column that will fill the histogram.
1439 /// \return the monodimensional histogram wrapped in a RResultPtr.
1440 ///
1441 /// Columns can be of a container type (e.g. `std::vector<double>`), in which case the histogram
1442 /// is filled with each one of the elements of the container. In case multiple columns of container type
1443 /// are provided (e.g. values and weights) they must have the same length for each one of the events (but
1444 /// possibly different lengths between events).
1445 /// This action is *lazy*: upon invocation of this method the calculation is
1446 /// booked but not executed. Also see RResultPtr.
1447 ///
1448 /// ### Example usage:
1449 /// ~~~{.cpp}
1450 /// // Deduce column type (this invocation needs jitting internally)
1451 /// auto myHist1 = myDf.Histo1D({"histName", "histTitle", 64u, 0., 128.}, "myColumn");
1452 /// // Explicit column type
1453 /// auto myHist2 = myDf.Histo1D<float>({"histName", "histTitle", 64u, 0., 128.}, "myColumn");
1454 /// ~~~
1455 ///
1456 /// \note Differently from other ROOT interfaces, the returned histogram is not associated to gDirectory
1457 /// and the caller is responsible for its lifetime (in particular, a typical source of confusion is that
1458 /// if result histograms go out of scope before the end of the program, ROOT might display a blank canvas).
1459 template <typename V = RDFDetail::RInferredType>
1460 RResultPtr<::TH1D> Histo1D(const TH1DModel &model = {"", "", 128u, 0., 0.}, std::string_view vName = "")
1461 {
1462 const auto userColumns = vName.empty() ? ColumnNames_t() : ColumnNames_t({std::string(vName)});
1463
1464 const auto validatedColumns = GetValidatedColumnNames(1, userColumns);
1465
1466 std::shared_ptr<::TH1D> h(nullptr);
1467 {
1468 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
1469 h = model.GetHistogram();
1470 h->SetDirectory(nullptr);
1471 }
1472
1473 if (h->GetXaxis()->GetXmax() == h->GetXaxis()->GetXmin())
1474 RDFInternal::HistoUtils<::TH1D>::SetCanExtendAllAxes(*h);
1475 return CreateAction<RDFInternal::ActionTags::Histo1D, V>(validatedColumns, h, h, fProxiedPtr);
1476 }
1477
1478 ////////////////////////////////////////////////////////////////////////////
1479 /// \brief Fill and return a one-dimensional histogram with the values of a column (*lazy action*).
1480 /// \tparam V The type of the column used to fill the histogram.
1481 /// \param[in] vName The name of the column that will fill the histogram.
1482 /// \return the monodimensional histogram wrapped in a RResultPtr.
1483 ///
1484 /// This overload uses a default model histogram TH1D(name, title, 128u, 0., 0.).
1485 /// The "name" and "title" strings are built starting from the input column name.
1486 /// See the description of the first Histo1D() overload for more details.
1487 ///
1488 /// ### Example usage:
1489 /// ~~~{.cpp}
1490 /// // Deduce column type (this invocation needs jitting internally)
1491 /// auto myHist1 = myDf.Histo1D("myColumn");
1492 /// // Explicit column type
1493 /// auto myHist2 = myDf.Histo1D<float>("myColumn");
1494 /// ~~~
1495 template <typename V = RDFDetail::RInferredType>
1496 RResultPtr<::TH1D> Histo1D(std::string_view vName)
1497 {
1498 const auto h_name = std::string(vName);
1499 const auto h_title = h_name + ";" + h_name + ";count";
1500 return Histo1D<V>({h_name.c_str(), h_title.c_str(), 128u, 0., 0.}, vName);
1501 }
1502
1503 ////////////////////////////////////////////////////////////////////////////
1504 /// \brief Fill and return a one-dimensional histogram with the weighted values of a column (*lazy action*).
1505 /// \tparam V The type of the column used to fill the histogram.
1506 /// \tparam W The type of the column used as weights.
1507 /// \param[in] model The returned histogram will be constructed using this as a model.
1508 /// \param[in] vName The name of the column that will fill the histogram.
1509 /// \param[in] wName The name of the column that will provide the weights.
1510 /// \return the monodimensional histogram wrapped in a RResultPtr.
1511 ///
1512 /// See the description of the first Histo1D() overload for more details.
1513 ///
1514 /// ### Example usage:
1515 /// ~~~{.cpp}
1516 /// // Deduce column type (this invocation needs jitting internally)
1517 /// auto myHist1 = myDf.Histo1D({"histName", "histTitle", 64u, 0., 128.}, "myValue", "myweight");
1518 /// // Explicit column type
1519 /// auto myHist2 = myDf.Histo1D<float, int>({"histName", "histTitle", 64u, 0., 128.}, "myValue", "myweight");
1520 /// ~~~
1521 template <typename V = RDFDetail::RInferredType, typename W = RDFDetail::RInferredType>
1522 RResultPtr<::TH1D> Histo1D(const TH1DModel &model, std::string_view vName, std::string_view wName)
1523 {
1524 const std::vector<std::string_view> columnViews = {vName, wName};
1525 const auto userColumns = RDFInternal::AtLeastOneEmptyString(columnViews)
1526 ? ColumnNames_t()
1527 : ColumnNames_t(columnViews.begin(), columnViews.end());
1528 std::shared_ptr<::TH1D> h(nullptr);
1529 {
1530 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
1531 h = model.GetHistogram();
1532 }
1533 return CreateAction<RDFInternal::ActionTags::Histo1D, V, W>(userColumns, h, h, fProxiedPtr);
1534 }
1535
1536 ////////////////////////////////////////////////////////////////////////////
1537 /// \brief Fill and return a one-dimensional histogram with the weighted values of a column (*lazy action*).
1538 /// \tparam V The type of the column used to fill the histogram.
1539 /// \tparam W The type of the column used as weights.
1540 /// \param[in] vName The name of the column that will fill the histogram.
1541 /// \param[in] wName The name of the column that will provide the weights.
1542 /// \return the monodimensional histogram wrapped in a RResultPtr.
1543 ///
1544 /// This overload uses a default model histogram TH1D(name, title, 128u, 0., 0.).
1545 /// The "name" and "title" strings are built starting from the input column names.
1546 /// See the description of the first Histo1D() overload for more details.
1547 ///
1548 /// ### Example usage:
1549 /// ~~~{.cpp}
1550 /// // Deduce column types (this invocation needs jitting internally)
1551 /// auto myHist1 = myDf.Histo1D("myValue", "myweight");
1552 /// // Explicit column types
1553 /// auto myHist2 = myDf.Histo1D<float, int>("myValue", "myweight");
1554 /// ~~~
1555 template <typename V = RDFDetail::RInferredType, typename W = RDFDetail::RInferredType>
1556 RResultPtr<::TH1D> Histo1D(std::string_view vName, std::string_view wName)
1557 {
1558 // We build name and title based on the value and weight column names
1559 std::string str_vName{vName};
1560 std::string str_wName{wName};
1561 const auto h_name = str_vName + "_weighted_" + str_wName;
1562 const auto h_title = str_vName + ", weights: " + str_wName + ";" + str_vName + ";count * " + str_wName;
1563 return Histo1D<V, W>({h_name.c_str(), h_title.c_str(), 128u, 0., 0.}, vName, wName);
1564 }
1565
1566 ////////////////////////////////////////////////////////////////////////////
1567 /// \brief Fill and return a one-dimensional histogram with the weighted values of a column (*lazy action*).
1568 /// \tparam V The type of the column used to fill the histogram.
1569 /// \tparam W The type of the column used as weights.
1570 /// \param[in] model The returned histogram will be constructed using this as a model.
1571 /// \return the monodimensional histogram wrapped in a RResultPtr.
1572 ///
1573 /// This overload will use the first two default columns as column names.
1574 /// See the description of the first Histo1D() overload for more details.
1575 template <typename V, typename W>
1576 RResultPtr<::TH1D> Histo1D(const TH1DModel &model = {"", "", 128u, 0., 0.})
1577 {
1578 return Histo1D<V, W>(model, "", "");
1579 }
1580
1581 ////////////////////////////////////////////////////////////////////////////
1582 /// \brief Fill and return a two-dimensional histogram (*lazy action*).
1583 /// \tparam V1 The type of the column used to fill the x axis of the histogram.
1584 /// \tparam V2 The type of the column used to fill the y axis of the histogram.
1585 /// \param[in] model The returned histogram will be constructed using this as a model.
1586 /// \param[in] v1Name The name of the column that will fill the x axis.
1587 /// \param[in] v2Name The name of the column that will fill the y axis.
1588 /// \return the bidimensional histogram wrapped in a RResultPtr.
1589 ///
1590 /// Columns can be of a container type (e.g. std::vector<double>), in which case the histogram
1591 /// is filled with each one of the elements of the container. In case multiple columns of container type
1592 /// are provided (e.g. values and weights) they must have the same length for each one of the events (but
1593 /// possibly different lengths between events).
1594 /// This action is *lazy*: upon invocation of this method the calculation is
1595 /// booked but not executed. Also see RResultPtr.
1596 ///
1597 /// ### Example usage:
1598 /// ~~~{.cpp}
1599 /// // Deduce column types (this invocation needs jitting internally)
1600 /// auto myHist1 = myDf.Histo2D({"histName", "histTitle", 64u, 0., 128., 32u, -4., 4.}, "myValueX", "myValueY");
1601 /// // Explicit column types
1602 /// auto myHist2 = myDf.Histo2D<float, float>({"histName", "histTitle", 64u, 0., 128., 32u, -4., 4.}, "myValueX", "myValueY");
1603 /// ~~~
1604 ///
1605 ///
1606 /// \note Differently from other ROOT interfaces, the returned histogram is not associated to gDirectory
1607 /// and the caller is responsible for its lifetime (in particular, a typical source of confusion is that
1608 /// if result histograms go out of scope before the end of the program, ROOT might display a blank canvas).
1609 template <typename V1 = RDFDetail::RInferredType, typename V2 = RDFDetail::RInferredType>
1610 RResultPtr<::TH2D> Histo2D(const TH2DModel &model, std::string_view v1Name = "", std::string_view v2Name = "")
1611 {
1612 std::shared_ptr<::TH2D> h(nullptr);
1613 {
1614 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
1615 h = model.GetHistogram();
1616 }
1617 if (!RDFInternal::HistoUtils<::TH2D>::HasAxisLimits(*h)) {
1618 throw std::runtime_error("2D histograms with no axes limits are not supported yet.");
1619 }
1620 const std::vector<std::string_view> columnViews = {v1Name, v2Name};
1621 const auto userColumns = RDFInternal::AtLeastOneEmptyString(columnViews)
1622 ? ColumnNames_t()
1623 : ColumnNames_t(columnViews.begin(), columnViews.end());
1624 return CreateAction<RDFInternal::ActionTags::Histo2D, V1, V2>(userColumns, h, h, fProxiedPtr);
1625 }
1626
1627 ////////////////////////////////////////////////////////////////////////////
1628 /// \brief Fill and return a weighted two-dimensional histogram (*lazy action*).
1629 /// \tparam V1 The type of the column used to fill the x axis of the histogram.
1630 /// \tparam V2 The type of the column used to fill the y axis of the histogram.
1631 /// \tparam W The type of the column used for the weights of the histogram.
1632 /// \param[in] model The returned histogram will be constructed using this as a model.
1633 /// \param[in] v1Name The name of the column that will fill the x axis.
1634 /// \param[in] v2Name The name of the column that will fill the y axis.
1635 /// \param[in] wName The name of the column that will provide the weights.
1636 /// \return the bidimensional histogram wrapped in a RResultPtr.
1637 ///
1638 /// This action is *lazy*: upon invocation of this method the calculation is
1639 /// booked but not executed. Also see RResultPtr.
1640 ///
1641 /// ### Example usage:
1642 /// ~~~{.cpp}
1643 /// // Deduce column types (this invocation needs jitting internally)
1644 /// auto myHist1 = myDf.Histo2D({"histName", "histTitle", 64u, 0., 128., 32u, -4., 4.}, "myValueX", "myValueY", "myWeight");
1645 /// // Explicit column types
1646 /// auto myHist2 = myDf.Histo2D<float, float, double>({"histName", "histTitle", 64u, 0., 128., 32u, -4., 4.}, "myValueX", "myValueY", "myWeight");
1647 /// ~~~
1648 ///
1649 /// See the documentation of the first Histo2D() overload for more details.
1650 template <typename V1 = RDFDetail::RInferredType, typename V2 = RDFDetail::RInferredType,
1651 typename W = RDFDetail::RInferredType>
1653 Histo2D(const TH2DModel &model, std::string_view v1Name, std::string_view v2Name, std::string_view wName)
1654 {
1655 std::shared_ptr<::TH2D> h(nullptr);
1656 {
1657 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
1658 h = model.GetHistogram();
1659 }
1660 if (!RDFInternal::HistoUtils<::TH2D>::HasAxisLimits(*h)) {
1661 throw std::runtime_error("2D histograms with no axes limits are not supported yet.");
1662 }
1663 const std::vector<std::string_view> columnViews = {v1Name, v2Name, wName};
1664 const auto userColumns = RDFInternal::AtLeastOneEmptyString(columnViews)
1665 ? ColumnNames_t()
1666 : ColumnNames_t(columnViews.begin(), columnViews.end());
1667 return CreateAction<RDFInternal::ActionTags::Histo2D, V1, V2, W>(userColumns, h, h, fProxiedPtr);
1668 }
1669
1670 template <typename V1, typename V2, typename W>
1672 {
1673 return Histo2D<V1, V2, W>(model, "", "", "");
1674 }
1675
1676 ////////////////////////////////////////////////////////////////////////////
1677 /// \brief Fill and return a three-dimensional histogram (*lazy action*).
1678 /// \tparam V1 The type of the column used to fill the x axis of the histogram. Inferred if not present.
1679 /// \tparam V2 The type of the column used to fill the y axis of the histogram. Inferred if not present.
1680 /// \tparam V3 The type of the column used to fill the z axis of the histogram. Inferred if not present.
1681 /// \param[in] model The returned histogram will be constructed using this as a model.
1682 /// \param[in] v1Name The name of the column that will fill the x axis.
1683 /// \param[in] v2Name The name of the column that will fill the y axis.
1684 /// \param[in] v3Name The name of the column that will fill the z axis.
1685 /// \return the tridimensional histogram wrapped in a RResultPtr.
1686 ///
1687 /// This action is *lazy*: upon invocation of this method the calculation is
1688 /// booked but not executed. Also see RResultPtr.
1689 ///
1690 /// ### Example usage:
1691 /// ~~~{.cpp}
1692 /// // Deduce column types (this invocation needs jitting internally)
1693 /// auto myHist1 = myDf.Histo3D({"name", "title", 64u, 0., 128., 32u, -4., 4., 8u, -2., 2.},
1694 /// "myValueX", "myValueY", "myValueZ");
1695 /// // Explicit column types
1696 /// auto myHist2 = myDf.Histo3D<double, double, float>({"name", "title", 64u, 0., 128., 32u, -4., 4., 8u, -2., 2.},
1697 /// "myValueX", "myValueY", "myValueZ");
1698 /// ~~~
1699 ///
1700 /// \note Differently from other ROOT interfaces, the returned histogram is not associated to gDirectory
1701 /// and the caller is responsible for its lifetime (in particular, a typical source of confusion is that
1702 /// if result histograms go out of scope before the end of the program, ROOT might display a blank canvas).
1703 template <typename V1 = RDFDetail::RInferredType, typename V2 = RDFDetail::RInferredType,
1704 typename V3 = RDFDetail::RInferredType>
1705 RResultPtr<::TH3D> Histo3D(const TH3DModel &model, std::string_view v1Name = "", std::string_view v2Name = "",
1706 std::string_view v3Name = "")
1707 {
1708 std::shared_ptr<::TH3D> h(nullptr);
1709 {
1710 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
1711 h = model.GetHistogram();
1712 }
1713 if (!RDFInternal::HistoUtils<::TH3D>::HasAxisLimits(*h)) {
1714 throw std::runtime_error("3D histograms with no axes limits are not supported yet.");
1715 }
1716 const std::vector<std::string_view> columnViews = {v1Name, v2Name, v3Name};
1717 const auto userColumns = RDFInternal::AtLeastOneEmptyString(columnViews)
1718 ? ColumnNames_t()
1719 : ColumnNames_t(columnViews.begin(), columnViews.end());
1720 return CreateAction<RDFInternal::ActionTags::Histo3D, V1, V2, V3>(userColumns, h, h, fProxiedPtr);
1721 }
1722
1723 ////////////////////////////////////////////////////////////////////////////
1724 /// \brief Fill and return a three-dimensional histogram (*lazy action*).
1725 /// \tparam V1 The type of the column used to fill the x axis of the histogram. Inferred if not present.
1726 /// \tparam V2 The type of the column used to fill the y axis of the histogram. Inferred if not present.
1727 /// \tparam V3 The type of the column used to fill the z axis of the histogram. Inferred if not present.
1728 /// \tparam W The type of the column used for the weights of the histogram. Inferred if not present.
1729 /// \param[in] model The returned histogram will be constructed using this as a model.
1730 /// \param[in] v1Name The name of the column that will fill the x axis.
1731 /// \param[in] v2Name The name of the column that will fill the y axis.
1732 /// \param[in] v3Name The name of the column that will fill the z axis.
1733 /// \param[in] wName The name of the column that will provide the weights.
1734 /// \return the tridimensional histogram wrapped in a RResultPtr.
1735 ///
1736 /// This action is *lazy*: upon invocation of this method the calculation is
1737 /// booked but not executed. Also see RResultPtr.
1738 ///
1739 /// ### Example usage:
1740 /// ~~~{.cpp}
1741 /// // Deduce column types (this invocation needs jitting internally)
1742 /// auto myHist1 = myDf.Histo3D({"name", "title", 64u, 0., 128., 32u, -4., 4., 8u, -2., 2.},
1743 /// "myValueX", "myValueY", "myValueZ", "myWeight");
1744 /// // Explicit column types
1745 /// using d_t = double;
1746 /// auto myHist2 = myDf.Histo3D<d_t, d_t, float, d_t>({"name", "title", 64u, 0., 128., 32u, -4., 4., 8u, -2., 2.},
1747 /// "myValueX", "myValueY", "myValueZ", "myWeight");
1748 /// ~~~
1749 ///
1750 ///
1751 /// See the documentation of the first Histo2D() overload for more details.
1752 template <typename V1 = RDFDetail::RInferredType, typename V2 = RDFDetail::RInferredType,
1753 typename V3 = RDFDetail::RInferredType, typename W = RDFDetail::RInferredType>
1754 RResultPtr<::TH3D> Histo3D(const TH3DModel &model, std::string_view v1Name, std::string_view v2Name,
1755 std::string_view v3Name, std::string_view wName)
1756 {
1757 std::shared_ptr<::TH3D> h(nullptr);
1758 {
1759 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
1760 h = model.GetHistogram();
1761 }
1762 if (!RDFInternal::HistoUtils<::TH3D>::HasAxisLimits(*h)) {
1763 throw std::runtime_error("3D histograms with no axes limits are not supported yet.");
1764 }
1765 const std::vector<std::string_view> columnViews = {v1Name, v2Name, v3Name, wName};
1766 const auto userColumns = RDFInternal::AtLeastOneEmptyString(columnViews)
1767 ? ColumnNames_t()
1768 : ColumnNames_t(columnViews.begin(), columnViews.end());
1769 return CreateAction<RDFInternal::ActionTags::Histo3D, V1, V2, V3, W>(userColumns, h, h, fProxiedPtr);
1770 }
1771
1772 template <typename V1, typename V2, typename V3, typename W>
1774 {
1775 return Histo3D<V1, V2, V3, W>(model, "", "", "", "");
1776 }
1777
1778 ////////////////////////////////////////////////////////////////////////////
1779 /// \brief Fill and return an N-dimensional histogram (*lazy action*).
1780 /// \tparam FirstColumn The first type of the column the values of which are used to fill the object. Inferred if not
1781 /// present.
1782 /// \tparam OtherColumns A list of the other types of the columns the values of which are used to fill the
1783 /// object.
1784 /// \param[in] model The returned histogram will be constructed using this as a model.
1785 /// \param[in] columnList
1786 /// A list containing the names of the columns that will be passed when calling `Fill`.
1787 /// (N columns for unweighted filling, or N+1 columns for weighted filling)
1788 /// \return the N-dimensional histogram wrapped in a RResultPtr.
1789 ///
1790 /// This action is *lazy*: upon invocation of this method the calculation is
1791 /// booked but not executed. See RResultPtr documentation.
1792 ///
1793 /// ### Example usage:
1794 /// ~~~{.cpp}
1795 /// auto myFilledObj = myDf.HistoND<float, float, float, float>({"name","title", 4,
1796 /// {40,40,40,40}, {20.,20.,20.,20.}, {60.,60.,60.,60.}},
1797 /// {"col0", "col1", "col2", "col3"});
1798 /// ~~~
1799 ///
1800 template <typename FirstColumn, typename... OtherColumns> // need FirstColumn to disambiguate overloads
1801 RResultPtr<::THnD> HistoND(const THnDModel &model, const ColumnNames_t &columnList)
1802 {
1803 std::shared_ptr<::THnD> h(nullptr);
1804 {
1805 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
1806 h = model.GetHistogram();
1807
1808 if (int(columnList.size()) == (h->GetNdimensions() + 1)) {
1809 h->Sumw2();
1810 } else if (int(columnList.size()) != h->GetNdimensions()) {
1811 throw std::runtime_error("Wrong number of columns for the specified number of histogram axes.");
1812 }
1813 }
1814 return CreateAction<RDFInternal::ActionTags::HistoND, FirstColumn, OtherColumns...>(columnList, h, h,
1815 fProxiedPtr);
1816 }
1817
1818 ////////////////////////////////////////////////////////////////////////////
1819 /// \brief Fill and return an N-dimensional histogram (*lazy action*).
1820 /// \param[in] model The returned histogram will be constructed using this as a model.
1821 /// \param[in] columnList A list containing the names of the columns that will be passed when calling `Fill`
1822 /// (N columns for unweighted filling, or N+1 columns for weighted filling)
1823 /// \return the N-dimensional histogram wrapped in a RResultPtr.
1824 ///
1825 /// This action is *lazy*: upon invocation of this method the calculation is
1826 /// booked but not executed. Also see RResultPtr.
1827 ///
1828 /// ### Example usage:
1829 /// ~~~{.cpp}
1830 /// auto myFilledObj = myDf.HistoND({"name","title", 4,
1831 /// {40,40,40,40}, {20.,20.,20.,20.}, {60.,60.,60.,60.}},
1832 /// {"col0", "col1", "col2", "col3"});
1833 /// ~~~
1834 ///
1835 RResultPtr<::THnD> HistoND(const THnDModel &model, const ColumnNames_t &columnList)
1836 {
1837 std::shared_ptr<::THnD> h(nullptr);
1838 {
1839 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
1840 h = model.GetHistogram();
1841
1842 if (int(columnList.size()) == (h->GetNdimensions() + 1)) {
1843 h->Sumw2();
1844 } else if (int(columnList.size()) != h->GetNdimensions()) {
1845 throw std::runtime_error("Wrong number of columns for the specified number of histogram axes.");
1846 }
1847 }
1848 return CreateAction<RDFInternal::ActionTags::HistoND, RDFDetail::RInferredType>(columnList, h, h, fProxiedPtr,
1849 columnList.size());
1850 }
1851
1852 ////////////////////////////////////////////////////////////////////////////
1853 /// \brief Fill and return a TGraph object (*lazy action*).
1854 /// \tparam X The type of the column used to fill the x axis.
1855 /// \tparam Y The type of the column used to fill the y axis.
1856 /// \param[in] x The name of the column that will fill the x axis.
1857 /// \param[in] y The name of the column that will fill the y axis.
1858 /// \return the TGraph wrapped in a RResultPtr.
1859 ///
1860 /// Columns can be of a container type (e.g. std::vector<double>), in which case the TGraph
1861 /// is filled with each one of the elements of the container.
1862 /// If Multithreading is enabled, the order in which points are inserted is undefined.
1863 /// If the Graph has to be drawn, it is suggested to the user to sort it on the x before printing.
1864 /// A name and a title to the TGraph is given based on the input column names.
1865 ///
1866 /// This action is *lazy*: upon invocation of this method the calculation is
1867 /// booked but not executed. Also see RResultPtr.
1868 ///
1869 /// ### Example usage:
1870 /// ~~~{.cpp}
1871 /// // Deduce column types (this invocation needs jitting internally)
1872 /// auto myGraph1 = myDf.Graph("xValues", "yValues");
1873 /// // Explicit column types
1874 /// auto myGraph2 = myDf.Graph<int, float>("xValues", "yValues");
1875 /// ~~~
1876 ///
1877 /// \note Differently from other ROOT interfaces, the returned TGraph is not associated to gDirectory
1878 /// and the caller is responsible for its lifetime (in particular, a typical source of confusion is that
1879 /// if result histograms go out of scope before the end of the program, ROOT might display a blank canvas).
1880 template <typename X = RDFDetail::RInferredType, typename Y = RDFDetail::RInferredType>
1881 RResultPtr<::TGraph> Graph(std::string_view x = "", std::string_view y = "")
1882 {
1883 auto graph = std::make_shared<::TGraph>();
1884 const std::vector<std::string_view> columnViews = {x, y};
1885 const auto userColumns = RDFInternal::AtLeastOneEmptyString(columnViews)
1886 ? ColumnNames_t()
1887 : ColumnNames_t(columnViews.begin(), columnViews.end());
1888
1889 const auto validatedColumns = GetValidatedColumnNames(2, userColumns);
1890
1891 // We build a default name and title based on the input columns
1892 const auto g_name = validatedColumns[0] + "_vs_" + validatedColumns[1];
1893 const auto g_title = validatedColumns[0] + " vs " + validatedColumns[1];
1894 graph->SetNameTitle(g_name.c_str(), g_title.c_str());
1895 graph->GetXaxis()->SetTitle(validatedColumns[0].c_str());
1896 graph->GetYaxis()->SetTitle(validatedColumns[1].c_str());
1897
1898 return CreateAction<RDFInternal::ActionTags::Graph, X, Y>(validatedColumns, graph, graph, fProxiedPtr);
1899 }
1900
1901 ////////////////////////////////////////////////////////////////////////////
1902 /// \brief Fill and return a TGraphAsymmErrors object (*lazy action*).
1903 /// \param[in] x The name of the column that will fill the x axis.
1904 /// \param[in] y The name of the column that will fill the y axis.
1905 /// \param[in] exl The name of the column of X low errors
1906 /// \param[in] exh The name of the column of X high errors
1907 /// \param[in] eyl The name of the column of Y low errors
1908 /// \param[in] eyh The name of the column of Y high errors
1909 /// \return the TGraphAsymmErrors wrapped in a RResultPtr.
1910 ///
1911 /// Columns can be of a container type (e.g. std::vector<double>), in which case the graph
1912 /// is filled with each one of the elements of the container.
1913 /// If Multithreading is enabled, the order in which points are inserted is undefined.
1914 ///
1915 /// This action is *lazy*: upon invocation of this method the calculation is
1916 /// booked but not executed. Also see RResultPtr.
1917 ///
1918 /// ### Example usage:
1919 /// ~~~{.cpp}
1920 /// // Deduce column types (this invocation needs jitting internally)
1921 /// auto myGAE1 = myDf.GraphAsymmErrors("xValues", "yValues", "exl", "exh", "eyl", "eyh");
1922 /// // Explicit column types
1923 /// using f = float
1924 /// auto myGAE2 = myDf.GraphAsymmErrors<f, f, f, f, f, f>("xValues", "yValues", "exl", "exh", "eyl", "eyh");
1925 /// ~~~
1926 ///
1927 /// \note Differently from other ROOT interfaces, the returned TGraphAsymmErrors is not associated to gDirectory
1928 /// and the caller is responsible for its lifetime (in particular, a typical source of confusion is that
1929 /// if result histograms go out of scope before the end of the program, ROOT might display a blank canvas).
1930 template <typename X = RDFDetail::RInferredType, typename Y = RDFDetail::RInferredType,
1931 typename EXL = RDFDetail::RInferredType, typename EXH = RDFDetail::RInferredType,
1932 typename EYL = RDFDetail::RInferredType, typename EYH = RDFDetail::RInferredType>
1934 GraphAsymmErrors(std::string_view x = "", std::string_view y = "", std::string_view exl = "",
1935 std::string_view exh = "", std::string_view eyl = "", std::string_view eyh = "")
1936 {
1937 auto graph = std::make_shared<::TGraphAsymmErrors>();
1938 const std::vector<std::string_view> columnViews = {x, y, exl, exh, eyl, eyh};
1939 const auto userColumns = RDFInternal::AtLeastOneEmptyString(columnViews)
1940 ? ColumnNames_t()
1941 : ColumnNames_t(columnViews.begin(), columnViews.end());
1942
1943 const auto validatedColumns = GetValidatedColumnNames(6, userColumns);
1944
1945 // We build a default name and title based on the input columns
1946 const auto g_name = validatedColumns[0] + "_vs_" + validatedColumns[1];
1947 const auto g_title = validatedColumns[0] + " vs " + validatedColumns[1];
1948 graph->SetNameTitle(g_name.c_str(), g_title.c_str());
1949 graph->GetXaxis()->SetTitle(validatedColumns[0].c_str());
1950 graph->GetYaxis()->SetTitle(validatedColumns[1].c_str());
1951
1952 return CreateAction<RDFInternal::ActionTags::GraphAsymmErrors, X, Y, EXL, EXH, EYL, EYH>(validatedColumns, graph,
1954 }
1955
1956 ////////////////////////////////////////////////////////////////////////////
1957 /// \brief Fill and return a one-dimensional profile (*lazy action*).
1958 /// \tparam V1 The type of the column the values of which are used to fill the profile. Inferred if not present.
1959 /// \tparam V2 The type of the column the values of which are used to fill the profile. Inferred if not present.
1960 /// \param[in] model The model to be considered to build the new return value.
1961 /// \param[in] v1Name The name of the column that will fill the x axis.
1962 /// \param[in] v2Name The name of the column that will fill the y axis.
1963 /// \return the monodimensional profile wrapped in a RResultPtr.
1964 ///
1965 /// This action is *lazy*: upon invocation of this method the calculation is
1966 /// booked but not executed. Also see RResultPtr.
1967 ///
1968 /// ### Example usage:
1969 /// ~~~{.cpp}
1970 /// // Deduce column types (this invocation needs jitting internally)
1971 /// auto myProf1 = myDf.Profile1D({"profName", "profTitle", 64u, -4., 4.}, "xValues", "yValues");
1972 /// // Explicit column types
1973 /// auto myProf2 = myDf.Graph<int, float>({"profName", "profTitle", 64u, -4., 4.}, "xValues", "yValues");
1974 /// ~~~
1975 ///
1976 /// \note Differently from other ROOT interfaces, the returned profile is not associated to gDirectory
1977 /// and the caller is responsible for its lifetime (in particular, a typical source of confusion is that
1978 /// if result histograms go out of scope before the end of the program, ROOT might display a blank canvas).
1979 template <typename V1 = RDFDetail::RInferredType, typename V2 = RDFDetail::RInferredType>
1981 Profile1D(const TProfile1DModel &model, std::string_view v1Name = "", std::string_view v2Name = "")
1982 {
1983 std::shared_ptr<::TProfile> h(nullptr);
1984 {
1985 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
1986 h = model.GetProfile();
1987 }
1988
1989 if (!RDFInternal::HistoUtils<::TProfile>::HasAxisLimits(*h)) {
1990 throw std::runtime_error("Profiles with no axes limits are not supported yet.");
1991 }
1992 const std::vector<std::string_view> columnViews = {v1Name, v2Name};
1993 const auto userColumns = RDFInternal::AtLeastOneEmptyString(columnViews)
1994 ? ColumnNames_t()
1995 : ColumnNames_t(columnViews.begin(), columnViews.end());
1996 return CreateAction<RDFInternal::ActionTags::Profile1D, V1, V2>(userColumns, h, h, fProxiedPtr);
1997 }
1998
1999 ////////////////////////////////////////////////////////////////////////////
2000 /// \brief Fill and return a one-dimensional profile (*lazy action*).
2001 /// \tparam V1 The type of the column the values of which are used to fill the profile. Inferred if not present.
2002 /// \tparam V2 The type of the column the values of which are used to fill the profile. Inferred if not present.
2003 /// \tparam W The type of the column the weights of which are used to fill the profile. Inferred if not present.
2004 /// \param[in] model The model to be considered to build the new return value.
2005 /// \param[in] v1Name The name of the column that will fill the x axis.
2006 /// \param[in] v2Name The name of the column that will fill the y axis.
2007 /// \param[in] wName The name of the column that will provide the weights.
2008 /// \return the monodimensional profile wrapped in a RResultPtr.
2009 ///
2010 /// This action is *lazy*: upon invocation of this method the calculation is
2011 /// booked but not executed. Also see RResultPtr.
2012 ///
2013 /// ### Example usage:
2014 /// ~~~{.cpp}
2015 /// // Deduce column types (this invocation needs jitting internally)
2016 /// auto myProf1 = myDf.Profile1D({"profName", "profTitle", 64u, -4., 4.}, "xValues", "yValues", "weight");
2017 /// // Explicit column types
2018 /// auto myProf2 = myDf.Profile1D<int, float, double>({"profName", "profTitle", 64u, -4., 4.},
2019 /// "xValues", "yValues", "weight");
2020 /// ~~~
2021 ///
2022 /// See the first Profile1D() overload for more details.
2023 template <typename V1 = RDFDetail::RInferredType, typename V2 = RDFDetail::RInferredType,
2024 typename W = RDFDetail::RInferredType>
2026 Profile1D(const TProfile1DModel &model, std::string_view v1Name, std::string_view v2Name, std::string_view wName)
2027 {
2028 std::shared_ptr<::TProfile> h(nullptr);
2029 {
2030 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
2031 h = model.GetProfile();
2032 }
2033
2034 if (!RDFInternal::HistoUtils<::TProfile>::HasAxisLimits(*h)) {
2035 throw std::runtime_error("Profile histograms with no axes limits are not supported yet.");
2036 }
2037 const std::vector<std::string_view> columnViews = {v1Name, v2Name, wName};
2038 const auto userColumns = RDFInternal::AtLeastOneEmptyString(columnViews)
2039 ? ColumnNames_t()
2040 : ColumnNames_t(columnViews.begin(), columnViews.end());
2041 return CreateAction<RDFInternal::ActionTags::Profile1D, V1, V2, W>(userColumns, h, h, fProxiedPtr);
2042 }
2043
2044 ////////////////////////////////////////////////////////////////////////////
2045 /// \brief Fill and return a one-dimensional profile (*lazy action*).
2046 /// See the first Profile1D() overload for more details.
2047 template <typename V1, typename V2, typename W>
2049 {
2050 return Profile1D<V1, V2, W>(model, "", "", "");
2051 }
2052
2053 ////////////////////////////////////////////////////////////////////////////
2054 /// \brief Fill and return a two-dimensional profile (*lazy action*).
2055 /// \tparam V1 The type of the column used to fill the x axis of the histogram. Inferred if not present.
2056 /// \tparam V2 The type of the column used to fill the y axis of the histogram. Inferred if not present.
2057 /// \tparam V2 The type of the column used to fill the z axis of the histogram. Inferred if not present.
2058 /// \param[in] model The returned profile will be constructed using this as a model.
2059 /// \param[in] v1Name The name of the column that will fill the x axis.
2060 /// \param[in] v2Name The name of the column that will fill the y axis.
2061 /// \param[in] v3Name The name of the column that will fill the z axis.
2062 /// \return the bidimensional profile wrapped in a RResultPtr.
2063 ///
2064 /// This action is *lazy*: upon invocation of this method the calculation is
2065 /// booked but not executed. Also see RResultPtr.
2066 ///
2067 /// ### Example usage:
2068 /// ~~~{.cpp}
2069 /// // Deduce column types (this invocation needs jitting internally)
2070 /// auto myProf1 = myDf.Profile2D({"profName", "profTitle", 40, -4, 4, 40, -4, 4, 0, 20},
2071 /// "xValues", "yValues", "zValues");
2072 /// // Explicit column types
2073 /// auto myProf2 = myDf.Profile2D<int, float, double>({"profName", "profTitle", 40, -4, 4, 40, -4, 4, 0, 20},
2074 /// "xValues", "yValues", "zValues");
2075 /// ~~~
2076 ///
2077 /// \note Differently from other ROOT interfaces, the returned profile is not associated to gDirectory
2078 /// and the caller is responsible for its lifetime (in particular, a typical source of confusion is that
2079 /// if result histograms go out of scope before the end of the program, ROOT might display a blank canvas).
2080 template <typename V1 = RDFDetail::RInferredType, typename V2 = RDFDetail::RInferredType,
2081 typename V3 = RDFDetail::RInferredType>
2082 RResultPtr<::TProfile2D> Profile2D(const TProfile2DModel &model, std::string_view v1Name = "",
2083 std::string_view v2Name = "", std::string_view v3Name = "")
2084 {
2085 std::shared_ptr<::TProfile2D> h(nullptr);
2086 {
2087 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
2088 h = model.GetProfile();
2089 }
2090
2091 if (!RDFInternal::HistoUtils<::TProfile2D>::HasAxisLimits(*h)) {
2092 throw std::runtime_error("2D profiles with no axes limits are not supported yet.");
2093 }
2094 const std::vector<std::string_view> columnViews = {v1Name, v2Name, v3Name};
2095 const auto userColumns = RDFInternal::AtLeastOneEmptyString(columnViews)
2096 ? ColumnNames_t()
2097 : ColumnNames_t(columnViews.begin(), columnViews.end());
2098 return CreateAction<RDFInternal::ActionTags::Profile2D, V1, V2, V3>(userColumns, h, h, fProxiedPtr);
2099 }
2100
2101 ////////////////////////////////////////////////////////////////////////////
2102 /// \brief Fill and return a two-dimensional profile (*lazy action*).
2103 /// \tparam V1 The type of the column used to fill the x axis of the histogram. Inferred if not present.
2104 /// \tparam V2 The type of the column used to fill the y axis of the histogram. Inferred if not present.
2105 /// \tparam V3 The type of the column used to fill the z axis of the histogram. Inferred if not present.
2106 /// \tparam W The type of the column used for the weights of the histogram. Inferred if not present.
2107 /// \param[in] model The returned histogram will be constructed using this as a model.
2108 /// \param[in] v1Name The name of the column that will fill the x axis.
2109 /// \param[in] v2Name The name of the column that will fill the y axis.
2110 /// \param[in] v3Name The name of the column that will fill the z axis.
2111 /// \param[in] wName The name of the column that will provide the weights.
2112 /// \return the bidimensional profile wrapped in a RResultPtr.
2113 ///
2114 /// This action is *lazy*: upon invocation of this method the calculation is
2115 /// booked but not executed. Also see RResultPtr.
2116 ///
2117 /// ### Example usage:
2118 /// ~~~{.cpp}
2119 /// // Deduce column types (this invocation needs jitting internally)
2120 /// auto myProf1 = myDf.Profile2D({"profName", "profTitle", 40, -4, 4, 40, -4, 4, 0, 20},
2121 /// "xValues", "yValues", "zValues", "weight");
2122 /// // Explicit column types
2123 /// auto myProf2 = myDf.Profile2D<int, float, double, int>({"profName", "profTitle", 40, -4, 4, 40, -4, 4, 0, 20},
2124 /// "xValues", "yValues", "zValues", "weight");
2125 /// ~~~
2126 ///
2127 /// See the first Profile2D() overload for more details.
2128 template <typename V1 = RDFDetail::RInferredType, typename V2 = RDFDetail::RInferredType,
2129 typename V3 = RDFDetail::RInferredType, typename W = RDFDetail::RInferredType>
2130 RResultPtr<::TProfile2D> Profile2D(const TProfile2DModel &model, std::string_view v1Name, std::string_view v2Name,
2131 std::string_view v3Name, std::string_view wName)
2132 {
2133 std::shared_ptr<::TProfile2D> h(nullptr);
2134 {
2135 ROOT::Internal::RDF::RIgnoreErrorLevelRAII iel(kError);
2136 h = model.GetProfile();
2137 }
2138
2139 if (!RDFInternal::HistoUtils<::TProfile2D>::HasAxisLimits(*h)) {
2140 throw std::runtime_error("2D profiles with no axes limits are not supported yet.");
2141 }
2142 const std::vector<std::string_view> columnViews = {v1Name, v2Name, v3Name, wName};
2143 const auto userColumns = RDFInternal::AtLeastOneEmptyString(columnViews)
2144 ? ColumnNames_t()
2145 : ColumnNames_t(columnViews.begin(), columnViews.end());
2146 return CreateAction<RDFInternal::ActionTags::Profile2D, V1, V2, V3, W>(userColumns, h, h, fProxiedPtr);
2147 }
2148
2149 /// \brief Fill and return a two-dimensional profile (*lazy action*).
2150 /// See the first Profile2D() overload for more details.
2151 template <typename V1, typename V2, typename V3, typename W>
2153 {
2154 return Profile2D<V1, V2, V3, W>(model, "", "", "", "");
2155 }
2156
2157 ////////////////////////////////////////////////////////////////////////////
2158 /// \brief Return an object of type T on which `T::Fill` will be called once per event (*lazy action*).
2159 ///
2160 /// Type T must provide at least:
2161 /// - a copy-constructor
2162 /// - a `Fill` method that accepts as many arguments and with same types as the column names passed as columnList
2163 /// (these types can also be passed as template parameters to this method)
2164 /// - a `Merge` method with signature `Merge(TCollection *)` or `Merge(const std::vector<T *>&)` that merges the
2165 /// objects passed as argument into the object on which `Merge` was called (an analogous of TH1::Merge). Note that
2166 /// if the signature that takes a `TCollection*` is used, then T must inherit from TObject (to allow insertion in
2167 /// the TCollection*).
2168 ///
2169 /// \tparam FirstColumn The first type of the column the values of which are used to fill the object. Inferred together with OtherColumns if not present.
2170 /// \tparam OtherColumns A list of the other types of the columns the values of which are used to fill the object.
2171 /// \tparam T The type of the object to fill. Automatically deduced.
2172 /// \param[in] model The model to be considered to build the new return value.
2173 /// \param[in] columnList A list containing the names of the columns that will be passed when calling `Fill`
2174 /// \return the filled object wrapped in a RResultPtr.
2175 ///
2176 /// The user gives up ownership of the model object.
2177 /// The list of column names to be used for filling must always be specified.
2178 /// This action is *lazy*: upon invocation of this method the calculation is booked but not executed.
2179 /// Also see RResultPtr.
2180 ///
2181 /// ### Example usage:
2182 /// ~~~{.cpp}
2183 /// MyClass obj;
2184 /// // Deduce column types (this invocation needs jitting internally, and in this case
2185 /// // MyClass needs to be known to the interpreter)
2186 /// auto myFilledObj = myDf.Fill(obj, {"col0", "col1"});
2187 /// // explicit column types
2188 /// auto myFilledObj = myDf.Fill<float, float>(obj, {"col0", "col1"});
2189 /// ~~~
2190 ///
2191 template <typename FirstColumn = RDFDetail::RInferredType, typename... OtherColumns, typename T>
2192 RResultPtr<std::decay_t<T>> Fill(T &&model, const ColumnNames_t &columnList)
2193 {
2194 auto h = std::make_shared<std::decay_t<T>>(std::forward<T>(model));
2195 if (!RDFInternal::HistoUtils<T>::HasAxisLimits(*h)) {
2196 throw std::runtime_error("The absence of axes limits is not supported yet.");
2197 }
2198 return CreateAction<RDFInternal::ActionTags::Fill, FirstColumn, OtherColumns...>(columnList, h, h, fProxiedPtr,
2199 columnList.size());
2200 }
2201
2202 ////////////////////////////////////////////////////////////////////////////
2203 /// \brief Return a TStatistic object, filled once per event (*lazy action*).
2204 ///
2205 /// \tparam V The type of the value column
2206 /// \param[in] value The name of the column with the values to fill the statistics with.
2207 /// \return the filled TStatistic object wrapped in a RResultPtr.
2208 ///
2209 /// ### Example usage:
2210 /// ~~~{.cpp}
2211 /// // Deduce column type (this invocation needs jitting internally)
2212 /// auto stats0 = myDf.Stats("values");
2213 /// // Explicit column type
2214 /// auto stats1 = myDf.Stats<float>("values");
2215 /// ~~~
2216 ///
2217 template <typename V = RDFDetail::RInferredType>
2218 RResultPtr<TStatistic> Stats(std::string_view value = "")
2219 {
2220 ColumnNames_t columns;
2221 if (!value.empty()) {
2222 columns.emplace_back(std::string(value));
2223 }
2224 const auto validColumnNames = GetValidatedColumnNames(1, columns);
2225 if (std::is_same<V, RDFDetail::RInferredType>::value) {
2226 return Fill(TStatistic(), validColumnNames);
2227 } else {
2228 return Fill<V>(TStatistic(), validColumnNames);
2229 }
2230 }
2231
2232 ////////////////////////////////////////////////////////////////////////////
2233 /// \brief Return a TStatistic object, filled once per event (*lazy action*).
2234 ///
2235 /// \tparam V The type of the value column
2236 /// \tparam W The type of the weight column
2237 /// \param[in] value The name of the column with the values to fill the statistics with.
2238 /// \param[in] weight The name of the column with the weights to fill the statistics with.
2239 /// \return the filled TStatistic object wrapped in a RResultPtr.
2240 ///
2241 /// ### Example usage:
2242 /// ~~~{.cpp}
2243 /// // Deduce column types (this invocation needs jitting internally)
2244 /// auto stats0 = myDf.Stats("values", "weights");
2245 /// // Explicit column types
2246 /// auto stats1 = myDf.Stats<int, float>("values", "weights");
2247 /// ~~~
2248 ///
2249 template <typename V = RDFDetail::RInferredType, typename W = RDFDetail::RInferredType>
2250 RResultPtr<TStatistic> Stats(std::string_view value, std::string_view weight)
2251 {
2252 ColumnNames_t columns{std::string(value), std::string(weight)};
2253 constexpr auto vIsInferred = std::is_same<V, RDFDetail::RInferredType>::value;
2254 constexpr auto wIsInferred = std::is_same<W, RDFDetail::RInferredType>::value;
2255 const auto validColumnNames = GetValidatedColumnNames(2, columns);
2256 // We have 3 cases:
2257 // 1. Both types are inferred: we use Fill and let the jit kick in.
2258 // 2. One of the two types is explicit and the other one is inferred: the case is not supported.
2259 // 3. Both types are explicit: we invoke the fully compiled Fill method.
2260 if (vIsInferred && wIsInferred) {
2261 return Fill(TStatistic(), validColumnNames);
2262 } else if (vIsInferred != wIsInferred) {
2263 std::string error("The ");
2264 error += vIsInferred ? "value " : "weight ";
2265 error += "column type is explicit, while the ";
2266 error += vIsInferred ? "weight " : "value ";
2267 error += " is specified to be inferred. This case is not supported: please specify both types or none.";
2268 throw std::runtime_error(error);
2269 } else {
2270 return Fill<V, W>(TStatistic(), validColumnNames);
2271 }
2272 }
2273
2274 ////////////////////////////////////////////////////////////////////////////
2275 /// \brief Return the minimum of processed column values (*lazy action*).
2276 /// \tparam T The type of the branch/column.
2277 /// \param[in] columnName The name of the branch/column to be treated.
2278 /// \return the minimum value of the selected column wrapped in a RResultPtr.
2279 ///
2280 /// If T is not specified, RDataFrame will infer it from the data and just-in-time compile the correct
2281 /// template specialization of this method.
2282 /// If the type of the column is inferred, the return type is `double`, the type of the column otherwise.
2283 ///
2284 /// This action is *lazy*: upon invocation of this method the calculation is
2285 /// booked but not executed. Also see RResultPtr.
2286 ///
2287 /// ### Example usage:
2288 /// ~~~{.cpp}
2289 /// // Deduce column type (this invocation needs jitting internally)
2290 /// auto minVal0 = myDf.Min("values");
2291 /// // Explicit column type
2292 /// auto minVal1 = myDf.Min<double>("values");
2293 /// ~~~
2294 ///
2295 template <typename T = RDFDetail::RInferredType>
2296 RResultPtr<RDFDetail::MinReturnType_t<T>> Min(std::string_view columnName = "")
2297 {
2298 const auto userColumns = columnName.empty() ? ColumnNames_t() : ColumnNames_t({std::string(columnName)});
2299 using RetType_t = RDFDetail::MinReturnType_t<T>;
2300 auto minV = std::make_shared<RetType_t>(std::numeric_limits<RetType_t>::max());
2301 return CreateAction<RDFInternal::ActionTags::Min, T>(userColumns, minV, minV, fProxiedPtr);
2302 }
2303
2304 ////////////////////////////////////////////////////////////////////////////
2305 /// \brief Return the maximum of processed column values (*lazy action*).
2306 /// \tparam T The type of the branch/column.
2307 /// \param[in] columnName The name of the branch/column to be treated.
2308 /// \return the maximum value of the selected column wrapped in a RResultPtr.
2309 ///
2310 /// If T is not specified, RDataFrame will infer it from the data and just-in-time compile the correct
2311 /// template specialization of this method.
2312 /// If the type of the column is inferred, the return type is `double`, the type of the column otherwise.
2313 ///
2314 /// This action is *lazy*: upon invocation of this method the calculation is
2315 /// booked but not executed. Also see RResultPtr.
2316 ///
2317 /// ### Example usage:
2318 /// ~~~{.cpp}
2319 /// // Deduce column type (this invocation needs jitting internally)
2320 /// auto maxVal0 = myDf.Max("values");
2321 /// // Explicit column type
2322 /// auto maxVal1 = myDf.Max<double>("values");
2323 /// ~~~
2324 ///
2325 template <typename T = RDFDetail::RInferredType>
2326 RResultPtr<RDFDetail::MaxReturnType_t<T>> Max(std::string_view columnName = "")
2327 {
2328 const auto userColumns = columnName.empty() ? ColumnNames_t() : ColumnNames_t({std::string(columnName)});
2329 using RetType_t = RDFDetail::MaxReturnType_t<T>;
2330 auto maxV = std::make_shared<RetType_t>(std::numeric_limits<RetType_t>::lowest());
2331 return CreateAction<RDFInternal::ActionTags::Max, T>(userColumns, maxV, maxV, fProxiedPtr);
2332 }
2333
2334 ////////////////////////////////////////////////////////////////////////////
2335 /// \brief Return the mean of processed column values (*lazy action*).
2336 /// \tparam T The type of the branch/column.
2337 /// \param[in] columnName The name of the branch/column to be treated.
2338 /// \return the mean value of the selected column wrapped in a RResultPtr.
2339 ///
2340 /// If T is not specified, RDataFrame will infer it from the data and just-in-time compile the correct
2341 /// template specialization of this method.
2342 ///
2343 /// This action is *lazy*: upon invocation of this method the calculation is
2344 /// booked but not executed. Also see RResultPtr.
2345 ///
2346 /// ### Example usage:
2347 /// ~~~{.cpp}
2348 /// // Deduce column type (this invocation needs jitting internally)
2349 /// auto meanVal0 = myDf.Mean("values");
2350 /// // Explicit column type
2351 /// auto meanVal1 = myDf.Mean<double>("values");
2352 /// ~~~
2353 ///
2354 template <typename T = RDFDetail::RInferredType>
2355 RResultPtr<double> Mean(std::string_view columnName = "")
2356 {
2357 const auto userColumns = columnName.empty() ? ColumnNames_t() : ColumnNames_t({std::string(columnName)});
2358 auto meanV = std::make_shared<double>(0);
2359 return CreateAction<RDFInternal::ActionTags::Mean, T>(userColumns, meanV, meanV, fProxiedPtr);
2360 }
2361
2362 ////////////////////////////////////////////////////////////////////////////
2363 /// \brief Return the unbiased standard deviation of processed column values (*lazy action*).
2364 /// \tparam T The type of the branch/column.
2365 /// \param[in] columnName The name of the branch/column to be treated.
2366 /// \return the standard deviation value of the selected column wrapped in a RResultPtr.
2367 ///
2368 /// If T is not specified, RDataFrame will infer it from the data and just-in-time compile the correct
2369 /// template specialization of this method.
2370 ///
2371 /// This action is *lazy*: upon invocation of this method the calculation is
2372 /// booked but not executed. Also see RResultPtr.
2373 ///
2374 /// ### Example usage:
2375 /// ~~~{.cpp}
2376 /// // Deduce column type (this invocation needs jitting internally)
2377 /// auto stdDev0 = myDf.StdDev("values");
2378 /// // Explicit column type
2379 /// auto stdDev1 = myDf.StdDev<double>("values");
2380 /// ~~~
2381 ///
2382 template <typename T = RDFDetail::RInferredType>
2383 RResultPtr<double> StdDev(std::string_view columnName = "")
2384 {
2385 const auto userColumns = columnName.empty() ? ColumnNames_t() : ColumnNames_t({std::string(columnName)});
2386 auto stdDeviationV = std::make_shared<double>(0);
2387 return CreateAction<RDFInternal::ActionTags::StdDev, T>(userColumns, stdDeviationV, stdDeviationV, fProxiedPtr);
2388 }
2389
2390 // clang-format off
2391 ////////////////////////////////////////////////////////////////////////////
2392 /// \brief Return the sum of processed column values (*lazy action*).
2393 /// \tparam T The type of the branch/column.
2394 /// \param[in] columnName The name of the branch/column.
2395 /// \param[in] initValue Optional initial value for the sum. If not present, the column values must be default-constructible.
2396 /// \return the sum of the selected column wrapped in a RResultPtr.
2397 ///
2398 /// If T is not specified, RDataFrame will infer it from the data and just-in-time compile the correct
2399 /// template specialization of this method.
2400 /// If the type of the column is inferred, the return type is `double`, the type of the column otherwise.
2401 ///
2402 /// This action is *lazy*: upon invocation of this method the calculation is
2403 /// booked but not executed. Also see RResultPtr.
2404 ///
2405 /// ### Example usage:
2406 /// ~~~{.cpp}
2407 /// // Deduce column type (this invocation needs jitting internally)
2408 /// auto sum0 = myDf.Sum("values");
2409 /// // Explicit column type
2410 /// auto sum1 = myDf.Sum<double>("values");
2411 /// ~~~
2412 ///
2413 template <typename T = RDFDetail::RInferredType>
2415 Sum(std::string_view columnName = "",
2416 const RDFDetail::SumReturnType_t<T> &initValue = RDFDetail::SumReturnType_t<T>{})
2417 {
2418 const auto userColumns = columnName.empty() ? ColumnNames_t() : ColumnNames_t({std::string(columnName)});
2419 auto sumV = std::make_shared<RDFDetail::SumReturnType_t<T>>(initValue);
2420 return CreateAction<RDFInternal::ActionTags::Sum, T>(userColumns, sumV, sumV, fProxiedPtr);
2421 }
2422 // clang-format on
2423
2424 ////////////////////////////////////////////////////////////////////////////
2425 /// \brief Gather filtering statistics.
2426 /// \return the resulting `RCutFlowReport` instance wrapped in a RResultPtr.
2427 ///
2428 /// Calling `Report` on the main `RDataFrame` object gathers stats for
2429 /// all named filters in the call graph. Calling this method on a
2430 /// stored chain state (i.e. a graph node different from the first) gathers
2431 /// the stats for all named filters in the chain section between the original
2432 /// `RDataFrame` and that node (included). Stats are gathered in the same
2433 /// order as the named filters have been added to the graph.
2434 /// A RResultPtr<RCutFlowReport> is returned to allow inspection of the
2435 /// effects cuts had.
2436 ///
2437 /// This action is *lazy*: upon invocation of
2438 /// this method the calculation is booked but not executed. See RResultPtr
2439 /// documentation.
2440 ///
2441 /// ### Example usage:
2442 /// ~~~{.cpp}
2443 /// auto filtered = d.Filter(cut1, {"b1"}, "Cut1").Filter(cut2, {"b2"}, "Cut2");
2444 /// auto cutReport = filtered3.Report();
2445 /// cutReport->Print();
2446 /// ~~~
2447 ///
2449 {
2450 bool returnEmptyReport = false;
2451 // if this is a RInterface<RLoopManager> on which `Define` has been called, users
2452 // are calling `Report` on a chain of the form LoopManager->Define->Define->..., which
2453 // certainly does not contain named filters.
2454 // The number 4 takes into account the implicit columns for entry and slot number
2455 // and their aliases (2 + 2, i.e. {r,t}dfentry_ and {r,t}dfslot_)
2456 if (std::is_same<Proxied, RLoopManager>::value && fColRegister.GetNames().size() > 4)
2457 returnEmptyReport = true;
2458
2459 auto rep = std::make_shared<RCutFlowReport>();
2460 using Helper_t = RDFInternal::ReportHelper<Proxied>;
2462
2463 auto action = std::make_unique<Action_t>(Helper_t(rep, fProxiedPtr.get(), returnEmptyReport), ColumnNames_t({}),
2465
2466 return MakeResultPtr(rep, *fLoopManager, std::move(action));
2467 }
2468
2469 /// \brief Returns the names of the filters created.
2470 /// \return the container of filters names.
2471 ///
2472 /// If called on a root node, all the filters in the computation graph will
2473 /// be printed. For any other node, only the filters upstream of that node.
2474 /// Filters without a name are printed as "Unnamed Filter"
2475 /// This is not an action nor a transformation, just a query to the RDataFrame object.
2476 ///
2477 /// ### Example usage:
2478 /// ~~~{.cpp}
2479 /// auto filtNames = d.GetFilterNames();
2480 /// for (auto &&filtName : filtNames) std::cout << filtName << std::endl;
2481 /// ~~~
2482 ///
2483 std::vector<std::string> GetFilterNames() { return RDFInternal::GetFilterNames(fProxiedPtr); }
2484
2485 // clang-format off
2486 ////////////////////////////////////////////////////////////////////////////
2487 /// \brief Execute a user-defined accumulation operation on the processed column values in each processing slot.
2488 /// \tparam F The type of the aggregator callable. Automatically deduced.
2489 /// \tparam U The type of the aggregator variable. Must be default-constructible, copy-constructible and copy-assignable. Automatically deduced.
2490 /// \tparam T The type of the column to apply the reduction to. Automatically deduced.
2491 /// \param[in] aggregator A callable with signature `U(U,T)` or `void(U&,T)`, where T is the type of the column, U is the type of the aggregator variable
2492 /// \param[in] merger A callable with signature `U(U,U)` or `void(std::vector<U>&)` used to merge the results of the accumulations of each thread
2493 /// \param[in] columnName The column to be aggregated. If omitted, the first default column is used instead.
2494 /// \param[in] aggIdentity The aggregator variable of each thread is initialized to this value (or is default-constructed if the parameter is omitted)
2495 /// \return the result of the aggregation wrapped in a RResultPtr.
2496 ///
2497 /// An aggregator callable takes two values, an aggregator variable and a column value. The aggregator variable is
2498 /// initialized to aggIdentity or default-constructed if aggIdentity is omitted.
2499 /// This action calls the aggregator callable for each processed entry, passing in the aggregator variable and
2500 /// the value of the column columnName.
2501 /// If the signature is `U(U,T)` the aggregator variable is then copy-assigned the result of the execution of the callable.
2502 /// Otherwise the signature of aggregator must be `void(U&,T)`.
2503 ///
2504 /// The merger callable is used to merge the partial accumulation results of each processing thread. It is only called in multi-thread executions.
2505 /// If its signature is `U(U,U)` the aggregator variables of each thread are merged two by two.
2506 /// If its signature is `void(std::vector<U>& a)` it is assumed that it merges all aggregators in a[0].
2507 ///
2508 /// This action is *lazy*: upon invocation of this method the calculation is booked but not executed. Also see RResultPtr.
2509 ///
2510 /// Example usage:
2511 /// ~~~{.cpp}
2512 /// auto aggregator = [](double acc, double x) { return acc * x; };
2513 /// ROOT::EnableImplicitMT();
2514 /// // If multithread is enabled, the aggregator function will be called by more threads
2515 /// // and will produce a vector of partial accumulators.
2516 /// // The merger function performs the final aggregation of these partial results.
2517 /// auto merger = [](std::vector<double> &accumulators) {
2518 /// for (auto i : ROOT::TSeqU(1u, accumulators.size())) {
2519 /// accumulators[0] *= accumulators[i];
2520 /// }
2521 /// };
2522 ///
2523 /// // The accumulator is initialized at this value by every thread.
2524 /// double initValue = 1.;
2525 ///
2526 /// // Multiplies all elements of the column "x"
2527 /// auto result = d.Aggregate(aggregator, merger, columnName, initValue);
2528 /// ~~~
2529 // clang-format on
2530 template <typename AccFun, typename MergeFun, typename R = typename TTraits::CallableTraits<AccFun>::ret_type,
2531 typename ArgTypes = typename TTraits::CallableTraits<AccFun>::arg_types,
2532 typename ArgTypesNoDecay = typename TTraits::CallableTraits<AccFun>::arg_types_nodecay,
2533 typename U = TTraits::TakeFirstParameter_t<ArgTypes>,
2534 typename T = TTraits::TakeFirstParameter_t<TTraits::RemoveFirstParameter_t<ArgTypes>>>
2535 RResultPtr<U> Aggregate(AccFun aggregator, MergeFun merger, std::string_view columnName, const U &aggIdentity)
2536 {
2537 RDFInternal::CheckAggregate<R, MergeFun>(ArgTypesNoDecay());
2538 const auto columns = columnName.empty() ? ColumnNames_t() : ColumnNames_t({std::string(columnName)});
2539
2540 const auto validColumnNames = GetValidatedColumnNames(1, columns);
2541 CheckAndFillDSColumns(validColumnNames, TTraits::TypeList<T>());
2542
2543 auto accObjPtr = std::make_shared<U>(aggIdentity);
2544 using Helper_t = RDFInternal::AggregateHelper<AccFun, MergeFun, R, T, U>;
2546 auto action = std::make_unique<Action_t>(
2547 Helper_t(std::move(aggregator), std::move(merger), accObjPtr, fLoopManager->GetNSlots()), validColumnNames,
2549 return MakeResultPtr(accObjPtr, *fLoopManager, std::move(action));
2550 }
2551
2552 // clang-format off
2553 ////////////////////////////////////////////////////////////////////////////
2554 /// \brief Execute a user-defined accumulation operation on the processed column values in each processing slot.
2555 /// \tparam F The type of the aggregator callable. Automatically deduced.
2556 /// \tparam U The type of the aggregator variable. Must be default-constructible, copy-constructible and copy-assignable. Automatically deduced.
2557 /// \tparam T The type of the column to apply the reduction to. Automatically deduced.
2558 /// \param[in] aggregator A callable with signature `U(U,T)` or `void(U,T)`, where T is the type of the column, U is the type of the aggregator variable
2559 /// \param[in] merger A callable with signature `U(U,U)` or `void(std::vector<U>&)` used to merge the results of the accumulations of each thread
2560 /// \param[in] columnName The column to be aggregated. If omitted, the first default column is used instead.
2561 /// \return the result of the aggregation wrapped in a RResultPtr.
2562 ///
2563 /// See previous Aggregate overload for more information.
2564 // clang-format on
2565 template <typename AccFun, typename MergeFun, typename R = typename TTraits::CallableTraits<AccFun>::ret_type,
2566 typename ArgTypes = typename TTraits::CallableTraits<AccFun>::arg_types,
2567 typename U = TTraits::TakeFirstParameter_t<ArgTypes>,
2568 typename T = TTraits::TakeFirstParameter_t<TTraits::RemoveFirstParameter_t<ArgTypes>>>
2569 RResultPtr<U> Aggregate(AccFun aggregator, MergeFun merger, std::string_view columnName = "")
2570 {
2571 static_assert(
2572 std::is_default_constructible<U>::value,
2573 "aggregated object cannot be default-constructed. Please provide an initialisation value (aggIdentity)");
2574 return Aggregate(std::move(aggregator), std::move(merger), columnName, U());
2575 }
2576
2577 // clang-format off
2578 ////////////////////////////////////////////////////////////////////////////
2579 /// \brief Book execution of a custom action using a user-defined helper object.
2580 /// \tparam FirstColumn The type of the first column used by this action. Inferred together with OtherColumns if not present.
2581 /// \tparam OtherColumns A list of the types of the other columns used by this action
2582 /// \tparam Helper The type of the user-defined helper. See below for the required interface it should expose.
2583 /// \param[in] helper The Action Helper to be scheduled.
2584 /// \param[in] columns The names of the columns on which the helper acts.
2585 /// \return the result of the helper wrapped in a RResultPtr.
2586 ///
2587 /// This method books a custom action for execution. The behavior of the action is completely dependent on the
2588 /// Helper object provided by the caller. The minimum required interface for the helper is the following (more
2589 /// methods can be present, e.g. a constructor that takes the number of worker threads is usually useful):
2590 ///
2591 /// * Helper must publicly inherit from ROOT::Detail::RDF::RActionImpl<Helper>
2592 /// * Helper(Helper &&): a move-constructor is required. Copy-constructors are discouraged.
2593 /// * Result_t: alias for the type of the result of this action helper. Must be default-constructible.
2594 /// * void Exec(unsigned int slot, ColumnTypes...columnValues): each working thread shall call this method
2595 /// during the event-loop, possibly concurrently. No two threads will ever call Exec with the same 'slot' value:
2596 /// this parameter is there to facilitate writing thread-safe helpers. The other arguments will be the values of
2597 /// the requested columns for the particular entry being processed.
2598 /// * void InitTask(TTreeReader *, unsigned int slot): each working thread shall call this method during the event
2599 /// loop, before processing a batch of entries (possibly read from the TTreeReader passed as argument, if not null).
2600 /// This method can be used e.g. to prepare the helper to process a batch of entries in a given thread. Can be no-op.
2601 /// * void Initialize(): this method is called once before starting the event-loop. Useful for setup operations.
2602 /// It must reset the state of the helper to the expected state at the beginning of the event loop: the same helper,
2603 /// or copies of it, might be used for multiple event loops (e.g. in the presence of systematic variations).
2604 /// * void Finalize(): this method is called at the end of the event loop. Commonly used to finalize the contents of the result.
2605 /// * Result_t &PartialUpdate(unsigned int slot): this method is optional, i.e. can be omitted. If present, it should
2606 /// return the value of the partial result of this action for the given 'slot'. Different threads might call this
2607 /// method concurrently, but will always pass different 'slot' numbers.
2608 /// * std::shared_ptr<Result_t> GetResultPtr() const: return a shared_ptr to the result of this action (of type
2609 /// Result_t). The RResultPtr returned by Book will point to this object. Note that this method can be called
2610 /// before Initialize(), because the RResultPtr is constructed before the event loop is started.
2611 /// * ROOT::RDF::SampleCallback_t GetSampleCallback(): optional. If present, it must return a callable with the
2612 /// appropriate signature (see ROOT::RDF::SampleCallback_t) that will be invoked at the beginning of the processing
2613 /// of every sample, as per with DefinePerSample().
2614 ///
2615 /// In case this is called without specifying column types, jitting is used,
2616 /// and the Helper class needs to be known to the interpreter.<br>
2617 /// This action is *lazy*: upon invocation of this method the calculation is booked but not executed. Also see RResultPtr.
2618 ///
2619 /// ### Examples
2620 /// See [this tutorial](https://root.cern/doc/master/df018__customActions_8C.html) for an example implementation of an action helper.<br>
2621 /// It is also possible to inspect the code used by built-in RDataFrame actions at ActionHelpers.hxx.
2622 ///
2623 // clang-format on
2624
2625 template <typename FirstColumn = RDFDetail::RInferredType, typename... OtherColumns, typename Helper>
2627 {
2628 using HelperT = std::decay_t<Helper>;
2629 // TODO add more static sanity checks on Helper
2631 static_assert(std::is_base_of<AH, HelperT>::value && std::is_convertible<HelperT *, AH *>::value,
2632 "Action helper of type T must publicly inherit from ROOT::Detail::RDF::RActionImpl<T>");
2633
2634 auto hPtr = std::make_shared<HelperT>(std::forward<Helper>(helper));
2635 auto resPtr = hPtr->GetResultPtr();
2636
2637 if (std::is_same<FirstColumn, RDFDetail::RInferredType>::value && columns.empty()) {
2638 return CallCreateActionWithoutColsIfPossible<HelperT>(resPtr, hPtr, TTraits::TypeList<FirstColumn>{});
2639 } else {
2640 return CreateAction<RDFInternal::ActionTags::Book, FirstColumn, OtherColumns...>(columns, resPtr, hPtr,
2641 fProxiedPtr, columns.size());
2642 }
2643 }
2644
2645 ////////////////////////////////////////////////////////////////////////////
2646 /// \brief Provides a representation of the columns in the dataset.
2647 /// \tparam ColumnTypes variadic list of branch/column types.
2648 /// \param[in] columnList Names of the columns to be displayed.
2649 /// \param[in] nRows Number of events for each column to be displayed.
2650 /// \param[in] nMaxCollectionElements Maximum number of collection elements to display per row.
2651 /// \return the `RDisplay` instance wrapped in a RResultPtr.
2652 ///
2653 /// This function returns a `RResultPtr<RDisplay>` containing all the entries to be displayed, organized in a tabular
2654 /// form. RDisplay will either print on the standard output a summarized version through `RDisplay::Print()` or will
2655 /// return a complete version through `RDisplay::AsString()`.
2656 ///
2657 /// This action is *lazy*: upon invocation of this method the calculation is booked but not executed. Also see
2658 /// RResultPtr.
2659 ///
2660 /// Example usage:
2661 /// ~~~{.cpp}
2662 /// // Preparing the RResultPtr<RDisplay> object with all columns and default number of entries
2663 /// auto d1 = rdf.Display("");
2664 /// // Preparing the RResultPtr<RDisplay> object with two columns and 128 entries
2665 /// auto d2 = d.Display({"x", "y"}, 128);
2666 /// // Printing the short representations, the event loop will run
2667 /// d1->Print();
2668 /// d2->Print();
2669 /// ~~~
2670 template <typename... ColumnTypes>
2671 RResultPtr<RDisplay> Display(const ColumnNames_t &columnList, size_t nRows = 5, size_t nMaxCollectionElements = 10)
2672 {
2673 CheckIMTDisabled("Display");
2674 auto newCols = columnList;
2675 newCols.insert(newCols.begin(), "rdfentry_"); // Artificially insert first column
2676 auto displayer = std::make_shared<RDisplay>(newCols, GetColumnTypeNamesList(newCols), nMaxCollectionElements);
2677 using displayHelperArgs_t = std::pair<size_t, std::shared_ptr<RDisplay>>;
2678 // Need to add ULong64_t type corresponding to the first column rdfentry_
2679 return CreateAction<RDFInternal::ActionTags::Display, ULong64_t, ColumnTypes...>(
2680 std::move(newCols), displayer, std::make_shared<displayHelperArgs_t>(nRows, displayer), fProxiedPtr);
2681 }
2682
2683 ////////////////////////////////////////////////////////////////////////////
2684 /// \brief Provides a representation of the columns in the dataset.
2685 /// \param[in] columnList Names of the columns to be displayed.
2686 /// \param[in] nRows Number of events for each column to be displayed.
2687 /// \param[in] nMaxCollectionElements Maximum number of collection elements to display per row.
2688 /// \return the `RDisplay` instance wrapped in a RResultPtr.
2689 ///
2690 /// This overload automatically infers the column types.
2691 /// See the previous overloads for further details.
2692 ///
2693 /// Invoked when no types are specified to Display
2694 RResultPtr<RDisplay> Display(const ColumnNames_t &columnList, size_t nRows = 5, size_t nMaxCollectionElements = 10)
2695 {
2696 CheckIMTDisabled("Display");
2697 auto newCols = columnList;
2698 newCols.insert(newCols.begin(), "rdfentry_"); // Artificially insert first column
2699 auto displayer = std::make_shared<RDisplay>(newCols, GetColumnTypeNamesList(newCols), nMaxCollectionElements);
2700 using displayHelperArgs_t = std::pair<size_t, std::shared_ptr<RDisplay>>;
2701 return CreateAction<RDFInternal::ActionTags::Display, RDFDetail::RInferredType>(
2702 std::move(newCols), displayer, std::make_shared<displayHelperArgs_t>(nRows, displayer), fProxiedPtr,
2703 columnList.size() + 1);
2704 }
2705
2706 ////////////////////////////////////////////////////////////////////////////
2707 /// \brief Provides a representation of the columns in the dataset.
2708 /// \param[in] columnNameRegexp A regular expression to select the columns.
2709 /// \param[in] nRows Number of events for each column to be displayed.
2710 /// \param[in] nMaxCollectionElements Maximum number of collection elements to display per row.
2711 /// \return the `RDisplay` instance wrapped in a RResultPtr.
2712 ///
2713 /// The existing columns are matched against the regular expression. If the string provided
2714 /// is empty, all columns are selected.
2715 /// See the previous overloads for further details.
2717 Display(std::string_view columnNameRegexp = "", size_t nRows = 5, size_t nMaxCollectionElements = 10)
2718 {
2719 const auto columnNames = GetColumnNames();
2720 const auto selectedColumns = RDFInternal::ConvertRegexToColumns(columnNames, columnNameRegexp, "Display");
2721 return Display(selectedColumns, nRows, nMaxCollectionElements);
2722 }
2723
2724 ////////////////////////////////////////////////////////////////////////////
2725 /// \brief Provides a representation of the columns in the dataset.
2726 /// \param[in] columnList Names of the columns to be displayed.
2727 /// \param[in] nRows Number of events for each column to be displayed.
2728 /// \param[in] nMaxCollectionElements Number of maximum elements in collection.
2729 /// \return the `RDisplay` instance wrapped in a RResultPtr.
2730 ///
2731 /// See the previous overloads for further details.
2733 Display(std::initializer_list<std::string> columnList, size_t nRows = 5, size_t nMaxCollectionElements = 10)
2734 {
2735 ColumnNames_t selectedColumns(columnList);
2736 return Display(selectedColumns, nRows, nMaxCollectionElements);
2737 }
2738
2739private:
2740 template <typename F, typename DefineType, typename RetType = typename TTraits::CallableTraits<F>::ret_type>
2741 std::enable_if_t<std::is_default_constructible<RetType>::value, RInterface<Proxied, DS_t>>
2742 DefineImpl(std::string_view name, F &&expression, const ColumnNames_t &columns, const std::string &where)
2743 {
2744 if (where.compare(0, 8, "Redefine") != 0) { // not a Redefine
2748 } else {
2752 }
2753
2754 using ArgTypes_t = typename TTraits::CallableTraits<F>::arg_types;
2755 using ColTypesTmp_t = typename RDFInternal::RemoveFirstParameterIf<
2756 std::is_same<DefineType, RDFDetail::ExtraArgsForDefine::Slot>::value, ArgTypes_t>::type;
2757 using ColTypes_t = typename RDFInternal::RemoveFirstTwoParametersIf<
2758 std::is_same<DefineType, RDFDetail::ExtraArgsForDefine::SlotAndEntry>::value, ColTypesTmp_t>::type;
2759
2760 constexpr auto nColumns = ColTypes_t::list_size;
2761
2762 const auto validColumnNames = GetValidatedColumnNames(nColumns, columns);
2763 CheckAndFillDSColumns(validColumnNames, ColTypes_t());
2764
2765 // Declare return type to the interpreter, for future use by jitted actions
2766 auto retTypeName = RDFInternal::TypeID2TypeName(typeid(RetType));
2767 if (retTypeName.empty()) {
2768 // The type is not known to the interpreter.
2769 // We must not error out here, but if/when this column is used in jitted code
2770 const auto demangledType = RDFInternal::DemangleTypeIdName(typeid(RetType));
2771 retTypeName = "CLING_UNKNOWN_TYPE_" + demangledType;
2772 }
2773
2774 using NewCol_t = RDFDetail::RDefine<F, DefineType>;
2775 auto newColumn = std::make_shared<NewCol_t>(name, retTypeName, std::forward<F>(expression), validColumnNames,
2777
2779 newCols.AddDefine(std::move(newColumn));
2780
2781 RInterface<Proxied> newInterface(fProxiedPtr, *fLoopManager, std::move(newCols));
2782
2783 return newInterface;
2784 }
2785
2786 // This overload is chosen when the callable passed to Define or DefineSlot returns void.
2787 // It simply fires a compile-time error. This is preferable to a static_assert in the main `Define` overload because
2788 // this way compilation of `Define` has no way to continue after throwing the error.
2789 template <typename F, typename DefineType, typename RetType = typename TTraits::CallableTraits<F>::ret_type,
2790 bool IsFStringConv = std::is_convertible<F, std::string>::value,
2791 bool IsRetTypeDefConstr = std::is_default_constructible<RetType>::value>
2792 std::enable_if_t<!IsFStringConv && !IsRetTypeDefConstr, RInterface<Proxied, DS_t>>
2793 DefineImpl(std::string_view, F, const ColumnNames_t &, const std::string &)
2794 {
2795 static_assert(std::is_default_constructible<typename TTraits::CallableTraits<F>::ret_type>::value,
2796 "Error in `Define`: type returned by expression is not default-constructible");
2797 return *this; // never reached
2798 }
2799
2800 template <typename... ColumnTypes>
2801 RResultPtr<RInterface<RLoopManager>> SnapshotImpl(std::string_view fullTreeName, std::string_view filename,
2802 const ColumnNames_t &columnList, const RSnapshotOptions &options)
2803 {
2804 const auto columnListWithoutSizeColumns = RDFInternal::FilterArraySizeColNames(columnList, "Snapshot");
2805
2806 RDFInternal::CheckTypesAndPars(sizeof...(ColumnTypes), columnListWithoutSizeColumns.size());
2807 // validCols has aliases resolved, while columnListWithoutSizeColumns still has aliases in it.
2808 const auto validCols = GetValidatedColumnNames(columnListWithoutSizeColumns.size(), columnListWithoutSizeColumns);
2811
2812 const auto parsedTreePath = RDFInternal::ParseTreePath(fullTreeName);
2813 const auto &treename = parsedTreePath.fTreeName;
2814 const auto &dirname = parsedTreePath.fDirName;
2815
2816 auto snapHelperArgs = std::make_shared<RDFInternal::SnapshotHelperArgs>(RDFInternal::SnapshotHelperArgs{
2817 std::string(filename), std::string(dirname), std::string(treename), columnListWithoutSizeColumns, options});
2818
2820 auto newRDF =
2821 std::make_shared<ROOT::RDataFrame>(fullTreeName, filename, /*defaultColumns=*/columnListWithoutSizeColumns);
2822
2823 // The Snapshot helper will use validCols (with aliases resolved) as input columns, and
2824 // columnListWithoutSizeColumns (still with aliases in it, passed through snapHelperArgs) as output column names.
2825 auto resPtr = CreateAction<RDFInternal::ActionTags::Snapshot, ColumnTypes...>(validCols, newRDF, snapHelperArgs,
2826 fProxiedPtr);
2827
2828 if (!options.fLazy)
2829 *resPtr;
2830 return resPtr;
2831 }
2832
2833 ////////////////////////////////////////////////////////////////////////////
2834 /// \brief Implementation of cache.
2835 template <typename... ColTypes, std::size_t... S>
2836 RInterface<RLoopManager> CacheImpl(const ColumnNames_t &columnList, std::index_sequence<S...>)
2837 {
2838 const auto columnListWithoutSizeColumns = RDFInternal::FilterArraySizeColNames(columnList, "Snapshot");
2839
2840 // Check at compile time that the columns types are copy constructible
2841 constexpr bool areCopyConstructible =
2842 RDFInternal::TEvalAnd<std::is_copy_constructible<ColTypes>::value...>::value;
2843 static_assert(areCopyConstructible, "Columns of a type which is not copy constructible cannot be cached yet.");
2844
2845 RDFInternal::CheckTypesAndPars(sizeof...(ColTypes), columnListWithoutSizeColumns.size());
2846
2847 auto colHolders = std::make_tuple(Take<ColTypes>(columnListWithoutSizeColumns[S])...);
2848 auto ds = std::make_unique<RLazyDS<ColTypes...>>(
2849 std::make_pair(columnListWithoutSizeColumns[S], std::get<S>(colHolders))...);
2850
2851 RInterface<RLoopManager> cachedRDF(std::make_shared<RLoopManager>(std::move(ds), columnListWithoutSizeColumns));
2852
2853 return cachedRDF;
2854 }
2855
2856 template <bool IsSingleColumn, typename F>
2858 VaryImpl(const std::vector<std::string> &colNames, F &&expression, const ColumnNames_t &inputColumns,
2859 const std::vector<std::string> &variationTags, std::string_view variationName)
2860 {
2861 using F_t = std::decay_t<F>;
2862 using ColTypes_t = typename TTraits::CallableTraits<F_t>::arg_types;
2863 using RetType = typename TTraits::CallableTraits<F_t>::ret_type;
2864 constexpr auto nColumns = ColTypes_t::list_size;
2865
2866 SanityChecksForVary<RetType>(colNames, variationTags, variationName);
2867
2868 const auto validColumnNames = GetValidatedColumnNames(nColumns, inputColumns);
2869 CheckAndFillDSColumns(validColumnNames, ColTypes_t{});
2870
2871 auto retTypeName = RDFInternal::TypeID2TypeName(typeid(RetType));
2872 if (retTypeName.empty()) {
2873 // The type is not known to the interpreter, but we don't want to error out
2874 // here, rather if/when this column is used in jitted code, so we inject a broken but telling type name.
2875 const auto demangledType = RDFInternal::DemangleTypeIdName(typeid(RetType));
2876 retTypeName = "CLING_UNKNOWN_TYPE_" + demangledType;
2877 }
2878
2879 auto variation = std::make_shared<RDFInternal::RVariation<F_t, IsSingleColumn>>(
2880 colNames, variationName, std::forward<F>(expression), variationTags, retTypeName, fColRegister, *fLoopManager,
2881 validColumnNames);
2882
2884 newCols.AddVariation(std::move(variation));
2885
2886 RInterface<Proxied> newInterface(fProxiedPtr, *fLoopManager, std::move(newCols));
2887
2888 return newInterface;
2889 }
2890
2891 RInterface<Proxied, DS_t> JittedVaryImpl(const std::vector<std::string> &colNames, std::string_view expression,
2892 const std::vector<std::string> &variationTags,
2893 std::string_view variationName, bool isSingleColumn)
2894 {
2895 R__ASSERT(variationTags.size() > 0 && "Must have at least one variation.");
2896 R__ASSERT(colNames.size() > 0 && "Must have at least one varied column.");
2897 R__ASSERT(!variationName.empty() && "Must provide a variation name.");
2898
2899 for (auto &colName : colNames) {
2900 RDFInternal::CheckValidCppVarName(colName, "Vary");
2903 }
2904 RDFInternal::CheckValidCppVarName(variationName, "Vary");
2905
2906 // when varying multiple columns, they must be different columns
2907 if (colNames.size() > 1) {
2908 std::set<std::string> uniqueCols(colNames.begin(), colNames.end());
2909 if (uniqueCols.size() != colNames.size())
2910 throw std::logic_error("A column name was passed to the same Vary invocation multiple times.");
2911 }
2912
2913 auto upcastNodeOnHeap = RDFInternal::MakeSharedOnHeap(RDFInternal::UpcastNode(fProxiedPtr));
2914 auto jittedVariation =
2915 RDFInternal::BookVariationJit(colNames, variationName, variationTags, expression, *fLoopManager, fDataSource,
2916 fColRegister, fLoopManager->GetBranchNames(), upcastNodeOnHeap, isSingleColumn);
2917
2919 newColRegister.AddVariation(std::move(jittedVariation));
2920
2921 RInterface<Proxied, DS_t> newInterface(fProxiedPtr, *fLoopManager, std::move(newColRegister));
2922
2923 return newInterface;
2924 }
2925
2926 template <typename Helper, typename ActionResultType>
2927 auto CallCreateActionWithoutColsIfPossible(const std::shared_ptr<ActionResultType> &resPtr,
2928 const std::shared_ptr<Helper> &hPtr,
2930 -> decltype(hPtr->Exec(0u), RResultPtr<ActionResultType>{})
2931 {
2932 return CreateAction<RDFInternal::ActionTags::Book>(/*columns=*/{}, resPtr, hPtr, fProxiedPtr, 0u);
2933 }
2934
2935 template <typename Helper, typename ActionResultType, typename... Others>
2936 RResultPtr<ActionResultType>
2937 CallCreateActionWithoutColsIfPossible(const std::shared_ptr<ActionResultType> &,
2938 const std::shared_ptr<Helper>& /*hPtr*/,
2939 Others...)
2940 {
2941 throw std::logic_error(std::string("An action was booked with no input columns, but the action requires "
2942 "columns! The action helper type was ") +
2943 typeid(Helper).name());
2944 return {};
2945 }
2946
2947protected:
2948 RInterface(const std::shared_ptr<Proxied> &proxied, RLoopManager &lm,
2949 const RDFInternal::RColumnRegister &colRegister)
2950 : RInterfaceBase(lm, colRegister), fProxiedPtr(proxied)
2951 {
2952 }
2953
2954 const std::shared_ptr<Proxied> &GetProxiedPtr() const { return fProxiedPtr; }
2955};
2956
2957} // namespace RDF
2958
2959} // namespace ROOT
2960
2961#endif // ROOT_RDF_INTERFACE
#define f(i)
Definition RSha256.hxx:104
#define h(i)
Definition RSha256.hxx:106
unsigned int UInt_t
Definition RtypesCore.h:46
unsigned long long ULong64_t
Definition RtypesCore.h:81
#define R__ASSERT(e)
Definition TError.h:117
const Int_t kError
Definition TError.cxx:38
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
Base class for action helpers, see RInterface::Book() for more information.
The head node of a RDF computation graph.
const ColumnNames_t & GetBranchNames()
Return all valid TTree::Branch names (caching results for subsequent calls).
void ToJitExec(const std::string &) const
void Run(bool jit=true)
Start the event loop with a different mechanism depending on IMT/no IMT, data source/no data source.
void Jit()
Add RDF nodes that require just-in-time compilation to the computation graph.
Helper class that provides the operation graph nodes.
A RDataFrame node that produces a result.
Definition RAction.hxx:54
A binder for user-defined columns, variations and aliases.
void AddVariation(std::shared_ptr< RVariationBase > variation)
Register a new systematic variation.
void AddDefine(std::shared_ptr< RDFDetail::RDefineBase > column)
Add a new defined column.
ColumnNames_t GetNames() const
Return the list of the names of the defined columns (Defines + Aliases).
virtual const std::vector< std::string > & GetColumnNames() const =0
Returns a reference to the collection of the dataset's column names.
ColumnNames_t GetValidatedColumnNames(const unsigned int nColumns, const ColumnNames_t &columns)
ColumnNames_t GetColumnTypeNamesList(const ColumnNames_t &columnList)
RDFDetail::RLoopManager * fLoopManager
< The RLoopManager at the root of this computation graph. Never null.
RResultPtr< ActionResultType > CreateAction(const ColumnNames_t &columns, const std::shared_ptr< ActionResultType > &r, const std::shared_ptr< HelperArgType > &helperArg, const std::shared_ptr< RDFNode > &proxiedPtr, const int=-1)
Create RAction object, return RResultPtr for the action Overload for the case in which all column typ...
RDataSource * fDataSource
Non-owning pointer to a data-source object. Null if no data-source. RLoopManager has ownership of the...
void CheckAndFillDSColumns(ColumnNames_t validCols, TTraits::TypeList< ColumnTypes... > typeList)
void CheckIMTDisabled(std::string_view callerName)
ColumnNames_t GetColumnNames()
Returns the names of the available columns.
RDFInternal::RColumnRegister fColRegister
Contains the columns defined up to this node.
The public interface to the RDataFrame federation of classes.
RResultPtr<::THnD > HistoND(const THnDModel &model, const ColumnNames_t &columnList)
Fill and return an N-dimensional histogram (lazy action).
RInterface(const RInterface &)=default
Copy-ctor for RInterface.
RResultPtr<::TH1D > Histo1D(std::string_view vName, std::string_view wName)
Fill and return a one-dimensional histogram with the weighted values of a column (lazy action).
RInterface(const std::shared_ptr< Proxied > &proxied, RLoopManager &lm, const RDFInternal::RColumnRegister &colRegister)
RResultPtr<::TH1D > Histo1D(const TH1DModel &model={"", "", 128u, 0., 0.})
Fill and return a one-dimensional histogram with the weighted values of a column (lazy action).
RResultPtr<::TH2D > Histo2D(const TH2DModel &model)
RResultPtr<::TProfile > Profile1D(const TProfile1DModel &model, std::string_view v1Name="", std::string_view v2Name="")
Fill and return a one-dimensional profile (lazy action).
RResultPtr<::THnD > HistoND(const THnDModel &model, const ColumnNames_t &columnList)
Fill and return an N-dimensional histogram (lazy action).
std::enable_if_t<!IsFStringConv &&!IsRetTypeDefConstr, RInterface< Proxied, DS_t > > DefineImpl(std::string_view, F, const ColumnNames_t &, const std::string &)
RResultPtr< RInterface< RLoopManager > > Snapshot(std::string_view treename, std::string_view filename, std::string_view columnNameRegexp="", const RSnapshotOptions &options=RSnapshotOptions())
Save selected columns to disk, in a new TTree treename in file filename.
RResultPtr< TStatistic > Stats(std::string_view value="")
Return a TStatistic object, filled once per event (lazy action).
RInterface< Proxied, DS_t > Vary(std::string_view colName, F &&expression, const ColumnNames_t &inputColumns, std::size_t nVariations, std::string_view variationName="")
Register systematic variations for an existing columns using auto-generated variation tags.
RInterface< Proxied, DS_t > Vary(std::string_view colName, std::string_view expression, std::size_t nVariations, std::string_view variationName="")
Register systematic variations for an existing column.
RResultPtr<::TGraph > Graph(std::string_view x="", std::string_view y="")
Fill and return a TGraph object (lazy action).
RResultPtr< ActionResultType > CallCreateActionWithoutColsIfPossible(const std::shared_ptr< ActionResultType > &, const std::shared_ptr< Helper > &, Others...)
RInterface< Proxied, DS_t > DefineSlot(std::string_view name, F expression, const ColumnNames_t &columns={})
Define a new column with a value dependent on the processing slot.
RResultPtr< double > StdDev(std::string_view columnName="")
Return the unbiased standard deviation of processed column values (lazy action).
std::enable_if_t< std::is_default_constructible< RetType >::value, RInterface< Proxied, DS_t > > DefineImpl(std::string_view name, F &&expression, const ColumnNames_t &columns, const std::string &where)
RInterface< Proxied, DS_t > DefinePerSample(std::string_view name, F expression)
Define a new column that is updated when the input sample changes.
RInterface & operator=(RInterface &&)=default
Move-assignment operator for RInterface.
RInterface< Proxied, DS_t > Vary(const std::vector< std::string > &colNames, F &&expression, const ColumnNames_t &inputColumns, std::size_t nVariations, std::string_view variationName)
Register systematic variations for one or more existing columns using auto-generated tags.
void ForeachSlot(F f, const ColumnNames_t &columns={})
Execute a user-defined function requiring a processing slot index on each entry (instant action).
RInterface< Proxied, DS_t > Vary(std::string_view colName, std::string_view expression, const std::vector< std::string > &variationTags, std::string_view variationName="")
Register systematic variations for an existing column.
RResultPtr< RDisplay > Display(const ColumnNames_t &columnList, size_t nRows=5, size_t nMaxCollectionElements=10)
Provides a representation of the columns in the dataset.
RInterface< RLoopManager > Cache(const ColumnNames_t &columnList)
Save selected columns in memory.
RInterface< Proxied, DS_t > Define(std::string_view name, F expression, const ColumnNames_t &columns={})
Define a new column.
RResultPtr< TStatistic > Stats(std::string_view value, std::string_view weight)
Return a TStatistic object, filled once per event (lazy action).
RInterface< Proxied, DS_t > Redefine(std::string_view name, std::string_view expression)
Overwrite the value and/or type of an existing column.
auto CallCreateActionWithoutColsIfPossible(const std::shared_ptr< ActionResultType > &resPtr, const std::shared_ptr< Helper > &hPtr, TTraits::TypeList< RDFDetail::RInferredType >) -> decltype(hPtr->Exec(0u), RResultPtr< ActionResultType >{})
RInterface< Proxied, DS_t > Vary(const std::vector< std::string > &colNames, std::string_view expression, std::size_t nVariations, std::string_view variationName)
Register systematic variations for one or more existing columns.
RResultPtr<::TH2D > Histo2D(const TH2DModel &model, std::string_view v1Name="", std::string_view v2Name="")
Fill and return a two-dimensional histogram (lazy action).
RResultPtr< RInterface< RLoopManager > > SnapshotImpl(std::string_view fullTreeName, std::string_view filename, const ColumnNames_t &columnList, const RSnapshotOptions &options)
RInterface< Proxied, DS_t > Vary(std::initializer_list< std::string > colNames, F &&expression, const ColumnNames_t &inputColumns, const std::vector< std::string > &variationTags, std::string_view variationName)
Overload to avoid ambiguity between C++20 string, vector<string> construction from init list.
RResultPtr<::TProfile > Profile1D(const TProfile1DModel &model)
Fill and return a one-dimensional profile (lazy action).
RInterface(const std::shared_ptr< RLoopManager > &proxied)
Build a RInterface from a RLoopManager.
RInterface< RDFDetail::RFilter< F, Proxied >, DS_t > Filter(F f, const std::initializer_list< std::string > &columns)
Append a filter to the call graph.
RInterface< Proxied, DS_t > DefinePerSample(std::string_view name, std::string_view expression)
Define a new column that is updated when the input sample changes.
RResultPtr< double > Mean(std::string_view columnName="")
Return the mean of processed column values (lazy action).
RResultPtr< RInterface< RLoopManager > > Snapshot(std::string_view treename, std::string_view filename, std::initializer_list< std::string > columnList, const RSnapshotOptions &options=RSnapshotOptions())
Save selected columns to disk, in a new TTree treename in file filename.
RResultPtr< RDisplay > Display(std::initializer_list< std::string > columnList, size_t nRows=5, size_t nMaxCollectionElements=10)
Provides a representation of the columns in the dataset.
RInterface< Proxied, DS_t > Alias(std::string_view alias, std::string_view columnName)
Allow to refer to a column with a different name.
RInterface< RLoopManager > Cache(const ColumnNames_t &columnList)
Save selected columns in memory.
RInterface< Proxied, DS_t > Redefine(std::string_view name, F expression, const ColumnNames_t &columns={})
Overwrite the value and/or type of an existing column.
RInterface< RLoopManager > Cache(std::string_view columnNameRegexp="")
Save selected columns in memory.
RInterface< Proxied, DS_t > VaryImpl(const std::vector< std::string > &colNames, F &&expression, const ColumnNames_t &inputColumns, const std::vector< std::string > &variationTags, std::string_view variationName)
RResultPtr< typename std::decay_t< Helper >::Result_t > Book(Helper &&helper, const ColumnNames_t &columns={})
Book execution of a custom action using a user-defined helper object.
RResultPtr< RDisplay > Display(std::string_view columnNameRegexp="", size_t nRows=5, size_t nMaxCollectionElements=10)
Provides a representation of the columns in the dataset.
friend class RDFInternal::GraphDrawing::GraphCreatorHelper
RResultPtr<::TH2D > Histo2D(const TH2DModel &model, std::string_view v1Name, std::string_view v2Name, std::string_view wName)
Fill and return a weighted two-dimensional histogram (lazy action).
RInterface & operator=(const RInterface &)=default
Copy-assignment operator for RInterface.
RResultPtr< RDFDetail::SumReturnType_t< T > > Sum(std::string_view columnName="", const RDFDetail::SumReturnType_t< T > &initValue=RDFDetail::SumReturnType_t< T >{})
Return the sum of processed column values (lazy action).
RInterface< Proxied, DS_t > Vary(std::string_view colName, F &&expression, const ColumnNames_t &inputColumns, const std::vector< std::string > &variationTags, std::string_view variationName="")
Register systematic variations for an existing column.
RResultPtr< ULong64_t > Count()
Return the number of entries processed (lazy action).
RInterface< Proxied, DS_t > Vary(const std::vector< std::string > &colNames, std::string_view expression, const std::vector< std::string > &variationTags, std::string_view variationName)
Register systematic variations for one or more existing columns.
RInterface< Proxied, DS_t > Define(std::string_view name, std::string_view expression)
Define a new column.
std::shared_ptr< Proxied > fProxiedPtr
Smart pointer to the graph node encapsulated by this RInterface.
RResultPtr<::TH1D > Histo1D(std::string_view vName)
Fill and return a one-dimensional histogram with the values of a column (lazy action).
RInterface< Proxied, DS_t > Vary(const std::vector< std::string > &colNames, F &&expression, const ColumnNames_t &inputColumns, const std::vector< std::string > &variationTags, std::string_view variationName)
Register a systematic variation that affects multiple columns simultaneously.
RInterface< Proxied, DS_t > RedefineSlotEntry(std::string_view name, F expression, const ColumnNames_t &columns={})
Overwrite the value and/or type of an existing column.
RResultPtr<::TH1D > Histo1D(const TH1DModel &model, std::string_view vName, std::string_view wName)
Fill and return a one-dimensional histogram with the weighted values of a column (lazy action).
RInterface< RLoopManager > CacheImpl(const ColumnNames_t &columnList, std::index_sequence< S... >)
Implementation of cache.
RInterface< RDFDetail::RRange< Proxied >, DS_t > Range(unsigned int end)
Creates a node that filters entries based on range.
RResultPtr< COLL > Take(std::string_view column="")
Return a collection of values of a column (lazy action, returns a std::vector by default).
RInterface< RLoopManager > Cache(std::initializer_list< std::string > columnList)
Save selected columns in memory.
RResultPtr<::TProfile2D > Profile2D(const TProfile2DModel &model, std::string_view v1Name="", std::string_view v2Name="", std::string_view v3Name="")
Fill and return a two-dimensional profile (lazy action).
const std::shared_ptr< Proxied > & GetProxiedPtr() const
RInterface< Proxied, DS_t > JittedVaryImpl(const std::vector< std::string > &colNames, std::string_view expression, const std::vector< std::string > &variationTags, std::string_view variationName, bool isSingleColumn)
RResultPtr<::TH3D > Histo3D(const TH3DModel &model, std::string_view v1Name="", std::string_view v2Name="", std::string_view v3Name="")
Fill and return a three-dimensional histogram (lazy action).
RInterface< Proxied, DS_t > Vary(std::initializer_list< std::string > colNames, F &&expression, const ColumnNames_t &inputColumns, std::size_t nVariations, std::string_view variationName)
Overload to avoid ambiguity between C++20 string, vector<string> construction from init list.
RResultPtr< std::decay_t< T > > Fill(T &&model, const ColumnNames_t &columnList)
Return an object of type T on which T::Fill will be called once per event (lazy action).
RResultPtr< RInterface< RLoopManager > > Snapshot(std::string_view treename, std::string_view filename, const ColumnNames_t &columnList, const RSnapshotOptions &options=RSnapshotOptions())
Save selected columns to disk, in a new TTree treename in file filename.
RResultPtr< RDisplay > Display(const ColumnNames_t &columnList, size_t nRows=5, size_t nMaxCollectionElements=10)
Provides a representation of the columns in the dataset.
RResultPtr< RCutFlowReport > Report()
Gather filtering statistics.
RInterface< Proxied, DS_t > RedefineSlot(std::string_view name, F expression, const ColumnNames_t &columns={})
Overwrite the value and/or type of an existing column.
RResultPtr<::TProfile2D > Profile2D(const TProfile2DModel &model, std::string_view v1Name, std::string_view v2Name, std::string_view v3Name, std::string_view wName)
Fill and return a two-dimensional profile (lazy action).
RResultPtr<::TGraphAsymmErrors > GraphAsymmErrors(std::string_view x="", std::string_view y="", std::string_view exl="", std::string_view exh="", std::string_view eyl="", std::string_view eyh="")
Fill and return a TGraphAsymmErrors object (lazy action).
RResultPtr< RInterface< RLoopManager > > Snapshot(std::string_view treename, std::string_view filename, const ColumnNames_t &columnList, const RSnapshotOptions &options=RSnapshotOptions())
Save selected columns to disk, in a new TTree treename in file filename.
RResultPtr< U > Aggregate(AccFun aggregator, MergeFun merger, std::string_view columnName="")
Execute a user-defined accumulation operation on the processed column values in each processing slot.
RInterface< Proxied, DS_t > DefineSlotEntry(std::string_view name, F expression, const ColumnNames_t &columns={})
Define a new column with a value dependent on the processing slot and the current entry.
RResultPtr< RDFDetail::MinReturnType_t< T > > Min(std::string_view columnName="")
Return the minimum of processed column values (lazy action).
RResultPtr< T > Reduce(F f, std::string_view columnName="")
Execute a user-defined reduce operation on the values of a column.
void Foreach(F f, const ColumnNames_t &columns={})
Execute a user-defined function on each entry (instant action).
RInterface< RDFDetail::RJittedFilter, DS_t > Filter(std::string_view expression, std::string_view name="")
Append a filter to the call graph.
RResultPtr<::TProfile2D > Profile2D(const TProfile2DModel &model)
Fill and return a two-dimensional profile (lazy action).
RInterface< RDFDetail::RFilter< F, Proxied >, DS_t > Filter(F f, const ColumnNames_t &columns={}, std::string_view name="")
Append a filter to the call graph.
RResultPtr< U > Aggregate(AccFun aggregator, MergeFun merger, std::string_view columnName, const U &aggIdentity)
Execute a user-defined accumulation operation on the processed column values in each processing slot.
RInterface(RInterface &&)=default
Move-ctor for RInterface.
RResultPtr< T > Reduce(F f, std::string_view columnName, const T &redIdentity)
Execute a user-defined reduce operation on the values of a column.
RResultPtr<::TH3D > Histo3D(const TH3DModel &model, std::string_view v1Name, std::string_view v2Name, std::string_view v3Name, std::string_view wName)
Fill and return a three-dimensional histogram (lazy action).
RInterface< RDFDetail::RFilter< F, Proxied >, DS_t > Filter(F f, std::string_view name)
Append a filter to the call graph.
RInterface< RDFDetail::RRange< Proxied >, DS_t > Range(unsigned int begin, unsigned int end, unsigned int stride=1)
Creates a node that filters entries based on range: [begin, end).
std::vector< std::string > GetFilterNames()
Returns the names of the filters created.
RResultPtr<::TH1D > Histo1D(const TH1DModel &model={"", "", 128u, 0., 0.}, std::string_view vName="")
Fill and return a one-dimensional histogram with the values of a column (lazy action).
RResultPtr<::TProfile > Profile1D(const TProfile1DModel &model, std::string_view v1Name, std::string_view v2Name, std::string_view wName)
Fill and return a one-dimensional profile (lazy action).
RResultPtr<::TH3D > Histo3D(const TH3DModel &model)
RResultPtr< RDFDetail::MaxReturnType_t< T > > Max(std::string_view columnName="")
Return the maximum of processed column values (lazy action).
RInterface< Proxied, DS_t > Vary(std::initializer_list< std::string > colNames, std::string_view expression, std::size_t nVariations, std::string_view variationName)
Overload to avoid ambiguity between C++20 string, vector<string> construction from init list.
A RDataSource implementation which is built on top of result proxies.
Smart pointer for the return type of actions.
ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree ,...
typename RemoveFirstParameter< T >::type RemoveFirstParameter_t
TDirectory::TContext keeps track and restore the current directory.
Definition TDirectory.h:89
A TGraph is an object made of two arrays X and Y with npoints each.
Definition TGraph.h:41
Statistical variable, defined by its mean and variance (RMS).
Definition TStatistic.h:33
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
#define F(x, y, z)
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)
void CheckForRedefinition(const std::string &where, std::string_view definedColView, const RColumnRegister &colRegister, const ColumnNames_t &treeColumns, const ColumnNames_t &dataSourceColumns)
Throw if column definedColView is already there.
void CheckForDefinition(const std::string &where, std::string_view definedColView, const RColumnRegister &colRegister, const ColumnNames_t &treeColumns, const ColumnNames_t &dataSourceColumns)
Throw if column definedColView is not already there.
std::shared_ptr< RJittedDefine > BookDefineJit(std::string_view name, std::string_view expression, RLoopManager &lm, RDataSource *ds, const RColumnRegister &colRegister, const ColumnNames_t &branches, 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)
std::shared_ptr< RNodeBase > UpcastNode(std::shared_ptr< RNodeBase > ptr)
std::string TypeID2TypeName(const std::type_info &id)
Returns the name of a type starting from its type_info An empty string is returned in case of failure...
Definition RDFUtils.cxx:99
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::shared_ptr< RDFDetail::RJittedFilter > BookFilterJit(std::shared_ptr< RDFDetail::RNodeBase > *prevNodeOnHeap, std::string_view name, std::string_view expression, const ColumnNames_t &branches, const RColumnRegister &colRegister, TTree *tree, RDataSource *ds)
Book the jitting of a Filter call.
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::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, const ColumnNames_t &branches, 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)
std::pair< std::vector< std::string >, std::vector< std::string > > AddSizeBranches(const std::vector< std::string > &branches, TTree *tree, std::vector< std::string > &&colsWithoutAliases, std::vector< std::string > &&colsWithAliases)
Return copies of colsWithoutAliases and colsWithAliases with size branches for variable-sized array b...
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 TriggerRun(ROOT::RDF::RNode &node)
Trigger the execution of an RDataFrame computation graph.
std::vector< std::string > GetTopLevelBranchNames(TTree &t)
Get all the top-level branches names, including the ones of the friend trees.
RInterface<::ROOT::Detail::RDF::RNodeBase, void > RNode
std::vector< std::string > ColumnNames_t
ROOT type_traits extensions.
This file contains a specialised ROOT message handler to test for diagnostic in unit tests.
void EnableImplicitMT(UInt_t numthreads=0)
Enable ROOT's implicit multi-threading for all objects and methods that provide an internal paralleli...
Definition TROOT.cxx:527
Bool_t IsImplicitMTEnabled()
Returns true if the implicit multi-threading in ROOT is enabled.
Definition TROOT.cxx:558
void DisableImplicitMT()
Disables the implicit multi-threading in ROOT (see EnableImplicitMT).
Definition TROOT.cxx:544
Definition graph.py:1
Definition tree.py:1
type is TypeList if MustRemove is false, otherwise it is a TypeList with the first type removed
Definition Utils.hxx:139
A collection of options to steer the creation of the dataset on file.
bool fLazy
Do not start the event loop when Snapshot is called.
A struct which stores the parameters of a TH1D.
std::shared_ptr<::TH1D > GetHistogram() const
A struct which stores the parameters of a TH2D.
std::shared_ptr<::TH2D > GetHistogram() const
A struct which stores the parameters of a TH3D.
std::shared_ptr<::TH3D > GetHistogram() const
A struct which stores the parameters of a THnD.
std::shared_ptr<::THnD > GetHistogram() const
A struct which stores the parameters of a TProfile.
std::shared_ptr<::TProfile > GetProfile() const
A struct which stores the parameters of a TProfile2D.
std::shared_ptr<::TProfile2D > GetProfile() const
Lightweight storage for a collection of types.