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