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