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