Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RDataFrame.cxx
Go to the documentation of this file.
1// Author: Enrico Guiraud, Danilo Piparo CERN 12/2016
2
3/*************************************************************************
4 * Copyright (C) 1995-2018, 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#include "ROOT/RDataFrame.hxx"
12#include "ROOT/RDataSource.hxx"
16#include "ROOT/RDF/Utils.hxx"
17#include "ROOT/RStringView.hxx"
18#include "TChain.h"
19#include "TDirectory.h"
20#include "RtypesCore.h" // for ULong64_t
21#include "TTree.h"
22
23#include <fstream> // std::ifstream
24#include <nlohmann/json.hpp> // nlohmann::json::parse
25#include <memory> // for make_shared, allocator, shared_ptr
26#include <ostream> // ostringstream
27#include <stdexcept>
28#include <string>
29#include <vector>
30
31// clang-format off
32/**
33* \class ROOT::RDataFrame
34* \ingroup dataframe
35* \brief ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree , CSV and other data formats, in C++ or Python.
36
37In addition, multi-threading and other low-level optimisations allow users to exploit all the resources available
38on their machines completely transparently.<br>
39Skip to the [class reference](#reference) or keep reading for the user guide.
40
41In a nutshell:
42~~~{.cpp}
43ROOT::EnableImplicitMT(); // Tell ROOT you want to go parallel
44ROOT::RDataFrame d("myTree", "file_*.root"); // Interface to TTree and TChain
45auto myHisto = d.Histo1D("Branch_A"); // This books the (lazy) filling of a histogram
46myHisto->Draw(); // Event loop is run here, upon first access to a result
47~~~
48
49Calculations are expressed in terms of a type-safe *functional chain of actions and transformations*, RDataFrame takes
50care of their execution. The implementation automatically puts in place several low level optimisations such as
51multi-thread parallelization and caching.
52
53\htmlonly
54<a href="https://doi.org/10.5281/zenodo.260230"><img src="https://zenodo.org/badge/DOI/10.5281/zenodo.260230.svg"
55alt="DOI"></a>
56\endhtmlonly
57
58## For the impatient user
59You can directly see RDataFrame in action in our [tutorials](https://root.cern.ch/doc/master/group__tutorial__dataframe.html), in C++ or Python.
60
61## Table of Contents
62- [Cheat sheet](\ref cheatsheet)
63- [Introduction](\ref introduction)
64- [Crash course](\ref crash-course)
65- [Working with collections](\ref collections)
66- [Transformations: manipulating data](\ref transformations)
67- [Actions: getting results](\ref actions)
68- [Distributed execution in Python](\ref distrdf)
69- [Performance tips and parallel execution](\ref parallel-execution)
70- [More features](\ref more-features)
71 - [Systematic variations](\ref systematics)
72 - [RDataFrame objects as function arguments and return values](\ref rnode)
73 - [Storing RDataFrame objects in collections](\ref RDFCollections)
74 - [Executing callbacks every N events](\ref callbacks)
75 - [Default column lists](\ref default-branches)
76 - [Special helper columns: `rdfentry_` and `rdfslot_`](\ref helper-cols)
77 - [Just-in-time compilation: column type inference and explicit declaration of column types](\ref jitting)
78 - [User-defined custom actions](\ref generic-actions)
79 - [Friend trees](\ref friends)
80 - [Reading data formats other than ROOT trees](\ref other-file-formats)
81 - [Computation graphs (storing and reusing sets of transformations)](\ref callgraphs)
82 - [Visualizing the computation graph](\ref representgraph)
83 - [Activating RDataFrame execution logs](\ref rdf-logging)
84- [Efficient analysis in Python](\ref python)
85- <a class="el" href="classROOT_1_1RDataFrame.html#reference" onclick="javascript:toggleInherit('pub_methods_classROOT_1_1RDF_1_1RInterface')">Class reference</a>
86
87\anchor cheatsheet
88## Cheat sheet
89These are the operations which can be performed with RDataFrame.
90
91### Transformations
92Transformations are a way to manipulate the data.
93
94| **Transformation** | **Description** |
95|------------------|--------------------|
96| Alias() | Introduce an alias for a particular column name. |
97| Define() | Create a new column in the dataset. Example usages include adding a column that contains the invariant mass of a particle, or a selection of elements of an array (e.g. only the `pt`s of "good" muons). |
98| DefinePerSample() | Define a new column that is updated when the input sample changes, e.g. when switching tree being processed in a chain. |
99| DefineSlot() | Same as Define(), but the user-defined function must take an extra `unsigned int slot` as its first parameter. `slot` will take a different value, `0` to `nThreads - 1`, for each thread of execution. This is meant as a helper in writing thread-safe Define() transformation when using RDataFrame after ROOT::EnableImplicitMT(). DefineSlot() works just as well with single-thread execution: in that case `slot` will always be `0`. |
100| DefineSlotEntry() | Same as DefineSlot(), but the entry number is passed in addition to the slot number. This is meant as a helper in case the expression depends on the entry number. For details about entry numbers in multi-threaded runs, see [here](\ref helper-cols). |
101| Filter() | Filter rows based on user-defined conditions. |
102| Range() | Filter rows based on entry number (single-thread only). |
103| Redefine() | Overwrite the value and/or type of an existing column. See Define() for more information. |
104| RedefineSlot() | Overwrite the value and/or type of an existing column. See DefineSlot() for more information. |
105| RedefineSlotEntry() | Overwrite the value and/or type of an existing column. See DefineSlotEntry() for more information. |
106| Vary() | Register systematic variations for an existing column. Varied results are then extracted via VariationsFor(). |
107
108
109### Actions
110Actions aggregate data into a result. Each one is described in more detail in the reference guide.
111
112In the following, whenever we say an action "returns" something, we always mean it returns a smart pointer to it. Actions only act on events that pass all preceding filters.
113
114Lazy actions only trigger the event loop when one of the results is accessed for the first time, making it easy to
115produce many different results in one event loop. Instant actions trigger the event loop instantly.
116
117
118| **Lazy action** | **Description** |
119|------------------|-----------------|
120| Aggregate() | Execute a user-defined accumulation operation on the processed column values. |
121| Book() | Book execution of a custom action using a user-defined helper object. |
122| Cache() | Cache column values in memory. Custom columns can be cached as well, filtered entries are not cached. Users can specify which columns to save (default is all). |
123| Count() | Return the number of events processed. Useful e.g. to get a quick count of the number of events passing a Filter. |
124| Display() | Provides a printable representation of the dataset contents. The method returns a ROOT::RDF::RDisplay() instance which can print a tabular representation of the data or return it as a string. |
125| Fill() | Fill a user-defined object with the values of the specified columns, as if by calling `Obj.Fill(col1, col2, ...)`. |
126| Graph() | Fills a TGraph with the two columns provided. If multi-threading is enabled, the order of the points may not be the one expected, it is therefore suggested to sort if before drawing. |
127| GraphAsymmErrors() | Fills a TGraphAsymmErrors. If multi-threading is enabled, the order of the points may not be the one expected, it is therefore suggested to sort if before drawing. |
128| Histo1D(), Histo2D(), Histo3D() | Fill a one-, two-, three-dimensional histogram with the processed column values. |
129| HistoND() | Fill an N-dimensional histogram with the processed column values. |
130| Max() | Return the maximum of processed column values. If the type of the column is inferred, the return type is `double`, the type of the column otherwise.|
131| Mean() | Return the mean of processed column values.|
132| Min() | Return the minimum of processed column values. If the type of the column is inferred, the return type is `double`, the type of the column otherwise.|
133| Profile1D(), Profile2D() | Fill a one- or two-dimensional profile with the column values that passed all filters. |
134| Reduce() | Reduce (e.g. sum, merge) entries using the function (lambda, functor...) passed as argument. The function must have signature `T(T,T)` where `T` is the type of the column. Return the final result of the reduction operation. An optional parameter allows initialization of the result object to non-default values. |
135| Report() | Obtain statistics on how many entries have been accepted and rejected by the filters. See the section on [named filters](#named-filters-and-cutflow-reports) for a more detailed explanation. The method returns a ROOT::RDF::RCutFlowReport instance which can be queried programmatically to get information about the effects of the individual cuts. |
136| Stats() | Return a TStatistic object filled with the input columns. |
137| StdDev() | Return the unbiased standard deviation of the processed column values. |
138| Sum() | Return the sum of the values in the column. If the type of the column is inferred, the return type is `double`, the type of the column otherwise. |
139| Take() | Extract a column from the dataset as a collection of values, e.g. a `std::vector<float>` for a column of type `float`. |
140
141| **Instant action** | **Description** |
142|---------------------|-----------------|
143| Foreach() | Execute a user-defined function on each entry. Users are responsible for the thread-safety of this callable when executing with implicit multi-threading enabled. |
144| ForeachSlot() | Same as Foreach(), but the user-defined function must take an extra `unsigned int slot` as its first parameter. `slot` will take a different value, `0` to `nThreads - 1`, for each thread of execution. This is meant as a helper in writing thread-safe Foreach() actions when using RDataFrame after ROOT::EnableImplicitMT(). ForeachSlot() works just as well with single-thread execution: in that case `slot` will always be `0`. |
145| Snapshot() | Write the processed dataset to disk, in a new TTree and TFile. Custom columns can be saved as well, filtered entries are not saved. Users can specify which columns to save (default is all). Snapshot, by default, overwrites the output file if it already exists. Snapshot() can be made *lazy* setting the appropriate flag in the snapshot options.|
146
147
148### Queries
149
150These operations do not modify the dataframe or book computations but simply return information on the RDataFrame object.
151
152| **Operation** | **Description** |
153|---------------------|-----------------|
154| Describe() | Get useful information describing the dataframe, e.g. columns and their types. |
155| GetColumnNames() | Get the names of all the available columns of the dataset. |
156| GetColumnType() | Return the type of a given column as a string. |
157| GetColumnTypeNamesList() | Return the list of type names of columns in the dataset. |
158| GetDefinedColumnNames() | Get the names of all the defined columns. |
159| GetFilterNames() | Return the names of all filters in the computation graph. |
160| GetNRuns() | Return the number of event loops run by this RDataFrame instance so far. |
161| GetNSlots() | Return the number of processing slots that RDataFrame will use during the event loop (i.e. the concurrency level). |
162| SaveGraph() | Store the computation graph of an RDataFrame in [DOT format (graphviz)](https://en.wikipedia.org/wiki/DOT_(graph_description_language)) for easy inspection. See the [relevant section](\ref representgraph) for details. |
163
164\anchor introduction
165## Introduction
166Users define their analysis as a sequence of operations to be performed on the dataframe object; the framework
167takes care of the management of the loop over entries as well as low-level details such as I/O and parallelization.
168RDataFrame provides methods to perform most common operations required by ROOT analyses;
169at the same time, users can just as easily specify custom code that will be executed in the event loop.
170
171RDataFrame is built with a *modular* and *flexible* workflow in mind, summarised as follows:
172
1731. Construct a dataframe object by specifying a dataset. RDataFrame supports TTree as well as TChain, [CSV files](https://root.cern/doc/master/df014__CSVDataSource_8C.html), [SQLite files](https://root.cern/doc/master/df027__SQliteDependencyOverVersion_8C.html), [RNTuples](https://root.cern/doc/master/structROOT_1_1Experimental_1_1RNTuple.html), and it can be extended to custom data formats. From Python, [NumPy arrays can be imported into RDataFrame](https://root.cern/doc/master/df032__MakeNumpyDataFrame_8py.html) as well.
174
1752. Transform the dataframe by:
176
177 - [Applying filters](https://root.cern/doc/master/classROOT_1_1RDataFrame.html#transformations). This selects only specific rows of the dataset.
178
179 - [Creating custom columns](https://root.cern/doc/master/classROOT_1_1RDataFrame.html#transformations). Custom columns can, for example, contain the results of a computation that must be performed for every row of the dataset.
180
1813. [Produce results](https://root.cern/doc/master/classROOT_1_1RDataFrame.html#actions). *Actions* are used to aggregate data into results. Most actions are *lazy*, i.e. they are not executed on the spot, but registered with RDataFrame and executed only when a result is accessed for the first time.
182
183Make sure to book all transformations and actions before you access the contents of any of the results. This lets RDataFrame accumulate work and then produce all results at the same time, upon first access to any of them.
184
185The following table shows how analyses based on TTreeReader and TTree::Draw() translate to RDataFrame. Follow the
186[crash course](#crash-course) to discover more idiomatic and flexible ways to express analyses with RDataFrame.
187<table>
188<tr>
189 <td>
190 <b>TTreeReader</b>
191 </td>
192 <td>
193 <b>ROOT::RDataFrame</b>
194 </td>
195</tr>
196<tr>
197 <td>
198~~~{.cpp}
199TTreeReader reader("myTree", file);
200TTreeReaderValue<A_t> a(reader, "A");
201TTreeReaderValue<B_t> b(reader, "B");
202TTreeReaderValue<C_t> c(reader, "C");
203while(reader.Next()) {
204 if(IsGoodEvent(*a, *b, *c))
205 DoStuff(*a, *b, *c);
206}
207~~~
208 </td>
209 <td>
210~~~{.cpp}
211ROOT::RDataFrame d("myTree", file, {"A", "B", "C"});
212d.Filter(IsGoodEvent).Foreach(DoStuff);
213~~~
214 </td>
215</tr>
216<tr>
217 <td>
218 <b>TTree::Draw</b>
219 </td>
220 <td>
221 <b>ROOT::RDataFrame</b>
222 </td>
223</tr>
224<tr>
225 <td>
226~~~{.cpp}
227auto *tree = file->Get<TTree>("myTree");
228tree->Draw("x", "y > 2");
229~~~
230 </td>
231 <td>
232~~~{.cpp}
233ROOT::RDataFrame df("myTree", file);
234auto h = df.Filter("y > 2").Histo1D("x");
235h->Draw()
236~~~
237 </td>
238</tr>
239<tr>
240 <td>
241~~~{.cpp}
242tree->Draw("jet_eta", "weight*(event == 1)");
243~~~
244 </td>
245 <td>
246~~~{.cpp}
247df.Filter("event == 1").Histo1D("jet_eta", "weight");
248// or the fully compiled version:
249df.Filter([] (ULong64_t e) { return e == 1; }, {"event"}).Histo1D<RVec<float>>("jet_eta", "weight");
250~~~
251 </td>
252</tr>
253<tr>
254 <td>
255~~~{cpp}
256// object selection: for each event, fill histogram with array of selected pts
257tree->Draw('Muon_pt', 'Muon_pt > 100')
258~~~
259 </td>
260 <td>
261~~~{cpp}
262// with RDF, arrays are read as ROOT::VecOps::RVec objects
263df.Define("good_pt", "Muon_pt[Muon_pt > 100]").Histo1D("good_pt")
264~~~
265 </td>
266</tr>
267</table>
268
269\anchor crash-course
270## Crash course
271All snippets of code presented in the crash course can be executed in the ROOT interpreter. Simply precede them with
272~~~{.cpp}
273using namespace ROOT; // RDataFrame's namespace
274~~~
275which is omitted for brevity. The terms "column" and "branch" are used interchangeably.
276
277### Creating an RDataFrame
278RDataFrame's constructor is where the user specifies the dataset and, optionally, a default set of columns that
279operations should work with. Here are the most common methods to construct an RDataFrame object:
280~~~{.cpp}
281// single file -- all constructors are equivalent
282TFile *f = TFile::Open("file.root");
283TTree *t = f.Get<TTree>("treeName");
284
285RDataFrame d1("treeName", "file.root");
286RDataFrame d2("treeName", f); // same as TTreeReader
287RDataFrame d3(*t);
288
289// multiple files -- all constructors are equivalent
290TChain chain("myTree");
291chain.Add("file1.root");
292chain.Add("file2.root");
293
294RDataFrame d4("myTree", {"file1.root", "file2.root"});
295std::vector<std::string> files = {"file1.root", "file2.root"};
296RDataFrame d5("myTree", files);
297RDataFrame d6("myTree", "file*.root"); // the glob is passed as-is to TChain's constructor
298RDataFrame d7(chain);
299~~~
300Additionally, users can construct an RDataFrame with no data source by passing an integer number. This is the number of rows that
301will be generated by this RDataFrame.
302~~~{.cpp}
303RDataFrame d(10); // a RDF with 10 entries (and no columns/branches, for now)
304d.Foreach([] { static int i = 0; std::cout << i++ << std::endl; }); // silly example usage: count to ten
305~~~
306This is useful to generate simple datasets on the fly: the contents of each event can be specified with Define() (explained below). For example, we have used this method to generate [Pythia](https://pythia.org/) events and write them to disk in parallel (with the Snapshot action).
307
308For data sources other than TTrees and TChains, RDataFrame objects are constructed using ad-hoc factory functions (see e.g. FromCSV(), FromSqlite(), FromArrow()):
309
310~~~{.cpp}
311auto df = ROOT::RDF::MakeCsvDataFrame("input.csv");
312// use df as usual
313~~~
314
315### Filling a histogram
316Let's now tackle a very common task, filling a histogram:
317~~~{.cpp}
318// Fill a TH1D with the "MET" branch
319RDataFrame d("myTree", "file.root");
320auto h = d.Histo1D("MET");
321h->Draw();
322~~~
323The first line creates an RDataFrame associated to the TTree "myTree". This tree has a branch named "MET".
324
325Histo1D() is an *action*; it returns a smart pointer (a ROOT::RDF::RResultPtr, to be precise) to a TH1D histogram filled
326with the `MET` of all events. If the quantity stored in the column is a collection (e.g. a vector or an array), the
327histogram is filled with all vector elements for each event.
328
329You can use the objects returned by actions as if they were pointers to the desired results. There are many other
330possible [actions](\ref cheatsheet), and all their results are wrapped in smart pointers; we'll see why in a minute.
331
332### Applying a filter
333Let's say we want to cut over the value of branch "MET" and count how many events pass this cut. This is one way to do it:
334~~~{.cpp}
335RDataFrame d("myTree", "file.root");
336auto c = d.Filter("MET > 4.").Count(); // computations booked, not run
337std::cout << *c << std::endl; // computations run here, upon first access to the result
338~~~
339The filter string (which must contain a valid C++ expression) is applied to the specified columns for each event;
340the name and types of the columns are inferred automatically. The string expression is required to return a `bool`
341which signals whether the event passes the filter (`true`) or not (`false`).
342
343You can think of your data as "flowing" through the chain of calls, being transformed, filtered and finally used to
344perform actions. Multiple Filter() calls can be chained one after another.
345
346Using string filters is nice for simple things, but they are limited to specifying the equivalent of a single return
347statement or the body of a lambda, so it's cumbersome to use strings with more complex filters. They also add a small
348runtime overhead, as ROOT needs to just-in-time compile the string into C++ code. When more freedom is required or
349runtime performance is very important, a C++ callable can be specified instead (a lambda in the following snippet,
350but it can be any kind of function or even a functor class), together with a list of column names.
351This snippet is analogous to the one above:
352~~~{.cpp}
353RDataFrame d("myTree", "file.root");
354auto metCut = [](double x) { return x > 4.; }; // a C++11 lambda function checking "x > 4"
355auto c = d.Filter(metCut, {"MET"}).Count();
356std::cout << *c << std::endl;
357~~~
358
359An example of a more complex filter expressed as a string containing C++ code is shown below
360
361~~~{.cpp}
362RDataFrame d("myTree", "file.root");
363auto df = d.Define("p", "std::array<double, 4> p{px, py, pz}; return p;")
364 .Filter("double p2 = 0.0; for (auto&& x : p) p2 += x*x; return sqrt(p2) < 10.0;");
365~~~
366
367The code snippet above defines a column `p` that is a fixed-size array using the component column names and then
368filters on its magnitude by looping over its elements. It must be noted that the usage of strings to define columns
369like the one above is currently the only possibility when using PyROOT. When writing expressions as such, only constants
370and data coming from other columns in the dataset can be involved in the code passed as a string. Local variables and
371functions cannot be used, since the interpreter will not know how to find them. When capturing local state is necessary,
372it must first be declared to the ROOT C++ interpreter.
373
374More information on filters and how to use them to automatically generate cutflow reports can be found [below](#Filters).
375
376### Defining custom columns
377Let's now consider the case in which "myTree" contains two quantities "x" and "y", but our analysis relies on a derived
378quantity `z = sqrt(x*x + y*y)`. Using the Define() transformation, we can create a new column in the dataset containing
379the variable "z":
380~~~{.cpp}
381RDataFrame d("myTree", "file.root");
382auto sqrtSum = [](double x, double y) { return sqrt(x*x + y*y); };
383auto zMean = d.Define("z", sqrtSum, {"x","y"}).Mean("z");
384std::cout << *zMean << std::endl;
385~~~
386Define() creates the variable "z" by applying `sqrtSum` to "x" and "y". Later in the chain of calls we refer to
387variables created with Define() as if they were actual tree branches/columns, but they are evaluated on demand, at most
388once per event. As with filters, Define() calls can be chained with other transformations to create multiple custom
389columns. Define() and Filter() transformations can be concatenated and intermixed at will.
390
391As with filters, it is possible to specify new columns as string expressions. This snippet is analogous to the one above:
392~~~{.cpp}
393RDataFrame d("myTree", "file.root");
394auto zMean = d.Define("z", "sqrt(x*x + y*y)").Mean("z");
395std::cout << *zMean << std::endl;
396~~~
397
398Again the names of the columns used in the expression and their types are inferred automatically. The string must be
399valid C++ and it is just-in-time compiled. The process has a small runtime overhead and like with filters it is currently the only possible approach when using PyROOT.
400
401Previously, when showing the different ways an RDataFrame can be created, we showed a constructor that takes a
402number of entries as a parameter. In the following example we show how to combine such an "empty" RDataFrame with Define()
403transformations to create a dataset on the fly. We then save the generated data on disk using the Snapshot() action.
404~~~{.cpp}
405RDataFrame d(100); // an RDF that will generate 100 entries (currently empty)
406int x = -1;
407auto d_with_columns = d.Define("x", [&x] { return ++x; })
408 .Define("xx", [&x] { return x*x; });
409d_with_columns.Snapshot("myNewTree", "newfile.root");
410~~~
411This example is slightly more advanced than what we have seen so far. First, it makes use of lambda captures (a
412simple way to make external variables available inside the body of C++ lambdas) to act on the same variable `x` from
413both Define() transformations. Second, we have *stored* the transformed dataframe in a variable. This is always
414possible, since at each point of the transformation chain users can store the status of the dataframe for further use (more
415on this [below](#callgraphs)).
416
417You can read more about defining new columns [here](#custom-columns).
418
419\image html RDF_Graph.png "A graph composed of two branches, one starting with a filter and one with a define. The end point of a branch is always an action."
420
421
422### Running on a range of entries
423It is sometimes necessary to limit the processing of the dataset to a range of entries. For this reason, the RDataFrame
424offers the concept of ranges as a node of the RDataFrame chain of transformations; this means that filters, columns and
425actions can be concatenated to and intermixed with Range()s. If a range is specified after a filter, the range will act
426exclusively on the entries passing the filter -- it will not even count the other entries! The same goes for a Range()
427hanging from another Range(). Here are some commented examples:
428~~~{.cpp}
429RDataFrame d("myTree", "file.root");
430// Here we store a dataframe that loops over only the first 30 entries in a variable
431auto d30 = d.Range(30);
432// This is how you pick all entries from 15 onwards
433auto d15on = d.Range(15, 0);
434// We can specify a stride too, in this case we pick an event every 3
435auto d15each3 = d.Range(0, 15, 3);
436~~~
437Note that ranges are not available when multi-threading is enabled. More information on ranges is available
438[here](#ranges).
439
440### Executing multiple actions in the same event loop
441As a final example let us apply two different cuts on branch "MET" and fill two different histograms with the "pt_v" of
442the filtered events.
443By now, you should be able to easily understand what is happening:
444~~~{.cpp}
445RDataFrame d("treeName", "file.root");
446auto h1 = d.Filter("MET > 10").Histo1D("pt_v");
447auto h2 = d.Histo1D("pt_v");
448h1->Draw(); // event loop is run once here
449h2->Draw("SAME"); // no need to run the event loop again
450~~~
451RDataFrame executes all above actions by **running the event-loop only once**. The trick is that actions are not
452executed at the moment they are called, but they are **lazy**, i.e. delayed until the moment one of their results is
453accessed through the smart pointer. At that time, the event loop is triggered and *all* results are produced
454simultaneously.
455
456It is therefore good practice to declare all your transformations and actions *before* accessing their results, allowing
457RDataFrame to run the loop once and produce all results in one go.
458
459### Going parallel
460Let's say we would like to run the previous examples in parallel on several cores, dividing events fairly between cores.
461The only modification required to the snippets would be the addition of this line *before* constructing the main
462dataframe object:
463~~~{.cpp}
464ROOT::EnableImplicitMT();
465~~~
466Simple as that. More details are given [below](#parallel-execution).
467
468\anchor collections
469## Working with collections and object selections
470
471RDataFrame reads collections as the special type [ROOT::RVec](https://root.cern/doc/master/classROOT_1_1VecOps_1_1RVec.html): for example, a column containing an array of floating point numbers can be read as a ROOT::RVecF. C-style arrays (with variable or static size), STL vectors and most other collection types can be read this way.
472
473RVec is a container similar to std::vector (and can be used just like a std::vector) but it also offers a rich interface to operate on the array elements in a vectorised fashion, similarly to Python's NumPy arrays.
474
475For example, to fill a histogram with the "pt" of selected particles for each event, Define() can be used to create a column that contains the desired array elements as follows:
476
477~~~{.cpp}
478// h is filled with all the elements of `good_pts`, for each event
479auto h = df.Define("good_pts", [](const ROOT::RVecF &pt) { return pt[pt > 0]; })
480 .Histo1D("good_pts");
481~~~
482
483And in Python:
484
485~~~{.py}
486h = df.Define("good_pts", "pt[pt > 0]").Histo1D("good_pts")
487~~~
488
489Learn more at ROOT::VecOps::RVec.
490
491\anchor transformations
492## Transformations: manipulating data
493\anchor Filters
494### Filters
495A filter is created through a call to `Filter(f, columnList)` or `Filter(filterString)`. In the first overload, `f` can
496be a function, a lambda expression, a functor class, or any other callable object. It must return a `bool` signalling
497whether the event has passed the selection (`true`) or not (`false`). It should perform "read-only" operations on the
498columns, and should not have side-effects (e.g. modification of an external or static variable) to ensure correctness
499when implicit multi-threading is active. The second overload takes a string with a valid C++ expression in which column
500names are used as variable names (e.g. `Filter("x[0] + x[1] > 0")`). This is a convenience feature that comes with a
501certain runtime overhead: C++ code has to be generated on the fly from this expression before using it in the event
502loop. See the paragraph about "Just-in-time compilation" below for more information.
503
504RDataFrame only evaluates filters when necessary: if multiple filters are chained one after another, they are executed
505in order and the first one returning `false` causes the event to be discarded and triggers the processing of the next
506entry. If multiple actions or transformations depend on the same filter, that filter is not executed multiple times for
507each entry: after the first access it simply serves a cached result.
508
509\anchor named-filters-and-cutflow-reports
510#### Named filters and cutflow reports
511An optional string parameter `name` can be passed to the Filter() method to create a **named filter**. Named filters
512work as usual, but also keep track of how many entries they accept and reject.
513
514Statistics are retrieved through a call to the Report() method:
515
516- when Report() is called on the main RDataFrame object, it returns a ROOT::RDF::RResultPtr<RCutFlowReport> relative to all
517named filters declared up to that point
518- when called on a specific node (e.g. the result of a Define() or Filter()), it returns a ROOT::RDF::RResultPtr<RCutFlowReport>
519relative all named filters in the section of the chain between the main RDataFrame and that node (included).
520
521Stats are stored in the same order as named filters have been added to the graph, and *refer to the latest event-loop*
522that has been run using the relevant RDataFrame.
523
524\anchor ranges
525### Ranges
526When RDataFrame is not being used in a multi-thread environment (i.e. no call to EnableImplicitMT() was made),
527Range() transformations are available. These act very much like filters but instead of basing their decision on
528a filter expression, they rely on `begin`,`end` and `stride` parameters.
529
530- `begin`: initial entry number considered for this range.
531- `end`: final entry number (excluded) considered for this range. 0 means that the range goes until the end of the dataset.
532- `stride`: process one entry of the [begin, end) range every `stride` entries. Must be strictly greater than 0.
533
534The actual number of entries processed downstream of a Range() node will be `(end - begin)/stride` (or less if less
535entries than that are available).
536
537Note that ranges act "locally", not based on the global entry count: `Range(10,50)` means "skip the first 10 entries
538*that reach this node*, let the next 40 entries pass, then stop processing". If a range node hangs from a filter node,
539and the range has a `begin` parameter of 10, that means the range will skip the first 10 entries *that pass the
540preceding filter*.
541
542Ranges allow "early quitting": if all branches of execution of a functional graph reached their `end` value of
543processed entries, the event-loop is immediately interrupted. This is useful for debugging and quick data explorations.
544
545\anchor custom-columns
546### Custom columns
547Custom columns are created by invoking `Define(name, f, columnList)`. As usual, `f` can be any callable object
548(function, lambda expression, functor class...); it takes the values of the columns listed in `columnList` (a list of
549strings) as parameters, in the same order as they are listed in `columnList`. `f` must return the value that will be
550assigned to the temporary column.
551
552A new variable is created called `name`, accessible as if it was contained in the dataset from subsequent
553transformations/actions.
554
555Use cases include:
556- caching the results of complex calculations for easy and efficient multiple access
557- extraction of quantities of interest from complex objects
558- branch aliasing, i.e. changing the name of a branch
559
560An exception is thrown if the `name` of the new column/branch is already in use for another branch in the TTree.
561
562It is also possible to specify the quantity to be stored in the new temporary column as a C++ expression with the method
563`Define(name, expression)`. For example this invocation
564
565~~~{.cpp}
566df.Define("pt", "sqrt(px*px + py*py)");
567~~~
568
569will create a new column called "pt" the value of which is calculated starting from the columns px and py. The system
570builds a just-in-time compiled function starting from the expression after having deduced the list of necessary branches
571from the names of the variables specified by the user.
572
573#### Custom columns as function of slot and entry number
574
575It is possible to create custom columns also as a function of the processing slot and entry numbers. The methods that can
576be invoked are:
577- `DefineSlot(name, f, columnList)`. In this case the callable f has this signature `R(unsigned int, T1, T2, ...)`: the
578first parameter is the slot number which ranges from 0 to ROOT::GetThreadPoolSize() - 1.
579- `DefineSlotEntry(name, f, columnList)`. In this case the callable f has this signature `R(unsigned int, ULong64_t,
580T1, T2, ...)`: the first parameter is the slot number while the second one the number of the entry being processed.
581
582\anchor actions
583## Actions: getting results
584### Instant and lazy actions
585Actions can be **instant** or **lazy**. Instant actions are executed as soon as they are called, while lazy actions are
586executed whenever the object they return is accessed for the first time. As a rule of thumb, actions with a return value
587are lazy, the others are instant.
588
589### Return type of a lazy action
590
591When a lazy action is called, it returns a \link ROOT::RDF::RResultPtr ROOT::RDF::RResultPtr<T>\endlink, where T is the
592type of the result of the action. The final result will be stored in the `RResultPtr` and can be retrieved by
593dereferencing it or via its `GetValue` method.
594
595### Actions that return collections
596
597If the type of the return value of an action is a collection, e.g. `std::vector<int>`, you can iterate its elements
598directly through the wrapping `RResultPtr`:
599
600~~~{.cpp}
601ROOT::RDataFrame df{5};
602auto df1 = df.Define("x", []{ return 42; });
603for (const auto &el: df1.Take<int>("x")){
604 std::cout << "Element: " << el << "\n";
605}
606~~~
607
608~~~{.py}
609df = ROOT.RDataFrame(5).Define("x", "42")
610for el in df.Take[int]("x"):
611 print(f"Element: {el}")
612~~~
613
614### Actions and readers
615
616An action that needs values for its computations will request it from a reader, e.g. a column created via `Define` or
617available from the input dataset. The action will request values from each column of the list of input columns (either
618inferred or specified by the user), in order. For example:
619
620~~~{.cpp}
621ROOT::RDataFrame df{1};
622auto df1 = df.Define("x", []{ return 11; });
623auto df2 = df1.Define("y", []{ return 22; });
624auto graph = df2.Graph<int, int>("x","y");
625~~~
626
627The `Graph` action is going to request first the value from column "x", then that of column "y". Specifically, the order
628of execution of the operations of nodes in this branch of the computation graph is guaranteed to be top to bottom.
629
630\anchor distrdf
631## Distributed execution
632
633RDataFrame applications can be executed in parallel through distributed computing frameworks on a set of remote machines
634thanks to the Python package `ROOT.RDF.Experimental.Distributed`. This experimental, **Python-only** package allows to scale the
635optimized performance RDataFrame can achieve on a single machine to multiple nodes at the same time. It is designed so
636that different backends can be easily plugged in, currently supporting [Apache Spark](http://spark.apache.org/) and
637[Dask](https://dask.org/). To make use of distributed RDataFrame, you only need to switch `ROOT.RDataFrame` with
638the backend-specific `RDataFrame` of your choice, for example:
639
640~~~{.py}
641import ROOT
642
643# Point RDataFrame calls to the Spark specific RDataFrame
644RDataFrame = ROOT.RDF.Experimental.Distributed.Spark.RDataFrame
645
646# It still accepts the same constructor arguments as traditional RDataFrame
647df = RDataFrame("mytree", "myfile.root")
648
649# Continue the application with the traditional RDataFrame API
650sum = df.Filter("x > 10").Sum("y")
651h = df.Histo1D(("name", "title", 10, 0, 10), "x")
652
653print(sum.GetValue())
654h.Draw()
655~~~
656
657The main goal of this package is to support running any RDataFrame application distributedly. Nonetheless, not all
658parts of the RDataFrame API currently work with this package. The subset that is currently available is:
659- AsNumpy
660- Count
661- Define
662- DefinePerSample
663- Filter
664- Graph
665- Histo[1,2,3]D
666- HistoND
667- Max
668- Mean
669- Min
670- Profile[1,2,3]D
671- Redefine
672- Snapshot
673- Stats
674- StdDev
675- Sum
676- Systematic variations: Vary and [VariationsFor](\ref ROOT::RDF::Experimental::VariationsFor).
677- Parallel submission of distributed graphs: [RunGraphs](\ref ROOT::RDF::RunGraphs).
678- Information about the dataframe: GetColumnNames.
679
680with support for more operations coming in the future. Data sources other than TTree and TChain (e.g. CSV, RNTuple) are
681currently not supported.
682
683**Note** that the distributed RDataFrame module is available in a ROOT installation if the following criteria are met:
684- PyROOT is available
685- RDataFrame is available
686- The version of the Python interpreter used to build ROOT is greater or equal than 3.7
687
688### Connecting to a Spark cluster
689
690In order to distribute the RDataFrame workload, you can connect to a Spark cluster you have access to through the
691official [Spark API](https://spark.apache.org/docs/latest/rdd-programming-guide.html#initializing-spark), then hook the
692connection instance to the distributed `RDataFrame` object like so:
693
694~~~{.py}
695import pyspark
696import ROOT
697
698# Create a SparkContext object with the right configuration for your Spark cluster
699conf = SparkConf().setAppName(appName).setMaster(master)
700sc = SparkContext(conf=conf)
701
702# Point RDataFrame calls to the Spark specific RDataFrame
703RDataFrame = ROOT.RDF.Experimental.Distributed.Spark.RDataFrame
704
705# The Spark RDataFrame constructor accepts an optional "sparkcontext" parameter
706# and it will distribute the application to the connected cluster
707df = RDataFrame("mytree", "myfile.root", sparkcontext = sc)
708~~~
709
710If an instance of [SparkContext](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.SparkContext.html)
711is not provided, the default behaviour is to create one in the background for you.
712
713### Connecting to a Dask cluster
714
715Similarly, you can connect to a Dask cluster by creating your own connection object which internally operates with one
716of the cluster schedulers supported by Dask (more information in the
717[Dask distributed docs](http://distributed.dask.org/en/stable/)):
718
719~~~{.py}
720import ROOT
721from dask.distributed import Client
722
723# Point RDataFrame calls to the Dask specific RDataFrame
724RDataFrame = ROOT.RDF.Experimental.Distributed.Dask.RDataFrame
725
726# In a Python script the Dask client needs to be initalized in a context
727# Jupyter notebooks / Python session don't need this
728if __name__ == "__main__":
729 # With an already setup cluster that exposes a Dask scheduler endpoint
730 client = Client("dask_scheduler.domain.com:8786")
731
732 # The Dask RDataFrame constructor accepts the Dask Client object as an optional argument
733 df = RDataFrame("mytree","myfile.root", daskclient=client)
734 # Proceed as usual
735 df.Define("x","someoperation").Histo1D(("name", "title", 10, 0, 10), "x")
736~~~
737
738If an instance of [distributed.Client](http://distributed.dask.org/en/stable/api.html#distributed.Client) is not
739provided to the RDataFrame object, it will be created for you and it will run the computations in the local machine
740using all cores available.
741
742### Choosing the number of distributed tasks
743
744A distributed RDataFrame has internal logic to define in how many chunks the input dataset will be split before sending
745tasks to the distributed backend. Each task reads and processes one of said chunks. The logic is backend-dependent, but
746generically tries to infer how many cores are available in the cluster through the connection object. The number of
747tasks will be equal to the inferred number of cores. There are cases where the connection object of the chosen backend
748doesn't have information about the actual resources of the cluster. An example of this is when using Dask to connect to
749a batch system. The client object created at the beginning of the application does not automatically know how many cores
750will be available during distributed execution, since the jobs are submitted to the batch system after the creation of
751the connection. In such cases, the logic is to default to process the whole dataset in 2 tasks.
752
753The number of tasks submitted for distributed execution can be also set programmatically, by providing the optional
754keyword argument `npartitions` when creating the RDataFrame object. This parameter is accepted irrespectively of the
755backend used:
756
757~~~{.py}
758import ROOT
759
760# Define correct imports and access the distributed RDataFrame appropriate for the
761# backend used in the analysis
762RDataFrame = ROOT.RDF.Experimental.Distributed.[BACKEND].RDataFrame
763
764if __name__ == "__main__":
765 # The `npartitions` optional argument tells the RDataFrame how many tasks are desired
766 df = RDataFrame("mytree","myfile.root", npartitions=NPARTITIONS)
767 # Proceed as usual
768 df.Define("x","someoperation").Histo1D(("name", "title", 10, 0, 10), "x")
769~~~
770
771Note that when processing a TTree or TChain dataset, the `npartitions` value should not exceed the number of clusters in
772the dataset. The number of clusters in a TTree can be retrieved by typing `rootls -lt myfile.root` at a command line.
773
774### Distributed Snapshot
775
776The Snapshot operation behaves slightly differently when executed distributedly. First off, it requires the path
777supplied to the Snapshot call to be accessible from any worker of the cluster and from the client machine (in general
778it should be provided as an absolute path). Another important difference is that `n` separate files will be produced,
779where `n` is the number of dataset partitions. As with local RDataFrame, the result of a Snapshot on a distributed
780RDataFrame is another distributed RDataFrame on which we can define a new computation graph and run more distributed
781computations.
782
783### Distributed RunGraphs
784
785Submitting multiple distributed RDataFrame executions is supported through the RunGraphs function. Similarly to its
786local counterpart, the function expects an iterable of objects representing an RDataFrame action. Each action will be
787triggered concurrently to send multiple computation graphs to a distributed cluster at the same time:
788
789~~~{.py}
790import ROOT
791RDataFrame = ROOT.RDF.Experimental.Distributed.Dask.RDataFrame
792RunGraphs = ROOT.RDF.Experimental.Distributed.RunGraphs
793
794# Create 3 different dataframes and book an histogram on each one
795histoproxies = [
796 RDataFrame(100)
797 .Define("x", "rdfentry_")
798 .Histo1D(("name", "title", 10, 0, 100), "x")
799 for _ in range(4)
800]
801
802# Execute the 3 computation graphs
803RunGraphs(histoproxies)
804# Retrieve all the histograms in one go
805histos = [histoproxy.GetValue() for histoproxy in histoproxies]
806~~~
807
808Every distributed backend supports this feature and graphs belonging to different backends can be still triggered with
809a single call to RunGraphs (e.g. it is possible to send a Spark job and a Dask job at the same time).
810
811### Histogram models in distributed mode
812
813When calling a Histo*D operation in distributed mode, remember to pass to the function the model of the histogram to be
814computed, e.g. the axis range and the number of bins:
815
816~~~{.py}
817import ROOT
818RDataFrame = ROOT.RDF.Experimental.Distributed.[BACKEND].RDataFrame
819
820if __name__ == "__main__":
821 df = RDataFrame("mytree","myfile.root").Define("x","someoperation")
822 # The model can be passed either as a tuple with the arguments in the correct order
823 df.Histo1D(("name", "title", 10, 0, 10), "x")
824 # Or by creating the specific struct
825 model = ROOT.RDF.TH1DModel("name", "title", 10, 0, 10)
826 df.Histo1D(model, "x")
827~~~
828
829Without this, two partial histograms resulting from two distributed tasks would have incompatible binning, thus leading
830to errors when merging them. Failing to pass a histogram model will raise an error on the client side, before starting
831the distributed execution.
832
833
834\anchor parallel-execution
835## Performance tips and parallel execution
836As pointed out before in this document, RDataFrame can transparently perform multi-threaded event loops to speed up
837the execution of its actions. Users have to call ROOT::EnableImplicitMT() *before* constructing the RDataFrame
838object to indicate that it should take advantage of a pool of worker threads. **Each worker thread processes a distinct
839subset of entries**, and their partial results are merged before returning the final values to the user.
840There are no guarantees on the order in which threads will process the batches of entries.
841In particular, note that this means that, for multi-thread event loops, there is no
842guarantee on the order in which Snapshot() will _write_ entries: they could be scrambled with respect to the input dataset. The values of the special `rdfentry_` column will also not correspond to the entry numbers in the input dataset (e.g. TChain) in multi-thread runs.
843
844\warning By default, RDataFrame will use as many threads as the hardware supports, using up **all** the resources on
845a machine. This might be undesirable on shared computing resources such as a batch cluster. Therefore, when running on shared computing resources, use
846~~~{.cpp}
847ROOT::EnableImplicitMT(i)
848~~~
849replacing `i` with the number of CPUs/slots that were allocated for this job.
850
851### Thread-safety of user-defined expressions
852RDataFrame operations such as Histo1D() or Snapshot() are guaranteed to work correctly in multi-thread event loops.
853User-defined expressions, such as strings or lambdas passed to Filter(), Define(), Foreach(), Reduce() or Aggregate()
854will have to be thread-safe, i.e. it should be possible to call them concurrently from different threads.
855
856Note that simple Filter() and Define() transformations will inherently satisfy this requirement: Filter() / Define()
857expressions will often be *pure* in the functional programming sense (no side-effects, no dependency on external state),
858which eliminates all risks of race conditions.
859
860In order to facilitate writing of thread-safe operations, some RDataFrame features such as Foreach(), Define() or \link ROOT::RDF::RResultPtr::OnPartialResult OnPartialResult()\endlink
861offer thread-aware counterparts (ForeachSlot(), DefineSlot(), \link ROOT::RDF::RResultPtr::OnPartialResultSlot OnPartialResultSlot()\endlink): their only difference is that they
862will pass an extra `slot` argument (an unsigned integer) to the user-defined expression. When calling user-defined code
863concurrently, RDataFrame guarantees that different threads will employ different values of the `slot` parameter,
864where `slot` will be a number between 0 and `GetNSlots() - 1`.
865In other words, within a slot, computation runs sequentially and events are processed sequentially.
866Note that the same slot might be associated to different threads over the course of a single event loop, but two threads
867will never receive the same slot at the same time.
868This extra parameter might facilitate writing safe parallel code by having each thread write/modify a different
869processing slot, e.g. a different element of a list. See [here](#generic-actions) for an example usage of ForeachSlot().
870
871### Parallel execution of multiple RDataFrame event loops
872A complex analysis may require multiple separate RDataFrame computation graphs to produce all desired results. This poses the challenge that the
873event loops of each computation graph can be parallelized, but the different loops run sequentially, one after the other.
874On many-core architectures it might be desirable to run different event loops concurrently to improve resource usage.
875ROOT::RDF::RunGraphs() allows running multiple RDataFrame event loops concurrently:
876~~~{.cpp}
877ROOT::EnableImplicitMT();
878ROOT::RDataFrame df1("tree1", "f1.root");
879ROOT::RDataFrame df2("tree2", "f2.root");
880auto histo1 = df1.Histo1D("x");
881auto histo2 = df2.Histo1D("y");
882
883// just accessing result pointers, the event loops of separate RDataFrames run one after the other
884histo1->Draw(); // runs first multi-thread event loop
885histo2->Draw(); // runs second multi-thread event loop
886
887// alternatively, with ROOT::RDF::RunGraphs, event loops for separate computation graphs can run concurrently
888ROOT::RDF::RunGraphs({histo1, histo2});
889histo1->Draw(); // results can then be used as usual
890~~~
891
892### Performance considerations
893
894To obtain the maximum performance out of RDataFrame, make sure to avoid just-in-time compiled versions of transformations and actions if at all possible.
895For instance, `Filter("x > 0")` requires just-in-time compilation of the corresponding C++ logic, while the equivalent `Filter([](float x) { return x > 0.; }, {"x"})` does not.
896Similarly, `Histo1D("x")` requires just-in-time compilation after the type of `x` is retrieved from the dataset, while `Histo1D<float>("x")` does not; the latter spelling
897should be preferred for performance-critical applications.
898
899Python applications cannot easily specify template parameters or pass C++ callables to RDataFrame.
900See [Efficient analysis in Python](#python) for possible ways to speed up hot paths in this case.
901
902Just-in-time compilation happens once, right before starting an event loop. To reduce the runtime cost of this step, make sure to book all operations *for all RDataFrame computation graphs*
903before the first event loop is triggered: just-in-time compilation will happen once for all code required to be generated up to that point, also across different computation graphs.
904
905Also make sure not to count the just-in-time compilation time (which happens once before the event loop and does not depend on the size of the dataset) as part of the event loop runtime (which scales with the size of the dataset). RDataFrame has an experimental logging feature that simplifies measuring the time spent in just-in-time compilation and in the event loop (as well as providing some more interesting information). See [Activating RDataFrame execution logs](\ref rdf-logging).
906
907### Memory usage
908
909There are two reasons why RDataFrame may consume more memory than expected. Firstly, each result is duplicated for each worker thread, which e.g. in case of many (possibly multi-dimensional) histograms with fine binning can result in visible memory consumption during the event loop. The thread-local copies of the results are destroyed when the final result is produced. Reducing the number of threads or using coarser binning will reduce the memory usage.
910
911Secondly, just-in-time compilation of string expressions or non-templated actions (see the previous paragraph) causes Cling, ROOT's C++ interpreter, to allocate some memory for the generated code that is only released at the end of the application. This commonly results in memory usage creep in long-running applications that create many RDataFrames one after the other. Possible mitigations include creating and running each RDataFrame event loop in a sub-process, or booking all operations for all different RDataFrame computation graphs before the first event loop is triggered, so that the interpreter is invoked only once for all computation graphs:
912
913~~~{.cpp}
914// assuming df1 and df2 are separate computation graphs, do:
915auto h1 = df1.Histo1D("x");
916auto h2 = df2.Histo1D("y");
917h1->Draw(); // we just-in-time compile everything needed by df1 and df2 here
918h2->Draw("SAME");
919
920// do not:
921auto h1 = df1.Histo1D("x");
922h1->Draw(); // we just-in-time compile here
923auto h2 = df2.Histo1D("y");
924h2->Draw("SAME"); // we just-in-time compile again here, as the second Histo1D call is new
925~~~
926
927\anchor more-features
928## More features
929Here is a list of the most important features that have been omitted in the "Crash course" for brevity.
930You don't need to read all these to start using RDataFrame, but they are useful to save typing time and runtime.
931
932\anchor systematics
933### Systematic variations
934
935Starting from ROOT v6.26, RDataFrame provides a flexible syntax to define systematic variations.
936This is done in two steps: a) variations for one or more existing columns are registered via Vary() and b) variations
937of normal RDataFrame results are extracted with a call to VariationsFor(). In between these steps, no other change
938to the analysis code is required: the presence of systematic variations for certain columns is automatically propagated
939through filters, defines and actions, and RDataFrame will take these dependencies into account when producing varied
940results. VariationsFor() is included in header `ROOT/RDFHelpers.hxx`, which compiled C++ programs must include
941explicitly.
942
943An example usage of Vary() and VariationsFor() in C++:
944
945~~~{.cpp}
946auto nominal_hx =
947 df.Vary("pt", "ROOT::RVecD{pt*0.9f, pt*1.1f}", {"down", "up"})
948 .Filter("pt > pt_cut")
949 .Define("x", someFunc, {"pt"})
950 .Histo1D<float>("x");
951
952// request the generation of varied results from the nominal
953ROOT::RDF::Experimental::RResultMap<TH1D> hx = ROOT::RDF::Experimental::VariationsFor(nominal_hx);
954
955// the event loop runs here, upon first access to any of the results or varied results:
956hx["nominal"].Draw(); // same effect as nominal_hx->Draw()
957hx["pt:down"].Draw("SAME");
958hx["pt:up"].Draw("SAME");
959~~~
960
961A list of variation "tags" is passed as last argument to Vary(): they give a name to the varied values that are returned
962as elements of an RVec of the appropriate type. The number of variation tags must correspond to the number of elements
963the RVec returned by the expression (2 in the example above: the first element will correspond to tag "down", the second
964to tag "up"). The _full_ variation name will be composed of the varied column name and the variation tags (e.g.
965"pt:down", "pt:up" in this example). Python usage looks similar.
966
967Note how we use the "pt" column as usual in the Filter() and Define() calls and we simply use "x" as the value to fill
968the resulting histogram. To produce the varied results, RDataFrame will automatically execute the Filter and Define
969calls for each variation and fill the histogram with values and cuts that depend on the variation.
970
971There is no limitation to the complexity of a Vary() expression, and just like for Define() and Filter() calls users are
972not limited to string expressions but they can also pass any valid C++ callable, including lambda functions and
973complex functors. The callable can be applied to zero or more existing columns and it will always receive their
974_nominal_ values in input.
975
976**Varying multiple columns in lockstep**
977
978In the following Python snippet we use the Vary() signature that allows varying multiple columns simultaneously or
979"in lockstep":
980
981~~~{.python}
982df.Vary(["pt", "eta"],
983 "RVec<RVecF>{{pt*0.9, pt*1.1}, {eta*0.9, eta*1.1}}",
984 variationTags=["down", "up"],
985 variationName="ptAndEta")
986~~~
987
988The expression returns an RVec of two RVecs: each inner vector contains the varied values for one column, and the
989inner vectors follow the same ordering as the column names passed as first argument. Besides the variation tags, in
990this case we also have to explicitly pass a variation name as there is no one column name that can be used as default.
991
992The call above will produce variations "ptAndEta:down" and "ptAndEta:up".
993
994**Combining multiple variations**
995
996Even if a result depends on multiple variations, only one is applied at a time, i.e. there will be no result produced
997by applying multiple systematic variations at the same time.
998For example, in the following example snippet, the RResultMap instance `all_h` will contain keys "nominal", "pt:down",
999"pt:up", "eta:0", "eta:1", but no "pt:up&&eta:0" or similar:
1000
1001~~~{.cpp}
1002auto df = _df.Vary("pt",
1003 "ROOT::RVecD{pt*0.9, pt*1.1}",
1004 {"down", "up"})
1005 .Vary("eta",
1006 [](float eta) { return RVecF{eta*0.9f, eta*1.1f}; },
1007 {"eta"},
1008 2);
1009
1010auto nom_h = df.Histo2D(histoModel, "pt", "eta");
1011auto all_hs = VariationsFor(nom_h);
1012all_hs.GetKeys(); // returns {"nominal", "pt:down", "pt:up", "eta:0", "eta:1"}
1013~~~
1014
1015Note how we passed the integer `2` instead of a list of variation tags to the second Vary() invocation: this is a
1016shorthand that automatically generates tags 0 to N-1 (in this case 0 and 1).
1017
1018\note As of v6.26, VariationsFor() and RResultMap are in the `ROOT::RDF::Experimental` namespace, to indicate that these
1019 interfaces might still evolve and improve based on user feedback. We expect that some aspects of the related
1020 programming model will be streamlined in future versions.
1021
1022\note As of v6.26, the results of a Snapshot(), Report() or Display() call cannot be varied (i.e. it is not possible to
1023 call VariationsFor() on them. These limitations will be lifted in future releases.
1024
1025\anchor rnode
1026### RDataFrame objects as function arguments and return values
1027RDataFrame variables/nodes are relatively cheap to copy and it's possible to both pass them to (or move them into)
1028functions and to return them from functions. However, in general each dataframe node will have a different C++ type,
1029which includes all available compile-time information about what that node does. One way to cope with this complication
1030is to use template functions and/or C++14 auto return types:
1031~~~{.cpp}
1032template <typename RDF>
1033auto ApplySomeFilters(RDF df)
1034{
1035 return df.Filter("x > 0").Filter([](int y) { return y < 0; }, {"y"});
1036}
1037~~~
1038
1039A possibly simpler, C++11-compatible alternative is to take advantage of the fact that any dataframe node can be
1040converted (implicitly or via an explicit cast) to the common type ROOT::RDF::RNode:
1041~~~{.cpp}
1042// a function that conditionally adds a Range to an RDataFrame node.
1043RNode MaybeAddRange(RNode df, bool mustAddRange)
1044{
1045 return mustAddRange ? df.Range(1) : df;
1046}
1047// use as :
1048ROOT::RDataFrame df(10);
1049auto maybeRangedDF = MaybeAddRange(df, true);
1050~~~
1051
1052The conversion to ROOT::RDF::RNode is cheap, but it will introduce an extra virtual call during the RDataFrame event
1053loop (in most cases, the resulting performance impact should be negligible). Python users can perform the conversion with the helper function `ROOT.RDF.AsRNode`.
1054
1055\anchor RDFCollections
1056### Storing RDataFrame objects in collections
1057
1058ROOT::RDF::RNode also makes it simple to store RDataFrame nodes in collections, e.g. a `std::vector<RNode>` or a `std::map<std::string, RNode>`:
1059
1060~~~{.cpp}
1061std::vector<ROOT::RDF::RNode> dfs;
1062dfs.emplace_back(ROOT::RDataFrame(10));
1063dfs.emplace_back(dfs[0].Define("x", "42.f"));
1064~~~
1065
1066\anchor callbacks
1067### Executing callbacks every N events
1068It's possible to schedule execution of arbitrary functions (callbacks) during the event loop.
1069Callbacks can be used e.g. to inspect partial results of the analysis while the event loop is running,
1070drawing a partially-filled histogram every time a certain number of new entries is processed, or
1071displaying a progress bar while the event loop runs.
1072
1073For example one can draw an up-to-date version of a result histogram every 100 entries like this:
1074~~~{.cpp}
1075auto h = df.Histo1D("x");
1076TCanvas c("c","x hist");
1077h.OnPartialResult(100, [&c](TH1D &h_) { c.cd(); h_.Draw(); c.Update(); });
1078// event loop runs here, this final `Draw` is executed after the event loop is finished
1079h->Draw();
1080~~~
1081
1082Callbacks are registered to a ROOT::RDF::RResultPtr and must be callables that takes a reference to the result type as argument
1083and return nothing. RDataFrame will invoke registered callbacks passing partial action results as arguments to them
1084(e.g. a histogram filled with a part of the selected events).
1085
1086Read more on ROOT::RDF::RResultPtr::OnPartialResult() and ROOT::RDF::RResultPtr::OnPartialResultSlot().
1087
1088\anchor default-branches
1089### Default column lists
1090When constructing an RDataFrame object, it is possible to specify a **default column list** for your analysis, in the
1091usual form of a list of strings representing branch/column names. The default column list will be used as a fallback
1092whenever a list specific to the transformation/action is not present. RDataFrame will take as many of these columns as
1093needed, ignoring trailing extra names if present.
1094~~~{.cpp}
1095// use "b1" and "b2" as default columns
1096RDataFrame d1("myTree", "file.root", {"b1","b2"});
1097auto h = d1.Filter([](int b1, int b2) { return b1 > b2; }) // will act on "b1" and "b2"
1098 .Histo1D(); // will act on "b1"
1099
1100// just one default column this time
1101RDataFrame d2("myTree", "file.root", {"b1"});
1102auto min = d2.Filter([](double b2) { return b2 > 0; }, {"b2"}) // we can still specify non-default column lists
1103 .Min(); // returns the minimum value of "b1" for the filtered entries
1104~~~
1105
1106\anchor helper-cols
1107### Special helper columns: rdfentry_ and rdfslot_
1108Every instance of RDataFrame is created with two special columns called `rdfentry_` and `rdfslot_`. The `rdfentry_`
1109column is of type `ULong64_t` and it holds the current entry number while `rdfslot_` is an `unsigned int`
1110holding the index of the current data processing slot.
1111For backwards compatibility reasons, the names `tdfentry_` and `tdfslot_` are also accepted.
1112These columns are ignored by operations such as [Cache](classROOT_1_1RDF_1_1RInterface.html#aaaa0a7bb8eb21315d8daa08c3e25f6c9)
1113or [Snapshot](classROOT_1_1RDF_1_1RInterface.html#a233b7723e498967f4340705d2c4db7f8).
1114
1115\warning Note that in multi-thread event loops the values of `rdfentry_` _do not_ correspond to what would be the entry numbers
1116of a TChain constructed over the same set of ROOT files, as the entries are processed in an unspecified order.
1117
1118\anchor jitting
1119### Just-in-time compilation: column type inference and explicit declaration of column types
1120C++ is a statically typed language: all types must be known at compile-time. This includes the types of the TTree
1121branches we want to work on. For filters, defined columns and some of the actions, **column types are deduced from the
1122signature** of the relevant filter function/temporary column expression/action function:
1123~~~{.cpp}
1124// here b1 is deduced to be `int` and b2 to be `double`
1125df.Filter([](int x, double y) { return x > 0 && y < 0.; }, {"b1", "b2"});
1126~~~
1127If we specify an incorrect type for one of the columns, an exception with an informative message will be thrown at
1128runtime, when the column value is actually read from the dataset: RDataFrame detects type mismatches. The same would
1129happen if we swapped the order of "b1" and "b2" in the column list passed to Filter().
1130
1131Certain actions, on the other hand, do not take a function as argument (e.g. Histo1D()), so we cannot deduce the type of
1132the column at compile-time. In this case **RDataFrame infers the type of the column** from the TTree itself. This
1133is why we never needed to specify the column types for all actions in the above snippets.
1134
1135When the column type is not a common one such as `int`, `double`, `char` or `float` it is nonetheless good practice to
1136specify it as a template parameter to the action itself, like this:
1137~~~{.cpp}
1138df.Histo1D("b1"); // OK, the type of "b1" is deduced at runtime
1139df.Min<MyNumber_t>("myObject"); // OK, "myObject" is deduced to be of type `MyNumber_t`
1140~~~
1141
1142Deducing types at runtime requires the just-in-time compilation of the relevant actions, which has a small runtime
1143overhead, so specifying the type of the columns as template parameters to the action is good practice when performance is a goal.
1144
1145When strings are passed as expressions to Filter() or Define(), fundamental types are passed as constants. This avoids certaincommon mistakes such as typing `x = 0` rather than `x == 0`:
1146
1147~~~{.cpp}
1148// this throws an error (note the typo)
1149df.Define("x", "0").Filter("x = 0");
1150~~~
1151
1152\anchor generic-actions
1153### User-defined custom actions
1154RDataFrame strives to offer a comprehensive set of standard actions that can be performed on each event. At the same
1155time, it allows users to inject their own action code to perform arbitrarily complex data reductions.
1156
1157#### Implementing custom actions with Book()
1158
1159Through the Book() method, users can implement a custom action and have access to the same features
1160that built-in RDataFrame actions have, e.g. hooks to events related to the start, end and execution of the
1161event loop, or the possibility to return a lazy RResultPtr to an arbitrary type of result:
1162
1163~~~{.cpp}
1164#include <ROOT/RDataFrame.hxx>
1165#include <memory>
1166
1167class MyCounter : public ROOT::Detail::RDF::RActionImpl<MyCounter> {
1168 std::shared_ptr<int> fFinalResult = std::make_shared<int>(0);
1169 std::vector<int> fPerThreadResults;
1170
1171public:
1172 // We use a public type alias to advertise the type of the result of this action
1173 using Result_t = int;
1174
1175 MyCounter(unsigned int nSlots) : fPerThreadResults(nSlots) {}
1176
1177 // Called before the event loop to retrieve the address of the result that will be filled/generated.
1178 std::shared_ptr<int> GetResultPtr() const { return fFinalResult; }
1179
1180 // Called at the beginning of the event loop.
1181 void Initialize() {}
1182
1183 // Called at the beginning of each processing task.
1184 void InitTask(TTreeReader *, int) {}
1185
1186 /// Called at every entry.
1187 void Exec(unsigned int slot)
1188 {
1189 fPerThreadResults[slot]++;
1190 }
1191
1192 // Called at the end of the event loop.
1193 void Finalize()
1194 {
1195 *fFinalResult = std::accumulate(fPerThreadResults.begin(), fPerThreadResults.end(), 0);
1196 }
1197
1198 // Called by RDataFrame to retrieve the name of this action.
1199 std::string GetActionName() const { return "MyCounter"; }
1200};
1201
1202int main() {
1203 ROOT::RDataFrame df(10);
1204 ROOT::RDF::RResultPtr<int> resultPtr = df.Book<>(MyCounter{df.GetNSlots()}, {});
1205 // The GetValue call triggers the event loop
1206 std::cout << "Number of processed entries: " << resultPtr.GetValue() << std::endl;
1207}
1208~~~
1209
1210See the Book() method for more information and [this tutorial](https://root.cern/doc/master/df018__customActions_8C.html)
1211for a more complete example.
1212
1213#### Injecting arbitrary code in the event loop with Foreach() and ForeachSlot()
1214
1215Foreach() takes a callable (lambda expression, free function, functor...) and a list of columns and
1216executes the callable on the values of those columns for each event that passes all upstream selections.
1217It can be used to perform actions that are not already available in the interface. For example, the following snippet
1218evaluates the root mean square of column "x":
1219~~~{.cpp}
1220// Single-thread evaluation of RMS of column "x" using Foreach
1221double sumSq = 0.;
1222unsigned int n = 0;
1223df.Foreach([&sumSq, &n](double x) { ++n; sumSq += x*x; }, {"x"});
1224std::cout << "rms of x: " << std::sqrt(sumSq / n) << std::endl;
1225~~~
1226In multi-thread runs, users are responsible for the thread-safety of the expression passed to Foreach():
1227thread will execute the expression concurrently.
1228The code above would need to employ some resource protection mechanism to ensure non-concurrent writing of `rms`; but
1229this is probably too much head-scratch for such a simple operation.
1230
1231ForeachSlot() can help in this situation. It is an alternative version of Foreach() for which the function takes an
1232additional "processing slot" parameter besides the columns it should be applied to. RDataFrame
1233guarantees that ForeachSlot() will invoke the user expression with different `slot` parameters for different concurrent
1234executions (see [Special helper columns: rdfentry_ and rdfslot_](\ref helper-cols) for more information on the slot parameter).
1235We can take advantage of ForeachSlot() to evaluate a thread-safe root mean square of column "x":
1236~~~{.cpp}
1237// Thread-safe evaluation of RMS of column "x" using ForeachSlot
1238ROOT::EnableImplicitMT();
1239const unsigned int nSlots = df.GetNSlots();
1240std::vector<double> sumSqs(nSlots, 0.);
1241std::vector<unsigned int> ns(nSlots, 0);
1242
1243df.ForeachSlot([&sumSqs, &ns](unsigned int slot, double x) { sumSqs[slot] += x*x; ns[slot] += 1; }, {"x"});
1244double sumSq = std::accumulate(sumSqs.begin(), sumSqs.end(), 0.); // sum all squares
1245unsigned int n = std::accumulate(ns.begin(), ns.end(), 0); // sum all counts
1246std::cout << "rms of x: " << std::sqrt(sumSq / n) << std::endl;
1247~~~
1248Notice how we created one `double` variable for each processing slot and later merged their results via `std::accumulate`.
1249
1250
1251\anchor friends
1252### Friend trees
1253Friend TTrees are supported by RDataFrame.
1254Friend TTrees with a TTreeIndex are supported starting from ROOT v6.24.
1255
1256To use friend trees in RDataFrame, it is necessary to add the friends directly to
1257the tree and instantiate an RDataFrame with the main tree:
1258
1259~~~{.cpp}
1260TTree t([...]);
1261TTree ft([...]);
1262t.AddFriend(&ft, "myFriend");
1263
1264RDataFrame d(t);
1265auto f = d.Filter("myFriend.MyCol == 42");
1266~~~
1267
1268Columns coming from the friend trees can be referred to by their full name, like in the example above,
1269or the friend tree name can be omitted in case the column name is not ambiguous (e.g. "MyCol" could be used instead of
1270 "myFriend.MyCol" in the example above).
1271
1272
1273\anchor other-file-formats
1274### Reading data formats other than ROOT trees
1275RDataFrame can be interfaced with RDataSources. The ROOT::RDF::RDataSource interface defines an API that RDataFrame can use to read arbitrary columnar data formats.
1276
1277RDataFrame calls into concrete RDataSource implementations to retrieve information about the data, retrieve (thread-local) readers or "cursors" for selected columns
1278and to advance the readers to the desired data entry.
1279Some predefined RDataSources are natively provided by ROOT such as the ROOT::RDF::RCsvDS which allows to read comma separated files:
1280~~~{.cpp}
1281auto tdf = ROOT::RDF::MakeCsvDataFrame("MuRun2010B.csv");
1282auto filteredEvents =
1283 tdf.Filter("Q1 * Q2 == -1")
1284 .Define("m", "sqrt(pow(E1 + E2, 2) - (pow(px1 + px2, 2) + pow(py1 + py2, 2) + pow(pz1 + pz2, 2)))");
1285auto h = filteredEvents.Histo1D("m");
1286h->Draw();
1287~~~
1288
1289See also FromNumpy (Python-only), FromRNTuple(), FromArrow(), FromSqlite().
1290
1291\anchor callgraphs
1292### Computation graphs (storing and reusing sets of transformations)
1293
1294As we saw, transformed dataframes can be stored as variables and reused multiple times to create modified versions of the dataset. This implicitly defines a **computation graph** in which
1295several paths of filtering/creation of columns are executed simultaneously, and finally aggregated results are produced.
1296
1297RDataFrame detects when several actions use the same filter or the same defined column, and **only evaluates each
1298filter or defined column once per event**, regardless of how many times that result is used down the computation graph.
1299Objects read from each column are **built once and never copied**, for maximum efficiency.
1300When "upstream" filters are not passed, subsequent filters, temporary column expressions and actions are not evaluated,
1301so it might be advisable to put the strictest filters first in the graph.
1302
1303\anchor representgraph
1304### Visualizing the computation graph
1305It is possible to print the computation graph from any node to obtain a [DOT (graphviz)](https://en.wikipedia.org/wiki/DOT_(graph_description_language)) representation either on the standard output
1306or in a file.
1307
1308Invoking the function ROOT::RDF::SaveGraph() on any node that is not the head node, the computation graph of the branch
1309the node belongs to is printed. By using the head node, the entire computation graph is printed.
1310
1311Following there is an example of usage:
1312~~~{.cpp}
1313// First, a sample computational graph is built
1314ROOT::RDataFrame df("tree", "f.root");
1315
1316auto df2 = df.Define("x", []() { return 1; })
1317 .Filter("col0 % 1 == col0")
1318 .Filter([](int b1) { return b1 <2; }, {"cut1"})
1319 .Define("y", []() { return 1; });
1320
1321auto count = df2.Count();
1322
1323// Prints the graph to the rd1.dot file in the current directory
1324ROOT::RDF::SaveGraph(df, "./mydot.dot");
1325// Prints the graph to standard output
1326ROOT::RDF::SaveGraph(df);
1327~~~
1328
1329The generated graph can be rendered using one of the graphviz filters, e.g. `dot`. For instance, the image below can be generated with the following command:
1330~~~{.sh}
1331$ dot -Tpng computation_graph.dot -ocomputation_graph.png
1332~~~
1333
1334\image html RDF_Graph2.png
1335
1336\anchor rdf-logging
1337### Activating RDataFrame execution logs
1338
1339RDataFrame has experimental support for verbose logging of the event loop runtimes and other interesting related information. It is activated as follows:
1340~~~{.cpp}
1341#include <ROOT/RLogger.hxx>
1342
1343// this increases RDF's verbosity level as long as the `verbosity` variable is in scope
1344auto verbosity = ROOT::Experimental::RLogScopedVerbosity(ROOT::Detail::RDF::RDFLogChannel(), ROOT::Experimental::ELogLevel::kInfo);
1345~~~
1346
1347or in Python:
1348~~~{.python}
1349import ROOT
1350
1351verbosity = ROOT.Experimental.RLogScopedVerbosity(ROOT.Detail.RDF.RDFLogChannel(), ROOT.Experimental.ELogLevel.kInfo)
1352~~~
1353
1354More information (e.g. start and end of each multi-thread task) is printed using `ELogLevel.kDebug` and even more
1355(e.g. a full dump of the generated code that RDataFrame just-in-time-compiles) using `ELogLevel.kDebug+10`.
1356*/
1357// clang-format on
1358
1359namespace ROOT {
1360
1362using ColumnNamesPtr_t = std::shared_ptr<const ColumnNames_t>;
1363
1364////////////////////////////////////////////////////////////////////////////
1365/// \brief Build the dataframe.
1366/// \param[in] treeName Name of the tree contained in the directory
1367/// \param[in] dirPtr TDirectory where the tree is stored, e.g. a TFile.
1368/// \param[in] defaultColumns Collection of default columns.
1369///
1370/// The default columns are looked at in case no column is specified in the
1371/// booking of actions or transformations.
1372/// \see ROOT::RDF::RInterface for the documentation of the methods available.
1373RDataFrame::RDataFrame(std::string_view treeName, TDirectory *dirPtr, const ColumnNames_t &defaultColumns)
1374 : RInterface(std::make_shared<RDFDetail::RLoopManager>(nullptr, defaultColumns))
1375{
1376 if (!dirPtr) {
1377 auto msg = "Invalid TDirectory!";
1378 throw std::runtime_error(msg);
1379 }
1380 const std::string treeNameInt(treeName);
1381 auto tree = static_cast<TTree *>(dirPtr->Get(treeNameInt.c_str()));
1382 if (!tree) {
1383 auto msg = "Tree \"" + treeNameInt + "\" cannot be found!";
1384 throw std::runtime_error(msg);
1385 }
1386 GetProxiedPtr()->SetTree(std::shared_ptr<TTree>(tree, [](TTree *) {}));
1387}
1388
1389////////////////////////////////////////////////////////////////////////////
1390/// \brief Build the dataframe.
1391/// \param[in] treeName Name of the tree contained in the directory
1392/// \param[in] filenameglob TDirectory where the tree is stored, e.g. a TFile.
1393/// \param[in] defaultColumns Collection of default columns.
1394///
1395/// The filename glob supports the same type of expressions as TChain::Add(), and it is passed as-is to TChain's
1396/// constructor.
1397///
1398/// The default columns are looked at in case no column is specified in the
1399/// booking of actions or transformations.
1400/// \see ROOT::RDF::RInterface for the documentation of the methods available.
1401RDataFrame::RDataFrame(std::string_view treeName, std::string_view filenameglob, const ColumnNames_t &defaultColumns)
1402 : RInterface(std::make_shared<RDFDetail::RLoopManager>(nullptr, defaultColumns))
1403{
1404 const std::string treeNameInt(treeName);
1405 const std::string filenameglobInt(filenameglob);
1406 auto chain = std::make_shared<TChain>(treeNameInt.c_str(), "", TChain::kWithoutGlobalRegistration);
1407 chain->Add(filenameglobInt.c_str());
1408 GetProxiedPtr()->SetTree(std::move(chain));
1409}
1410
1411////////////////////////////////////////////////////////////////////////////
1412/// \brief Build the dataframe.
1413/// \param[in] treeName Name of the tree contained in the directory
1414/// \param[in] fileglobs Collection of file names of filename globs
1415/// \param[in] defaultColumns Collection of default columns.
1416///
1417/// The filename globs support the same type of expressions as TChain::Add(), and each glob is passed as-is
1418/// to TChain's constructor.
1419///
1420/// The default columns are looked at in case no column is specified in the booking of actions or transformations.
1421/// \see ROOT::RDF::RInterface for the documentation of the methods available.
1422RDataFrame::RDataFrame(std::string_view treeName, const std::vector<std::string> &fileglobs,
1423 const ColumnNames_t &defaultColumns)
1424 : RInterface(std::make_shared<RDFDetail::RLoopManager>(nullptr, defaultColumns))
1425{
1426 std::string treeNameInt(treeName);
1427 auto chain = std::make_shared<TChain>(treeNameInt.c_str(), "", TChain::kWithoutGlobalRegistration);
1428 for (auto &f : fileglobs)
1429 chain->Add(f.c_str());
1430 GetProxiedPtr()->SetTree(std::move(chain));
1431}
1432
1433////////////////////////////////////////////////////////////////////////////
1434/// \brief Build the dataframe.
1435/// \param[in] tree The tree or chain to be studied.
1436/// \param[in] defaultColumns Collection of default column names to fall back to when none is specified.
1437///
1438/// The default columns are looked at in case no column is specified in the
1439/// booking of actions or transformations.
1440/// \see ROOT::RDF::RInterface for the documentation of the methods available.
1442 : RInterface(std::make_shared<RDFDetail::RLoopManager>(&tree, defaultColumns))
1443{
1444}
1445
1446//////////////////////////////////////////////////////////////////////////
1447/// \brief Build a dataframe that generates numEntries entries.
1448/// \param[in] numEntries The number of entries to generate.
1449///
1450/// An empty-source dataframe constructed with a number of entries will
1451/// generate those entries on the fly when some action is triggered,
1452/// and it will do so for all the previously-defined columns.
1453/// \see ROOT::RDF::RInterface for the documentation of the methods available.
1455 : RInterface(std::make_shared<RDFDetail::RLoopManager>(numEntries))
1456
1457{
1458}
1459
1460//////////////////////////////////////////////////////////////////////////
1461/// \brief Build dataframe associated to data source.
1462/// \param[in] ds The data source object.
1463/// \param[in] defaultColumns Collection of default column names to fall back to when none is specified.
1464///
1465/// A dataframe associated to a data source will query it to access column values.
1466/// \see ROOT::RDF::RInterface for the documentation of the methods available.
1467RDataFrame::RDataFrame(std::unique_ptr<ROOT::RDF::RDataSource> ds, const ColumnNames_t &defaultColumns)
1468 : RInterface(std::make_shared<RDFDetail::RLoopManager>(std::move(ds), defaultColumns))
1469{
1470}
1471
1472//////////////////////////////////////////////////////////////////////////
1473/// \brief Build dataframe from an RDatasetSpec object.
1474/// \param[in] spec The dataset specification object.
1475///
1476/// A dataset specification includes trees and file names,
1477/// as well as an optional friend list and/or entry range.
1478///
1479/// ### Example usage:
1480/// ~~~{.py}
1481/// spec = ROOT.RDF.Experimental.RDatasetSpec("tree", "file.root", (3, 5))
1482/// spec.AddFriend([("tree1", "a.root"), ("tree2", "b.root")], "alias")
1483/// df = ROOT.RDataFrame(spec)
1484/// ~~~
1486 : RInterface(std::make_shared<RDFDetail::RLoopManager>(std::move(spec)))
1487{
1488}
1489
1490namespace RDF {
1491namespace Experimental {
1492
1493ROOT::RDataFrame FromSpec(const std::string &jsonFile)
1494{
1495 const nlohmann::json fullData = nlohmann::json::parse(std::ifstream(jsonFile));
1496 if (!fullData.contains("samples") || fullData["samples"].size() == 0) {
1497 throw std::runtime_error(
1498 R"(The input specification does not contain any samples. Please provide the samples in the specification like:
1499{
1500 "samples": {
1501 "sampleA": {
1502 "trees": ["tree1", "tree2"],
1503 "files": ["file1.root", "file2.root"],
1504 "metadata": {"lumi": 1.0, }
1505 },
1506 "sampleB": {
1507 "trees": ["tree3", "tree4"],
1508 "files": ["file3.root", "file4.root"],
1509 "metadata": {"lumi": 0.5, }
1510 },
1511 ...
1512 },
1513})");
1514 }
1515
1516 RDatasetSpec spec;
1517 for (const auto &keyValue : fullData["samples"].items()) {
1518 const std::string &sampleName = keyValue.key();
1519 const auto &sample = keyValue.value();
1520 // TODO: if requested in https://github.com/root-project/root/issues/11624
1521 // allow union-like types for trees and files, see: https://github.com/nlohmann/json/discussions/3815
1522 if (!sample.contains("trees")) {
1523 throw std::runtime_error("A list of tree names must be provided for sample " + sampleName + ".");
1524 }
1525 std::vector<std::string> trees = sample["trees"];
1526 if (!sample.contains("files")) {
1527 throw std::runtime_error("A list of files must be provided for sample " + sampleName + ".");
1528 }
1529 std::vector<std::string> files = sample["files"];
1530 if (!sample.contains("metadata")) {
1531 spec.AddSample(RSample{sampleName, trees, files});
1532 } else {
1533 RMetaData m;
1534 for (const auto &metadata : sample["metadata"].items()) {
1535 const auto &val = metadata.value();
1536 if (val.is_string())
1537 m.Add(metadata.key(), val.get<std::string>());
1538 else if (val.is_number_integer())
1539 m.Add(metadata.key(), val.get<int>());
1540 else if (val.is_number_float())
1541 m.Add(metadata.key(), val.get<double>());
1542 else
1543 throw std::logic_error("The metadata keys can only be of type [string|int|double].");
1544 }
1545 spec.AddSample(RSample{sampleName, trees, files, m});
1546 }
1547 }
1548 if (fullData.contains("friends")) {
1549 for (const auto &friends : fullData["friends"].items()) {
1550 std::string alias = friends.key();
1551 std::vector<std::string> trees = friends.value()["trees"];
1552 std::vector<std::string> files = friends.value()["files"];
1553 if (files.size() != trees.size() && trees.size() > 1)
1554 throw std::runtime_error("Mismatch between trees and files in a friend.");
1555 spec.WithGlobalFriends(trees, files, alias);
1556 }
1557 }
1558
1559 if (fullData.contains("range")) {
1560 std::vector<int> range = fullData["range"];
1561
1562 if (range.size() == 1)
1563 spec.WithGlobalRange({range[0]});
1564 else if (range.size() == 2)
1565 spec.WithGlobalRange({range[0], range[1]});
1566 }
1567 return ROOT::RDataFrame(spec);
1568}
1569
1570} // namespace Experimental
1571} // namespace RDF
1572
1573} // namespace ROOT
1574
1575namespace cling {
1576//////////////////////////////////////////////////////////////////////////
1577/// Print an RDataFrame at the prompt
1578std::string printValue(ROOT::RDataFrame *tdf)
1579{
1580 auto &df = *tdf->GetLoopManager();
1581 auto *tree = df.GetTree();
1582 auto defCols = df.GetDefaultColumnNames();
1583
1584 std::ostringstream ret;
1585 if (tree) {
1586 ret << "A data frame built on top of the " << tree->GetName() << " dataset.";
1587 if (!defCols.empty()) {
1588 if (defCols.size() == 1)
1589 ret << "\nDefault column: " << defCols[0];
1590 else {
1591 ret << "\nDefault columns:\n";
1592 for (auto &&col : defCols) {
1593 ret << " - " << col << "\n";
1594 }
1595 }
1596 }
1597 } else if (auto ds = tdf->fDataSource) {
1598 ret << "A data frame associated to the data source \"" << cling::printValue(ds) << "\"";
1599 } else {
1600 ret << "An empty data frame that will create " << df.GetNEmptyEntries() << " entries\n";
1601 }
1602
1603 return ret.str();
1604}
1605} // namespace cling
#define f(i)
Definition RSha256.hxx:104
unsigned long long ULong64_t
Definition RtypesCore.h:81
The head node of a RDF computation graph.
A dataset specification for RDataFrame.
RDatasetSpec & WithGlobalFriends(const std::string &treeName, const std::string &fileNameGlob, const std::string &alias="")
RDatasetSpec & AddSample(RSample sample)
RDatasetSpec & WithGlobalRange(const RDatasetSpec::REntryRange &entryRange={})
Class behaving as a heterogenuous dictionary to store dataset metadata.
Definition RMetaData.hxx:29
Class representing a sample (grouping of trees (and their fileglobs) and (optional) metadata)
Definition RSample.hxx:29
RDataSource * fDataSource
Non-owning pointer to a data-source object. Null if no data-source. RLoopManager has ownership of the...
RDFDetail::RLoopManager * GetLoopManager() const
const std::shared_ptr< RDFDetail::RLoopManager > & GetProxiedPtr() const
ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree ,...
RDataFrame(std::string_view treeName, std::string_view filenameglob, const ColumnNames_t &defaultColumns={})
Build the dataframe.
ROOT::RDF::ColumnNames_t ColumnNames_t
@ kWithoutGlobalRegistration
Definition TChain.h:71
Describe directory structure in memory.
Definition TDirectory.h:45
virtual TObject * Get(const char *namecycle)
Return pointer to object identified by namecycle.
A TTree represents a columnar dataset.
Definition TTree.h:79
ROOT::RDataFrame FromSpec(const std::string &jsonFile)
Factory method to create an RDataFrame from a JSON specification file.
std::vector< std::string > ColumnNames_t
This file contains a specialised ROOT message handler to test for diagnostic in unit tests.
std::shared_ptr< const ColumnNames_t > ColumnNamesPtr_t
basic_json<> json
Definition tree.py:1
TMarker m
Definition textangle.C:8