Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
df001_introduction.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_dataframe
3/// \notebook -nodraw
4/// Basic RDataFrame usage.
5///
6/// This tutorial illustrates the basic features of the RDataFrame class,
7/// a utility which allows to interact with data stored in TTrees following
8/// a functional-chain like approach.
9///
10/// \macro_code
11/// \macro_output
12///
13/// \date December 2016
14/// \author Enrico Guiraud (CERN)
15
16// ## Preparation
17
18// A simple helper function to fill a test tree: this makes the example
19// stand-alone.
20void fill_tree(const char *treeName, const char *fileName)
21{
23 d.Define("b1", [](ULong64_t entry) -> double { return entry; }, {"rdfentry_"})
24 .Define("b2", [](ULong64_t entry) -> int { return entry * entry; }, {"rdfentry_"})
25 .Snapshot(treeName, fileName);
26}
27
29{
30
31 // We prepare an input tree to run on
32 auto fileName = "df001_introduction.root";
33 auto treeName = "myTree";
34 fill_tree(treeName, fileName);
35
36 // We read the tree from the file and create a RDataFrame, a class that
37 // allows us to interact with the data contained in the tree.
38 // We select a default column, a *branch* to adopt ROOT jargon, which will
39 // be looked at if none is specified by the user when dealing with filters
40 // and actions.
41 ROOT::RDataFrame d(treeName, fileName, {"b1"});
42
43 // ## Operations on the dataframe
44 // We now review some *actions* which can be performed on the data frame.
45 // Actions can be divided into instant actions (e. g. Foreach()) and lazy
46 // actions (e. g. Count()), depending on whether they trigger the event
47 // loop immediately or only when one of the results is accessed for the
48 // first time. Actions that return "something" either return their result
49 // wrapped in a RResultPtr or in a RDataFrame.
50 // But first of all, let us define our cut-flow with two lambda
51 // functions. We can use free functions too.
52 auto cutb1 = [](double b1) { return b1 < 5.; };
53 auto cutb1b2 = [](int b2, double b1) { return b2 % 2 && b1 < 4.; };
54
55 // ### `Count` action
56 // The `Count` allows to retrieve the number of the entries that passed the
57 // filters. Here, we show how the automatic selection of the column kicks
58 // in in case the user specifies none.
59 auto entries1 = d.Filter(cutb1) // <- no column name specified here!
60 .Filter(cutb1b2, {"b2", "b1"})
61 .Count();
62
63 std::cout << *entries1 << " entries passed all filters" << std::endl;
64
65 // Filters can be expressed as strings. The content must be C++ code. The
66 // name of the variables must be the name of the branches. The code is
67 // just-in-time compiled.
68 auto entries2 = d.Filter("b1 < 5.").Count();
69 std::cout << *entries2 << " entries passed the string filter" << std::endl;
70
71 // ### `Min`, `Max` and `Mean` actions
72 // These actions allow to retrieve statistical information about the entries
73 // passing the cuts, if any.
74 auto b1b2_cut = d.Filter(cutb1b2, {"b2", "b1"});
75 auto minVal = b1b2_cut.Min();
76 auto maxVal = b1b2_cut.Max();
77 auto meanVal = b1b2_cut.Mean();
78 auto nonDefmeanVal = b1b2_cut.Mean("b2"); // <- Column is not the default
79 std::cout << "The mean is always included between the min and the max: " << *minVal << " <= " << *meanVal
80 << " <= " << *maxVal << std::endl;
81
82 // ### `Take` action
83 // The `Take` action allows to retrieve all values of the variable stored in a
84 // particular column that passed filters we specified. The values are stored
85 // in a vector by default, but other collections can be chosen.
86 auto b1_cut = d.Filter(cutb1);
87 auto b1Vec = b1_cut.Take<double>();
88 auto b1List = b1_cut.Take<double, std::list<double>>();
89
90 std::cout << "Selected b1 entries" << std::endl;
91 for (auto b1_entry : *b1List)
92 std::cout << b1_entry << " ";
93 std::cout << std::endl;
94 auto b1VecCl = ROOT::GetClass(b1Vec.GetPtr());
95 std::cout << "The type of b1Vec is " << b1VecCl->GetName() << std::endl;
96
97 // ### `Histo1D` action
98 // The `Histo1D` action allows to fill an histogram. It returns a TH1D filled
99 // with values of the column that passed the filters. For the most common
100 // types, the type of the values stored in the column is automatically
101 // guessed.
102 auto hist = d.Filter(cutb1).Histo1D();
103 std::cout << "Filled h " << hist->GetEntries() << " times, mean: " << hist->GetMean() << std::endl;
104
105 // ### `Foreach` action
106 // The most generic action of all: an operation is applied to all entries.
107 // In this case we fill a histogram. In some sense this is a violation of a
108 // purely functional paradigm - C++ allows to do that.
109 TH1F h("h", "h", 12, -1, 11);
110 d.Filter([](int b2) { return b2 % 2 == 0; }, {"b2"}).Foreach([&h](double b1) { h.Fill(b1); });
111
112 std::cout << "Filled h with " << h.GetEntries() << " entries" << std::endl;
113
114 // ## Express your chain of operations with clarity!
115 // We are discussing an example here but it is not hard to imagine much more
116 // complex pipelines of actions acting on data. Those might require code
117 // which is well organised, for example allowing to conditionally add filters
118 // or again to clearly separate filters and actions without the need of
119 // writing the entire pipeline on one line. This can be easily achieved.
120 // We'll show this by re-working the `Count` example:
121 auto cutb1_result = d.Filter(cutb1);
122 auto cutb1b2_result = d.Filter(cutb1b2, {"b2", "b1"});
123 auto cutb1_cutb1b2_result = cutb1_result.Filter(cutb1b2, {"b2", "b1"});
124 // Now we want to count:
125 auto evts_cutb1_result = cutb1_result.Count();
126 auto evts_cutb1b2_result = cutb1b2_result.Count();
127 auto evts_cutb1_cutb1b2_result = cutb1_cutb1b2_result.Count();
128
129 std::cout << "Events passing cutb1: " << *evts_cutb1_result << std::endl
130 << "Events passing cutb1b2: " << *evts_cutb1b2_result << std::endl
131 << "Events passing both: " << *evts_cutb1_cutb1b2_result << std::endl;
132
133 // ## Calculating quantities starting from existing columns
134 // Often, operations need to be carried out on quantities calculated starting
135 // from the ones present in the columns. We'll create in this example a third
136 // column, the values of which are the sum of the *b1* and *b2* ones, entry by
137 // entry. The way in which the new quantity is defined is via a callable.
138 // It is important to note two aspects at this point:
139 // - The value is created on the fly only if the entry passed the existing
140 // filters.
141 // - The newly created column behaves as the one present on the file on disk.
142 // - The operation creates a new value, without modifying anything. De facto,
143 // this is like having a general container at disposal able to accommodate
144 // any value of any type.
145 // Let's dive in an example:
146 auto entries_sum = d.Define("sum", [](double b1, int b2) { return b2 + b1; }, {"b1", "b2"})
147 .Filter([](double sum) { return sum > 4.2; }, {"sum"})
148 .Count();
149 std::cout << *entries_sum << std::endl;
150
151 // Additional columns can be expressed as strings. The content must be C++
152 // code. The name of the variables must be the name of the branches. The code
153 // is just-in-time compiled.
154 auto entries_sum2 = d.Define("sum2", "b1 + b2").Filter("sum2 > 4.2").Count();
155 std::cout << *entries_sum2 << std::endl;
156
157 // It is possible at any moment to read the entry number and the processing
158 // slot number. The latter may change when implicit multithreading is active.
159 // The special columns which provide the entry number and the slot index are
160 // called "rdfentry_" and "rdfslot_" respectively. Their types are an unsigned
161 // 64 bit integer and an unsigned integer.
162 auto printEntrySlot = [](ULong64_t iEntry, unsigned int slot) {
163 std::cout << "Entry: " << iEntry << " Slot: " << slot << std::endl;
164 };
165 d.Foreach(printEntrySlot, {"rdfentry_", "rdfslot_"});
166
167 return 0;
168}
#define d(i)
Definition RSha256.hxx:102
#define h(i)
Definition RSha256.hxx:106
unsigned long long ULong64_t
Definition RtypesCore.h:81
ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree ,...
1-D histogram with a float per channel (see TH1 documentation)
Definition TH1.h:621
RVec< T > Filter(const RVec< T > &v, F &&f)
Create a new collection with the elements passing the filter expressed by the predicate.
Definition RVec.hxx:2182
TClass * GetClass(T *)
Definition TClass.h:663
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2345