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