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