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