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