26#include <nlohmann/json.hpp>
1501 void Exec(unsigned int slot)
1503 fPerThreadResults[slot]++;
1506 // Called at the end of the event loop.
1509 *fFinalResult = std::accumulate(fPerThreadResults.begin(), fPerThreadResults.end(), 0);
1512 // Called by RDataFrame to retrieve the name of this action.
1513 std::string GetActionName() const { return "MyCounter"; }
1517 ROOT::RDataFrame df(10);
1518 ROOT::RDF::RResultPtr<int> resultPtr = df.Book<>(MyCounter{df.GetNSlots()}, {});
1519 // The GetValue call triggers the event loop
1520 std::cout << "Number of processed entries: " << resultPtr.GetValue() << std::endl;
1524See the Book() method for more information and [this tutorial](https://root.cern/doc/master/df018__customActions_8C.html)
1525for a more complete example.
1527#### Injecting arbitrary code in the event loop with Foreach() and ForeachSlot()
1529Foreach() takes a callable (lambda expression, free function, functor...) and a list of columns and
1530executes the callable on the values of those columns for each event that passes all upstream selections.
1531It can be used to perform actions that are not already available in the interface. For example, the following snippet
1532evaluates the root mean square of column "x":
1534// Single-thread evaluation of RMS of column "x" using Foreach
1537df.Foreach([&sumSq, &n](double x) { ++n; sumSq += x*x; }, {"x"});
1538std::cout << "rms of x: " << std::sqrt(sumSq / n) << std::endl;
1540In multi-thread runs, users are responsible for the thread-safety of the expression passed to Foreach():
1541thread will execute the expression concurrently.
1542The code above would need to employ some resource protection mechanism to ensure non-concurrent writing of `rms`; but
1543this is probably too much head-scratch for such a simple operation.
1545ForeachSlot() can help in this situation. It is an alternative version of Foreach() for which the function takes an
1546additional "processing slot" parameter besides the columns it should be applied to. RDataFrame
1547guarantees that ForeachSlot() will invoke the user expression with different `slot` parameters for different concurrent
1548executions (see [Special helper columns: rdfentry_ and rdfslot_](\ref helper-cols) for more information on the slot parameter).
1549We can take advantage of ForeachSlot() to evaluate a thread-safe root mean square of column "x":
1551// Thread-safe evaluation of RMS of column "x" using ForeachSlot
1552ROOT::EnableImplicitMT();
1553const unsigned int nSlots = df.GetNSlots();
1554std::vector<double> sumSqs(nSlots, 0.);
1555std::vector<unsigned int> ns(nSlots, 0);
1557df.ForeachSlot([&sumSqs, &ns](unsigned int slot, double x) { sumSqs[slot] += x*x; ns[slot] += 1; }, {"x"});
1558double sumSq = std::accumulate(sumSqs.begin(), sumSqs.end(), 0.); // sum all squares
1559unsigned int n = std::accumulate(ns.begin(), ns.end(), 0); // sum all counts
1560std::cout << "rms of x: " << std::sqrt(sumSq / n) << std::endl;
1562Notice how we created one `double` variable for each processing slot and later merged their results via `std::accumulate`.
1566### Dataset joins with friend trees
1568Vertically concatenating multiple trees that have the same columns (creating a logical dataset with the same columns and
1569more rows) is trivial in RDataFrame: just pass the tree name and a list of file names to RDataFrame's constructor, or create a TChain
1570out of the desired trees and pass that to RDataFrame.
1572Horizontal concatenations of trees or chains (creating a logical dataset with the same number of rows and the union of the
1573columns of multiple trees) leverages TTree's "friend" mechanism.
1575Simple joins of trees that do not have the same number of rows are also possible with indexed friend trees (see below).
1577To use friend trees in RDataFrame, set up trees with the appropriate relationships and then instantiate an RDataFrame
1583main.AddFriend(&friend, "myFriend");
1586auto df2 = df.Filter("myFriend.MyCol == 42");
1589The same applies for TChains. Columns coming from the friend trees can be referred to by their full name, like in the example above,
1590or the friend tree name can be omitted in case the column name is not ambiguous (e.g. "MyCol" could be used instead of
1591"myFriend.MyCol" in the example above if there is no column "MyCol" in the main tree).
1593\note A common source of confusion is that trees that are written out from a multi-thread Snapshot() call will have their
1594 entries (block-wise) shuffled with respect to the original tree. Such trees cannot be used as friends of the original
1595 one: rows will be mismatched.
1597Indexed friend trees provide a way to perform simple joins of multiple trees over a common column.
1598When a certain entry in the main tree (or chain) is loaded, the friend trees (or chains) will then load an entry where the
1599"index" columns have a value identical to the one in the main one. For example, in Python:
1605# If a friend tree has an index on `commonColumn`, when the main tree loads
1606# a given row, it also loads the row of the friend tree that has the same
1607# value of `commonColumn`
1608aux_tree.BuildIndex("commonColumn")
1610mainTree.AddFriend(aux_tree)
1612df = ROOT.RDataFrame(mainTree)
1615RDataFrame supports indexed friend TTrees from ROOT v6.24 in single-thread mode and from v6.28/02 in multi-thread mode.
1617\anchor other-file-formats
1618### Reading data formats other than ROOT trees
1619RDataFrame can be interfaced with RDataSources. The ROOT::RDF::RDataSource interface defines an API that RDataFrame can use to read arbitrary columnar data formats.
1621RDataFrame calls into concrete RDataSource implementations to retrieve information about the data, retrieve (thread-local) readers or "cursors" for selected columns
1622and to advance the readers to the desired data entry.
1623Some predefined RDataSources are natively provided by ROOT such as the ROOT::RDF::RCsvDS which allows to read comma separated files:
1625auto tdf = ROOT::RDF::FromCSV("MuRun2010B.csv");
1626auto filteredEvents =
1627 tdf.Filter("Q1 * Q2 == -1")
1628 .Define("m", "sqrt(pow(E1 + E2, 2) - (pow(px1 + px2, 2) + pow(py1 + py2, 2) + pow(pz1 + pz2, 2)))");
1629auto h = filteredEvents.Histo1D("m");
1633See also FromNumpy (Python-only), FromRNTuple(), FromArrow(), FromSqlite().
1636### Computation graphs (storing and reusing sets of transformations)
1638As 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
1639several paths of filtering/creation of columns are executed simultaneously, and finally aggregated results are produced.
1641RDataFrame detects when several actions use the same filter or the same defined column, and **only evaluates each
1642filter or defined column once per event**, regardless of how many times that result is used down the computation graph.
1643Objects read from each column are **built once and never copied**, for maximum efficiency.
1644When "upstream" filters are not passed, subsequent filters, temporary column expressions and actions are not evaluated,
1645so it might be advisable to put the strictest filters first in the graph.
1647\anchor representgraph
1648### Visualizing the computation graph
1649It 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
1652Invoking the function ROOT::RDF::SaveGraph() on any node that is not the head node, the computation graph of the branch
1653the node belongs to is printed. By using the head node, the entire computation graph is printed.
1655Following there is an example of usage:
1657// First, a sample computational graph is built
1658ROOT::RDataFrame df("tree", "f.root");
1660auto df2 = df.Define("x", []() { return 1; })
1661 .Filter("col0 % 1 == col0")
1662 .Filter([](int b1) { return b1 <2; }, {"cut1"})
1663 .Define("y", []() { return 1; });
1665auto count = df2.Count();
1667// Prints the graph to the rd1.dot file in the current directory
1668ROOT::RDF::SaveGraph(df, "./mydot.dot");
1669// Prints the graph to standard output
1670ROOT::RDF::SaveGraph(df);
1673The 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:
1675$ dot -Tpng computation_graph.dot -ocomputation_graph.png
1678\image html RDF_Graph2.png
1681### Activating RDataFrame execution logs
1683RDataFrame has experimental support for verbose logging of the event loop runtimes and other interesting related information. It is activated as follows:
1685#include <ROOT/RLogger.hxx>
1687// this increases RDF's verbosity level as long as the `verbosity` variable is in scope
1688auto verbosity = ROOT::RLogScopedVerbosity(ROOT::Detail::RDF::RDFLogChannel(), ROOT::ELogLevel::kInfo);
1695verbosity = ROOT.RLogScopedVerbosity(ROOT.Detail.RDF.RDFLogChannel(), ROOT.ELogLevel.kInfo)
1698More information (e.g. start and end of each multi-thread task) is printed using `ELogLevel.kDebug` and even more
1699(e.g. a full dump of the generated code that RDataFrame just-in-time-compiles) using `ELogLevel.kDebug+10`.
1701\anchor rdf-from-spec
1702### Creating an RDataFrame from a dataset specification file
1704RDataFrame can be created using a dataset specification JSON file:
1709df = ROOT.RDF.Experimental.FromSpec("spec.json")
1712The input dataset specification JSON file needs to be provided by the user and it describes all necessary samples and
1713their associated metadata information. The main required key is the "samples" (at least one sample is needed) and the
1714required sub-keys for each sample are "trees" and "files". Additionally, one can specify a metadata dictionary for each
1715sample in the "metadata" key.
1717A simple example for the formatting of the specification in the JSON file is the following:
1723 "trees": ["tree1", "tree2"],
1724 "files": ["file1.root", "file2.root"],
1728 "sample_category" = "data"
1732 "trees": ["tree3", "tree4"],
1733 "files": ["file3.root", "file4.root"],
1737 "sample_category" = "MC_background"
1744The metadata information from the specification file can be then accessed using the DefinePerSample function.
1745For example, to access luminosity information (stored as a double):
1748df.DefinePerSample("lumi", 'rdfsampleinfo_.GetD("lumi")')
1751or sample_category information (stored as a string):
1754df.DefinePerSample("sample_category", 'rdfsampleinfo_.GetS("sample_category")')
1757or directly the filename:
1760df.DefinePerSample("name", "rdfsampleinfo_.GetSampleName()")
1763An example implementation of the "FromSpec" method is available in tutorial: df106_HiggstoFourLeptons.py, which also
1764provides a corresponding exemplary JSON file for the dataset specification.
1767### Adding a progress bar
1769A progress bar showing the processed event statistics can be added to any RDataFrame program.
1770The event statistics include elapsed time, currently processed file, currently processed events, the rate of event processing
1771and an estimated remaining time (per file being processed). It is recorded and printed in the terminal every m events and every
1772n seconds (by default m = 1000 and n = 1). The ProgressBar can be also added when the multithread (MT) mode is enabled.
1774ProgressBar is added after creating the dataframe object (df):
1776ROOT::RDataFrame df("tree", "file.root");
1777ROOT::RDF::Experimental::AddProgressBar(df);
1780Alternatively, RDataFrame can be cast to an RNode first, giving the user more flexibility
1781For example, it can be called at any computational node, such as Filter or Define, not only the head node,
1782with no change to the ProgressBar function itself (please see the [Python interface](classROOT_1_1RDataFrame.html#python)
1783section for appropriate usage in Python):
1785ROOT::RDataFrame df("tree", "file.root");
1786auto df_1 = ROOT::RDF::RNode(df.Filter("x>1"));
1787ROOT::RDF::Experimental::AddProgressBar(df_1);
1789Examples of implemented progress bars can be seen by running [Higgs to Four Lepton tutorial](https://root.cern/doc/master/df106__HiggsToFourLeptons_8py_source.html) and [Dimuon tutorial](https://root.cern/doc/master/df102__NanoAODDimuonAnalysis_8C.html).
1791\anchor missing-values
1792### Working with missing values in the dataset
1794In certain situations a dataset might be missing one or more values at one or
1795more of its entries. For example:
1797- If the dataset is composed of multiple files and one or more files is
1798 missing one or more columns required by the analysis.
1799- When joining different datasets horizontally according to some index value
1800 (e.g. the event number), if the index does not find a match in one or more
1801 other datasets for a certain entry.
1802- If, for a certain event, a column is invalid because it results from a Snapshot
1803 with systematic variations, and that variation didn't pass its filters. For
1804 more details, see \ref snapshot-with-variations.
1806For example, suppose that column "y" does not have a value for entry 42:
1816If the RDataFrame application reads that column, for example if a Take() action
1817was requested, the default behaviour is to throw an exception indicating
1818that that column is missing an entry.
1820The following paragraphs discuss the functionalities provided by RDataFrame to
1821work with missing values in the dataset.
1823#### FilterAvailable and FilterMissing
1825FilterAvailable and FilterMissing are specialized RDataFrame Filter operations.
1826They take as input argument the name of a column of the dataset to watch for
1827missing values. Like Filter, they will either keep or discard an entire entry
1828based on whether a condition returns true or false. Specifically:
1830- FilterAvailable: the condition is whether the value of the column is present.
1831 If so, the entry is kept. Otherwise if the value is missing the entry is
1833- FilterMissing: the condition is whether the value of the column is missing. If
1834 so, the entry is kept. Otherwise if the value is present the entry is
1838df = ROOT.RDataFrame(dataset)
1840# Anytime an entry from "col" is missing, the entire entry will be filtered out
1841df_available = df.FilterAvailable("col")
1842df_available = df_available.Define("twice", "col * 2")
1844# Conversely, if we want to select the entries for which the column has missing
1845# values, we do the following
1846df_missingcol = df.FilterMissing("col")
1847# Following operations in the same branch of the computation graph clearly
1848# cannot access that same column, since there would be no value to read
1849df_missingcol = df_missingcol.Define("observable", "othercolumn * 2")
1853ROOT::RDataFrame df{dataset};
1855// Anytime an entry from "col" is missing, the entire entry will be filtered out
1856auto df_available = df.FilterAvailable("col");
1857auto df_twicecol = df_available.Define("twice", "col * 2");
1859// Conversely, if we want to select the entries for which the column has missing
1860// values, we do the following
1861auto df_missingcol = df.FilterMissing("col");
1862// Following operations in the same branch of the computation graph clearly
1863// cannot access that same column, since there would be no value to read
1864auto df_observable = df_missingcol.Define("observable", "othercolumn * 2");
1869DefaultValueFor creates a node of the computation graph which just forwards the
1870values of the columns necessary for other downstream nodes, when they are
1871available. In case a value of the input column passed to this function is not
1872available, the node will provide the default value passed to this function call
1876df = ROOT.RDataFrame(dataset)
1877# Anytime an entry from "col" is missing, the value will be the default one
1878default_value = ... # Some sensible default value here
1879df = df.DefaultValueFor("col", default_value)
1880df = df.Define("twice", "col * 2")
1884ROOT::RDataFrame df{dataset};
1885// Anytime an entry from "col" is missing, the value will be the default one
1886constexpr auto default_value = ... // Some sensible default value here
1887auto df_default = df.DefaultValueFor("col", default_value);
1888auto df_col = df_default.Define("twice", "col * 2");
1891#### Mixing different strategies to work with missing values in the same RDataFrame
1893All the operations presented above only act on the particular branch of the
1894computation graph where they are called, so that different results can be
1895obtained by mixing and matching the filtering or providing a default value
1899df = ROOT.RDataFrame(dataset)
1900# Anytime an entry from "col" is missing, the value will be the default one
1901default_value = ... # Some sensible default value here
1902df_default = df.DefaultValueFor("col", default_value).Define("twice", "col * 2")
1903df_filtered = df.FilterAvailable("col").Define("twice", "col * 2")
1905# Same number of total entries as the input dataset, with defaulted values
1906df_default.Display(["twice"]).Print()
1907# Only keep the entries where "col" has values
1908df_filtered.Display(["twice"]).Print()
1912ROOT::RDataFrame df{dataset};
1914// Anytime an entry from "col" is missing, the value will be the default one
1915constexpr auto default_value = ... // Some sensible default value here
1916auto df_default = df.DefaultValueFor("col", default_value).Define("twice", "col * 2");
1917auto df_filtered = df.FilterAvailable("col").Define("twice", "col * 2");
1919// Same number of total entries as the input dataset, with defaulted values
1920df_default.Display({"twice"})->Print();
1921// Only keep the entries where "col" has values
1922df_filtered.Display({"twice"})->Print();
1925#### Further considerations
1927Note that working with missing values is currently supported with a TTree-based
1928data source. Support of this functionality for other data sources may come in
1931\anchor special-values
1932### Dealing with NaN or Inf values in the dataset
1934RDataFrame does not treat NaNs or infinities beyond what the floating-point standards require, i.e. they will
1935propagate to the final result.
1936Non-finite numbers can be suppressed using Filter(), e.g.:
1939df.Filter("std::isfinite(x)").Mean("x")
1942\anchor rosetta-stone
1943### Translating TTree::Draw to RDataFrame
1951 <b>ROOT::RDataFrame</b>
1957// Get the tree and Draw a histogram of x for selected y values
1958auto *tree = file->Get<TTree>("myTree");
1959tree->Draw("x", "y > 2");
1964ROOT::RDataFrame df("myTree", file);
1965df.Filter("y > 2").Histo1D("x")->Draw();
1972// Draw a histogram of "jet_eta" with the desired weight
1973tree->Draw("jet_eta", "weight*(event == 1)");
1978df.Filter("event == 1").Histo1D("jet_eta", "weight")->Draw();
1985// Draw a histogram filled with values resulting from calling a method of the class of the `event` branch in the TTree.
1986tree->Draw("event.GetNtrack()");
1992df.Define("NTrack","event.GetNtrack()").Histo1D("NTrack")->Draw();
1999// Draw only every 10th event
2000tree->Draw("fNtrack","fEvtHdr.fEvtNum%10 == 0");
2005// Use the Filter operation together with the special RDF column: `rdfentry_`
2006df.Filter("rdfentry_ % 10 == 0").Histo1D("fNtrack")->Draw();
2013// object selection: for each event, fill histogram with array of selected pts
2014tree->Draw('Muon_pt', 'Muon_pt > 100');
2019// with RDF, arrays are read as ROOT::VecOps::RVec objects
2020df.Define("good_pt", "Muon_pt[Muon_pt > 100]").Histo1D("good_pt")->Draw();
2028// Draw the histogram and fill hnew with it
2029tree->Draw("sqrt(x)>>hnew","y>0");
2031// Retrieve hnew from the current directory
2032auto hnew = gDirectory->Get<TH1F>("hnew");
2037// We pass histogram constructor arguments to the Histo1D operation, to easily give the histogram a name
2038auto hist = df.Define("sqrt_x", "sqrt(x)").Filter("y>0").Histo1D({"hnew","hnew", 10, 0, 10}, "sqrt_x");
2045// Draw a 1D Profile histogram instead of TH2F
2046tree->Draw("y:x","","prof");
2048// Draw a 2D Profile histogram instead of TH3F
2049tree->Draw("z:y:x","","prof");
2055// Draw a 1D Profile histogram
2056df.Profile1D("x", "y")->Draw();
2058// Draw a 2D Profile histogram
2059df.Profile2D("x", "y", "z")->Draw();
2066// This command draws 2 entries starting with entry 5
2067tree->Draw("x", "","", 2, 5);
2072// Range function with arguments begin, end
2073df.Range(5,7).Histo1D("x")->Draw();
2080// Draw the X() component of the
2081// ROOT::Math::DisplacementVector3D in vec_list
2082tree->Draw("vec_list.X()");
2087df.Define("x", "ROOT::RVecD out; for(const auto &el: vec_list) out.push_back(el.X()); return out;").Histo1D("x")->Draw();
2094// Gather all values from a branch holding a collection per event, `pt`,
2095// and fill a histogram so that we can count the total number of values across all events
2096tree->Draw("pt>>histo");
2097auto histo = gDirectory->Get<TH1D>("histo");
2103df.Histo1D("pt")->GetEntries();
2241namespace Experimental {
2295 auto *
lm = df->GetLoopManager();
2297 throw std::runtime_error(
"Cannot print information about this RDataFrame, "
2298 "it was not properly created. It must be discarded.");
2300 auto defCols =
lm->GetDefaultColumnNames();
2302 std::ostringstream
ret;
2303 if (
auto ds = df->GetDataSource()) {
2304 ret <<
"A data frame associated to the data source \"" << cling::printValue(
ds) <<
"\"";
2306 ret <<
"An empty data frame that will create " <<
lm->GetNEmptyEntries() <<
" entries\n";
Basic types used by ROOT and required by TInterpreter.
unsigned long long ULong64_t
Portable unsigned long integer 8 bytes.
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
The head node of a RDF computation graph.
The dataset specification for RDataFrame.
std::shared_ptr< ROOT::Detail::RDF::RLoopManager > fLoopManager
< The RLoopManager at the root of this computation graph. Never null.
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
Describe directory structure in memory.
A TTree represents a columnar dataset.
ROOT::RDF::Experimental::RDatasetSpec RetrieveSpecFromJson(const std::string &jsonFile)
Function to retrieve RDatasetSpec from JSON file provided.
ROOT::RDataFrame FromSpec(const std::string &jsonFile)
Factory method to create an RDataFrame from a JSON specification file.
std::vector< std::string > ColumnNames_t
std::shared_ptr< const ColumnNames_t > ColumnNamesPtr_t