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