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