26#include <nlohmann/json.hpp>
1502 void Exec(unsigned int slot)
1504 fPerThreadResults[slot]++;
1507 // Called at the end of the event loop.
1510 *fFinalResult = std::accumulate(fPerThreadResults.begin(), fPerThreadResults.end(), 0);
1513 // Called by RDataFrame to retrieve the name of this action.
1514 std::string GetActionName() const { return "MyCounter"; }
1518 ROOT::RDataFrame df(10);
1519 ROOT::RDF::RResultPtr<int> resultPtr = df.Book<>(MyCounter{df.GetNSlots()}, {});
1520 // The GetValue call triggers the event loop
1521 std::cout << "Number of processed entries: " << resultPtr.GetValue() << std::endl;
1525See the Book() method for more information and [this tutorial](https://root.cern/doc/master/df018__customActions_8C.html)
1526for a more complete example.
1528#### Injecting arbitrary code in the event loop with Foreach() and ForeachSlot()
1530Foreach() takes a callable (lambda expression, free function, functor...) and a list of columns and
1531executes the callable on the values of those columns for each event that passes all upstream selections.
1532It can be used to perform actions that are not already available in the interface. For example, the following snippet
1533evaluates the root mean square of column "x":
1535// Single-thread evaluation of RMS of column "x" using Foreach
1538df.Foreach([&sumSq, &n](double x) { ++n; sumSq += x*x; }, {"x"});
1539std::cout << "rms of x: " << std::sqrt(sumSq / n) << std::endl;
1541In multi-thread runs, users are responsible for the thread-safety of the expression passed to Foreach():
1542thread will execute the expression concurrently.
1543The code above would need to employ some resource protection mechanism to ensure non-concurrent writing of `rms`; but
1544this is probably too much head-scratch for such a simple operation.
1546ForeachSlot() can help in this situation. It is an alternative version of Foreach() for which the function takes an
1547additional "processing slot" parameter besides the columns it should be applied to. RDataFrame
1548guarantees that ForeachSlot() will invoke the user expression with different `slot` parameters for different concurrent
1549executions (see [Special helper columns: rdfentry_ and rdfslot_](\ref helper-cols) for more information on the slot parameter).
1550We can take advantage of ForeachSlot() to evaluate a thread-safe root mean square of column "x":
1552// Thread-safe evaluation of RMS of column "x" using ForeachSlot
1553ROOT::EnableImplicitMT();
1554const unsigned int nSlots = df.GetNSlots();
1555std::vector<double> sumSqs(nSlots, 0.);
1556std::vector<unsigned int> ns(nSlots, 0);
1558df.ForeachSlot([&sumSqs, &ns](unsigned int slot, double x) { sumSqs[slot] += x*x; ns[slot] += 1; }, {"x"});
1559double sumSq = std::accumulate(sumSqs.begin(), sumSqs.end(), 0.); // sum all squares
1560unsigned int n = std::accumulate(ns.begin(), ns.end(), 0); // sum all counts
1561std::cout << "rms of x: " << std::sqrt(sumSq / n) << std::endl;
1563Notice how we created one `double` variable for each processing slot and later merged their results via `std::accumulate`.
1567### Dataset joins with friend trees
1569Vertically concatenating multiple trees that have the same columns (creating a logical dataset with the same columns and
1570more rows) is trivial in RDataFrame: just pass the tree name and a list of file names to RDataFrame's constructor, or create a TChain
1571out of the desired trees and pass that to RDataFrame.
1573Horizontal concatenations of trees or chains (creating a logical dataset with the same number of rows and the union of the
1574columns of multiple trees) leverages TTree's "friend" mechanism.
1576Simple joins of trees that do not have the same number of rows are also possible with indexed friend trees (see below).
1578To use friend trees in RDataFrame, set up trees with the appropriate relationships and then instantiate an RDataFrame
1584main.AddFriend(&friend, "myFriend");
1587auto df2 = df.Filter("myFriend.MyCol == 42");
1590The same applies for TChains. Columns coming from the friend trees can be referred to by their full name, like in the example above,
1591or the friend tree name can be omitted in case the column name is not ambiguous (e.g. "MyCol" could be used instead of
1592"myFriend.MyCol" in the example above if there is no column "MyCol" in the main tree).
1594\note A common source of confusion is that trees that are written out from a multi-thread Snapshot() call will have their
1595 entries (block-wise) shuffled with respect to the original tree. Such trees cannot be used as friends of the original
1596 one: rows will be mismatched.
1598Indexed friend trees provide a way to perform simple joins of multiple trees over a common column.
1599When a certain entry in the main tree (or chain) is loaded, the friend trees (or chains) will then load an entry where the
1600"index" columns have a value identical to the one in the main one. For example, in Python:
1606# If a friend tree has an index on `commonColumn`, when the main tree loads
1607# a given row, it also loads the row of the friend tree that has the same
1608# value of `commonColumn`
1609aux_tree.BuildIndex("commonColumn")
1611mainTree.AddFriend(aux_tree)
1613df = ROOT.RDataFrame(mainTree)
1616RDataFrame supports indexed friend TTrees from ROOT v6.24 in single-thread mode and from v6.28/02 in multi-thread mode.
1618\anchor other-file-formats
1619### Reading data formats other than ROOT trees
1620RDataFrame can be interfaced with RDataSources. The ROOT::RDF::RDataSource interface defines an API that RDataFrame can use to read arbitrary columnar data formats.
1622RDataFrame calls into concrete RDataSource implementations to retrieve information about the data, retrieve (thread-local) readers or "cursors" for selected columns
1623and to advance the readers to the desired data entry.
1624Some predefined RDataSources are natively provided by ROOT such as the ROOT::RDF::RCsvDS which allows to read comma separated files:
1626auto tdf = ROOT::RDF::FromCSV("MuRun2010B.csv");
1627auto filteredEvents =
1628 tdf.Filter("Q1 * Q2 == -1")
1629 .Define("m", "sqrt(pow(E1 + E2, 2) - (pow(px1 + px2, 2) + pow(py1 + py2, 2) + pow(pz1 + pz2, 2)))");
1630auto h = filteredEvents.Histo1D("m");
1634See also FromNumpy (Python-only), FromRNTuple(), FromArrow(), FromSqlite().
1637### Computation graphs (storing and reusing sets of transformations)
1639As 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
1640several paths of filtering/creation of columns are executed simultaneously, and finally aggregated results are produced.
1642RDataFrame detects when several actions use the same filter or the same defined column, and **only evaluates each
1643filter or defined column once per event**, regardless of how many times that result is used down the computation graph.
1644Objects read from each column are **built once and never copied**, for maximum efficiency.
1645When "upstream" filters are not passed, subsequent filters, temporary column expressions and actions are not evaluated,
1646so it might be advisable to put the strictest filters first in the graph.
1648\anchor representgraph
1649### Visualizing the computation graph
1650It 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
1653Invoking the function ROOT::RDF::SaveGraph() on any node that is not the head node, the computation graph of the branch
1654the node belongs to is printed. By using the head node, the entire computation graph is printed.
1656Following there is an example of usage:
1658// First, a sample computational graph is built
1659ROOT::RDataFrame df("tree", "f.root");
1661auto df2 = df.Define("x", []() { return 1; })
1662 .Filter("col0 % 1 == col0")
1663 .Filter([](int b1) { return b1 <2; }, {"cut1"})
1664 .Define("y", []() { return 1; });
1666auto count = df2.Count();
1668// Prints the graph to the rd1.dot file in the current directory
1669ROOT::RDF::SaveGraph(df, "./mydot.dot");
1670// Prints the graph to standard output
1671ROOT::RDF::SaveGraph(df);
1674The 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:
1676$ dot -Tpng computation_graph.dot -ocomputation_graph.png
1679\image html RDF_Graph2.png
1682### Activating RDataFrame execution logs
1684RDataFrame has experimental support for verbose logging of the event loop runtimes and other interesting related information. It is activated as follows:
1686#include <ROOT/RLogger.hxx>
1688// this increases RDF's verbosity level as long as the `verbosity` variable is in scope
1689auto verbosity = ROOT::RLogScopedVerbosity(ROOT::Detail::RDF::RDFLogChannel(), ROOT::ELogLevel::kInfo);
1696verbosity = ROOT.RLogScopedVerbosity(ROOT.Detail.RDF.RDFLogChannel(), ROOT.ELogLevel.kInfo)
1699More information (e.g. start and end of each multi-thread task) is printed using `ELogLevel.kDebug` and even more
1700(e.g. a full dump of the generated code that RDataFrame just-in-time-compiles) using `ELogLevel.kDebug+10`.
1702\anchor rdf-from-spec
1703### Creating an RDataFrame from a dataset specification file
1705RDataFrame can be created using a dataset specification JSON file:
1710df = ROOT.RDF.Experimental.FromSpec("spec.json")
1713The input dataset specification JSON file needs to be provided by the user and it describes all necessary samples and
1714their associated metadata information. The main required key is the "samples" (at least one sample is needed) and the
1715required sub-keys for each sample are "trees" and "files". Additionally, one can specify a metadata dictionary for each
1716sample in the "metadata" key.
1718A simple example for the formatting of the specification in the JSON file is the following:
1724 "trees": ["tree1", "tree2"],
1725 "files": ["file1.root", "file2.root"],
1729 "sample_category" = "data"
1733 "trees": ["tree3", "tree4"],
1734 "files": ["file3.root", "file4.root"],
1738 "sample_category" = "MC_background"
1745The metadata information from the specification file can be then accessed using the DefinePerSample function.
1746For example, to access luminosity information (stored as a double):
1749df.DefinePerSample("lumi", 'rdfsampleinfo_.GetD("lumi")')
1752or sample_category information (stored as a string):
1755df.DefinePerSample("sample_category", 'rdfsampleinfo_.GetS("sample_category")')
1758or directly the filename:
1761df.DefinePerSample("name", "rdfsampleinfo_.GetSampleName()")
1764An example implementation of the "FromSpec" method is available in tutorial: df106_HiggstoFourLeptons.py, which also
1765provides a corresponding exemplary JSON file for the dataset specification.
1768### Adding a progress bar
1770A progress bar showing the processed event statistics can be added to any RDataFrame program.
1771The event statistics include elapsed time, currently processed file, currently processed events, the rate of event processing
1772and an estimated remaining time (per file being processed). It is recorded and printed in the terminal every m events and every
1773n seconds (by default m = 1000 and n = 1). The ProgressBar can be also added when the multithread (MT) mode is enabled.
1775ProgressBar is added after creating the dataframe object (df):
1777ROOT::RDataFrame df("tree", "file.root");
1778ROOT::RDF::Experimental::AddProgressBar(df);
1781Alternatively, RDataFrame can be cast to an RNode first, giving the user more flexibility
1782For example, it can be called at any computational node, such as Filter or Define, not only the head node,
1783with no change to the ProgressBar function itself (please see the [Python interface](classROOT_1_1RDataFrame.html#python)
1784section for appropriate usage in Python):
1786ROOT::RDataFrame df("tree", "file.root");
1787auto df_1 = ROOT::RDF::RNode(df.Filter("x>1"));
1788ROOT::RDF::Experimental::AddProgressBar(df_1);
1790Examples 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).
1792\anchor missing-values
1793### Working with missing values in the dataset
1795In certain situations a dataset might be missing one or more values at one or
1796more of its entries. For example:
1798- If the dataset is composed of multiple files and one or more files is
1799 missing one or more columns required by the analysis.
1800- When joining different datasets horizontally according to some index value
1801 (e.g. the event number), if the index does not find a match in one or more
1802 other datasets for a certain entry.
1803- If, for a certain event, a column is invalid because it results from a Snapshot
1804 with systematic variations, and that variation didn't pass its filters. For
1805 more details, see \ref snapshot-with-variations.
1807For example, suppose that column "y" does not have a value for entry 42:
1817If the RDataFrame application reads that column, for example if a Take() action
1818was requested, the default behaviour is to throw an exception indicating
1819that that column is missing an entry.
1821The following paragraphs discuss the functionalities provided by RDataFrame to
1822work with missing values in the dataset.
1824#### FilterAvailable and FilterMissing
1826FilterAvailable and FilterMissing are specialized RDataFrame Filter operations.
1827They take as input argument the name of a column of the dataset to watch for
1828missing values. Like Filter, they will either keep or discard an entire entry
1829based on whether a condition returns true or false. Specifically:
1831- FilterAvailable: the condition is whether the value of the column is present.
1832 If so, the entry is kept. Otherwise if the value is missing the entry is
1834- FilterMissing: the condition is whether the value of the column is missing. If
1835 so, the entry is kept. Otherwise if the value is present the entry is
1839df = ROOT.RDataFrame(dataset)
1841# Anytime an entry from "col" is missing, the entire entry will be filtered out
1842df_available = df.FilterAvailable("col")
1843df_available = df_available.Define("twice", "col * 2")
1845# Conversely, if we want to select the entries for which the column has missing
1846# values, we do the following
1847df_missingcol = df.FilterMissing("col")
1848# Following operations in the same branch of the computation graph clearly
1849# cannot access that same column, since there would be no value to read
1850df_missingcol = df_missingcol.Define("observable", "othercolumn * 2")
1854ROOT::RDataFrame df{dataset};
1856// Anytime an entry from "col" is missing, the entire entry will be filtered out
1857auto df_available = df.FilterAvailable("col");
1858auto df_twicecol = df_available.Define("twice", "col * 2");
1860// Conversely, if we want to select the entries for which the column has missing
1861// values, we do the following
1862auto df_missingcol = df.FilterMissing("col");
1863// Following operations in the same branch of the computation graph clearly
1864// cannot access that same column, since there would be no value to read
1865auto df_observable = df_missingcol.Define("observable", "othercolumn * 2");
1870DefaultValueFor creates a node of the computation graph which just forwards the
1871values of the columns necessary for other downstream nodes, when they are
1872available. In case a value of the input column passed to this function is not
1873available, the node will provide the default value passed to this function call
1877df = ROOT.RDataFrame(dataset)
1878# Anytime an entry from "col" is missing, the value will be the default one
1879default_value = ... # Some sensible default value here
1880df = df.DefaultValueFor("col", default_value)
1881df = df.Define("twice", "col * 2")
1885ROOT::RDataFrame df{dataset};
1886// Anytime an entry from "col" is missing, the value will be the default one
1887constexpr auto default_value = ... // Some sensible default value here
1888auto df_default = df.DefaultValueFor("col", default_value);
1889auto df_col = df_default.Define("twice", "col * 2");
1892#### Mixing different strategies to work with missing values in the same RDataFrame
1894All the operations presented above only act on the particular branch of the
1895computation graph where they are called, so that different results can be
1896obtained by mixing and matching the filtering or providing a default value
1900df = ROOT.RDataFrame(dataset)
1901# Anytime an entry from "col" is missing, the value will be the default one
1902default_value = ... # Some sensible default value here
1903df_default = df.DefaultValueFor("col", default_value).Define("twice", "col * 2")
1904df_filtered = df.FilterAvailable("col").Define("twice", "col * 2")
1906# Same number of total entries as the input dataset, with defaulted values
1907df_default.Display(["twice"]).Print()
1908# Only keep the entries where "col" has values
1909df_filtered.Display(["twice"]).Print()
1913ROOT::RDataFrame df{dataset};
1915// Anytime an entry from "col" is missing, the value will be the default one
1916constexpr auto default_value = ... // Some sensible default value here
1917auto df_default = df.DefaultValueFor("col", default_value).Define("twice", "col * 2");
1918auto df_filtered = df.FilterAvailable("col").Define("twice", "col * 2");
1920// Same number of total entries as the input dataset, with defaulted values
1921df_default.Display({"twice"})->Print();
1922// Only keep the entries where "col" has values
1923df_filtered.Display({"twice"})->Print();
1926#### Further considerations
1928Note that working with missing values is currently supported with a TTree-based
1929data source. Support of this functionality for other data sources may come in
1932\anchor special-values
1933### Dealing with NaN or Inf values in the dataset
1935RDataFrame does not treat NaNs or infinities beyond what the floating-point standards require, i.e. they will
1936propagate to the final result.
1937Non-finite numbers can be suppressed using Filter(), e.g.:
1940df.Filter("std::isfinite(x)").Mean("x")
2075namespace Experimental {
2129 auto *
lm = df->GetLoopManager();
2131 throw std::runtime_error(
"Cannot print information about this RDataFrame, "
2132 "it was not properly created. It must be discarded.");
2134 auto defCols =
lm->GetDefaultColumnNames();
2136 std::ostringstream
ret;
2137 if (
auto ds = df->GetDataSource()) {
2138 ret <<
"A data frame associated to the data source \"" << cling::printValue(
ds) <<
"\"";
2140 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