Logo ROOT  
Reference Guide
RDFUtils.cxx
Go to the documentation of this file.
1// Author: Enrico Guiraud, Danilo Piparo CERN 03/2017
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 "RConfigure.h" // R__USE_IMT
12#include "ROOT/RDataSource.hxx"
14#include "RtypesCore.h"
15#include "TBranch.h"
16#include "TBranchElement.h"
17#include "TClass.h"
18#include "TClassEdit.h"
19#include "TClassRef.h"
20#include "TInterpreter.h"
21#include "TLeaf.h"
22#include "TObjArray.h"
23#include "TROOT.h" // IsImplicitMTEnabled, GetImplicitMTPoolSize
24#include "TTree.h"
25
26#include <stdexcept>
27#include <string>
28#include <typeinfo>
29
30using namespace ROOT::Detail::RDF;
31using namespace ROOT::RDF;
32
33namespace ROOT {
34namespace Internal {
35namespace RDF {
36
37/// Return the type_info associated to a name. If the association fails, an
38/// exception is thrown.
39/// References and pointers are not supported since those cannot be stored in
40/// columns.
41const std::type_info &TypeName2TypeID(const std::string &name)
42{
43 if (auto c = TClass::GetClass(name.c_str())) {
44 return *c->GetTypeInfo();
45 } else if (name == "char" || name == "Char_t")
46 return typeid(char);
47 else if (name == "unsigned char" || name == "UChar_t")
48 return typeid(unsigned char);
49 else if (name == "int" || name == "Int_t")
50 return typeid(int);
51 else if (name == "unsigned int" || name == "UInt_t")
52 return typeid(unsigned int);
53 else if (name == "short" || name == "Short_t")
54 return typeid(short);
55 else if (name == "unsigned short" || name == "UShort_t")
56 return typeid(unsigned short);
57 else if (name == "long" || name == "Long_t")
58 return typeid(long);
59 else if (name == "unsigned long" || name == "ULong_t")
60 return typeid(unsigned long);
61 else if (name == "double" || name == "Double_t")
62 return typeid(double);
63 else if (name == "float" || name == "Float_t")
64 return typeid(float);
65 else if (name == "long long" || name == "long long int" || name == "Long64_t")
66 return typeid(Long64_t);
67 else if (name == "unsigned long long" || name == "unsigned long long int" || name == "ULong64_t")
68 return typeid(ULong64_t);
69 else if (name == "bool" || name == "Bool_t")
70 return typeid(bool);
71 else {
72 std::string msg("Cannot extract type_info of type ");
73 msg += name.c_str();
74 msg += ".";
75 throw std::runtime_error(msg);
76 }
77}
78
79/// Returns the name of a type starting from its type_info
80/// An empty string is returned in case of failure
81/// References and pointers are not supported since those cannot be stored in
82/// columns.
83std::string TypeID2TypeName(const std::type_info &id)
84{
85 if (auto c = TClass::GetClass(id)) {
86 return c->GetName();
87 } else if (id == typeid(char))
88 return "char";
89 else if (id == typeid(unsigned char))
90 return "unsigned char";
91 else if (id == typeid(int))
92 return "int";
93 else if (id == typeid(unsigned int))
94 return "unsigned int";
95 else if (id == typeid(short))
96 return "short";
97 else if (id == typeid(unsigned short))
98 return "unsigned short";
99 else if (id == typeid(long))
100 return "long";
101 else if (id == typeid(unsigned long))
102 return "unsigned long";
103 else if (id == typeid(double))
104 return "double";
105 else if (id == typeid(float))
106 return "float";
107 else if (id == typeid(Long64_t))
108 return "Long64_t";
109 else if (id == typeid(ULong64_t))
110 return "ULong64_t";
111 else if (id == typeid(bool))
112 return "bool";
113 else
114 return "";
115}
116
117std::string ComposeRVecTypeName(const std::string &valueType)
118{
119 return "ROOT::VecOps::RVec<" + valueType + ">";
120}
121
122std::string GetLeafTypeName(TLeaf *leaf, const std::string &colName)
123{
124 std::string colType = leaf->GetTypeName();
125 if (colType.empty())
126 throw std::runtime_error("Could not deduce type of leaf " + colName);
127 if (leaf->GetLeafCount() != nullptr && leaf->GetLenStatic() == 1) {
128 // this is a variable-sized array
129 colType = ComposeRVecTypeName(colType);
130 } else if (leaf->GetLeafCount() == nullptr && leaf->GetLenStatic() > 1) {
131 // this is a fixed-sized array (we do not differentiate between variable- and fixed-sized arrays)
132 colType = ComposeRVecTypeName(colType);
133 } else if (leaf->GetLeafCount() != nullptr && leaf->GetLenStatic() > 1) {
134 // we do not know how to deal with this branch
135 throw std::runtime_error("TTree leaf " + colName +
136 " has both a leaf count and a static length. This is not supported.");
137 }
138
139 return colType;
140}
141
142/// Return the typename of object colName stored in t, if any. Return an empty string if colName is not in t.
143/// Supported cases:
144/// - leaves corresponding to single values, variable- and fixed-length arrays, with following syntax:
145/// - "leafname", as long as TTree::GetLeaf resolves it
146/// - "b1.b2...leafname", as long as TTree::GetLeaf("b1.b2....", "leafname") resolves it
147/// - TBranchElements, as long as TTree::GetBranch resolves their names
148std::string GetBranchOrLeafTypeName(TTree &t, const std::string &colName)
149{
150 // look for TLeaf either with GetLeaf(colName) or with GetLeaf(branchName, leafName) (splitting on last dot)
151 auto leaf = t.GetLeaf(colName.c_str());
152 if (!leaf) {
153 const auto dotPos = colName.find_last_of('.');
154 const auto hasDot = dotPos != std::string::npos;
155 if (hasDot) {
156 const auto branchName = colName.substr(0, dotPos);
157 const auto leafName = colName.substr(dotPos + 1);
158 leaf = t.GetLeaf(branchName.c_str(), leafName.c_str());
159
160 // FIXME GetLeaf("a.b") and GetLeaf("a", "b") might fail while GetBranch("a.b") might work, even if a leaf
161 // called "a.b" exists. If that's the case, however, we don't want branch->GetCurrentClass()->GetName() as the
162 // type, because GetCurrentClass() returns the type of the top-level branch.
163 // So as a last resort, let's check if we manage to get to the leaf from the TBranch.
164 // To be revised once the TLeaf part of ROOT-10942 is fixed (see the ticket for more context).
165 auto branch = t.GetBranch(colName.c_str());
166 if (branch) {
167 auto leaves = branch->GetListOfLeaves();
168 if (leaves->GetEntries() == 1 && branch->GetListOfBranches()->GetEntries() == 0 &&
169 static_cast<TLeaf *>(leaves->At(0))->GetFullName() == colName)
170 return GetLeafTypeName(static_cast<TLeaf *>(leaves->At(0)), colName);
171 }
172 }
173 }
174 if (leaf)
175 return GetLeafTypeName(leaf, colName);
176
177 // we could not find a leaf named colName, so we look for a TBranchElement
178 auto branch = t.GetBranch(colName.c_str());
179 if (branch) {
180 static const TClassRef tbranchelement("TBranchElement");
181 if (branch->InheritsFrom(tbranchelement)) {
182 auto be = static_cast<TBranchElement *>(branch);
183 if (auto currentClass = be->GetCurrentClass())
184 return currentClass->GetName();
185 else {
186 // Here we have a special case for getting right the type of data members
187 // of classes sorted in TClonesArrays: ROOT-9674
188 auto mother = be->GetMother();
189 if (mother && mother->InheritsFrom(tbranchelement) && mother != be) {
190 auto beMom = static_cast<TBranchElement *>(mother);
191 auto beMomClass = beMom->GetClass();
192 if (beMomClass && 0 == strcmp("TClonesArray", beMomClass->GetName()))
193 return be->GetTypeName();
194 }
195 return be->GetClassName();
196 }
197 }
198 }
199
200 // colName is not a leaf nor a TBranchElement
201 return std::string();
202}
203
204/// Return a string containing the type of the given branch. Works both with real TTree branches and with temporary
205/// column created by Define. Throws if type name deduction fails.
206/// Note that for fixed- or variable-sized c-style arrays the returned type name will be RVec<T>.
207/// vector2rvec specifies whether typename 'std::vector<T>' should be converted to 'RVec<T>' or returned as is
208/// customColID is only used if isCustomColumn is true, and must correspond to the custom column's unique identifier
209/// returned by its `GetID()` method.
210std::string ColumnName2ColumnTypeName(const std::string &colName, unsigned int namespaceID, TTree *tree,
211 RDataSource *ds, bool isCustomColumn, bool vector2rvec, unsigned int customColID)
212{
213 std::string colType;
214
215 if (ds && ds->HasColumn(colName))
216 colType = ds->GetTypeName(colName);
217
218 if (colType.empty() && tree) {
219 colType = GetBranchOrLeafTypeName(*tree, colName);
220 if (vector2rvec && TClassEdit::IsSTLCont(colType) == ROOT::ESTLType::kSTLvector) {
221 std::vector<std::string> split;
222 int dummy;
223 TClassEdit::GetSplit(colType.c_str(), split, dummy);
224 auto &valueType = split[1];
225 colType = ComposeRVecTypeName(valueType);
226 }
227 }
228
229 if (colType.empty() && isCustomColumn) {
230 // this must be a temporary branch, we know there is an alias for its type
231 colType = "__rdf" + std::to_string(namespaceID) + "::" + colName + std::to_string(customColID) + "_type";
232 }
233
234 if (colType.empty())
235 throw std::runtime_error("Column \"" + colName +
236 "\" is not in a dataset and is not a custom column been defined.");
237
238 return colType;
239}
240
241/// Convert type name (e.g. "Float_t") to ROOT type code (e.g. 'F') -- see TBranch documentation.
242/// Return a space ' ' in case no match was found.
243char TypeName2ROOTTypeName(const std::string &b)
244{
245 if (b == "Char_t" || b == "char")
246 return 'B';
247 if (b == "UChar_t" || b == "unsigned char")
248 return 'b';
249 if (b == "Short_t" || b == "short" || b == "short int")
250 return 'S';
251 if (b == "UShort_t" || b == "unsigned short" || b == "unsigned short int")
252 return 's';
253 if (b == "Int_t" || b == "int")
254 return 'I';
255 if (b == "UInt_t" || b == "unsigned" || b == "unsigned int")
256 return 'i';
257 if (b == "Float_t" || b == "float")
258 return 'F';
259 if (b == "Double_t" || b == "double")
260 return 'D';
261 if (b == "Long64_t" || b == "long" || b == "long int")
262 return 'L';
263 if (b == "ULong64_t" || b == "unsigned long" || b == "unsigned long int")
264 return 'l';
265 if (b == "Bool_t" || b == "bool")
266 return 'O';
267 return ' ';
268}
269
270unsigned int GetNSlots()
271{
272 unsigned int nSlots = 1;
273#ifdef R__USE_IMT
276#endif // R__USE_IMT
277 return nSlots;
278}
279
280/// Replace occurrences of '.' with '_' in each string passed as argument.
281/// An Info message is printed when this happens. Dots at the end of the string are not replaced.
282/// An exception is thrown in case the resulting set of strings would contain duplicates.
283std::vector<std::string> ReplaceDotWithUnderscore(const std::vector<std::string> &columnNames)
284{
285 auto newColNames = columnNames;
286 for (auto &col : newColNames) {
287 const auto dotPos = col.find('.');
288 if (dotPos != std::string::npos && dotPos != col.size() - 1 && dotPos != 0u) {
289 auto oldName = col;
290 std::replace(col.begin(), col.end(), '.', '_');
291 if (std::find(columnNames.begin(), columnNames.end(), col) != columnNames.end())
292 throw std::runtime_error("Column " + oldName + " would be written as " + col +
293 " but this column already exists. Please use Alias to select a new name for " +
294 oldName);
295 Info("Snapshot", "Column %s will be saved as %s", oldName.c_str(), col.c_str());
296 }
297 }
298
299 return newColNames;
300}
301
302void InterpreterDeclare(const std::string &code)
303{
304 if (!gInterpreter->Declare(code.c_str())) {
305 const auto msg = "\nAn error occurred while jitting. The lines above might indicate the cause of the crash\n";
306 throw std::runtime_error(msg);
307 }
308}
309
310Long64_t InterpreterCalc(const std::string &code, const std::string &context)
311{
313 auto res = gInterpreter->Calc(code.c_str(), &errorCode);
314 if (errorCode != TInterpreter::EErrorCode::kNoError) {
315 std::string msg = "\nAn error occurred while jitting";
316 if (!context.empty())
317 msg += " in " + context;
318 msg += ". The lines above might indicate the cause of the crash\n";
319 throw std::runtime_error(msg);
320 }
321 return res;
322}
323
324} // end NS RDF
325} // end NS Internal
326} // end NS ROOT
#define b(i)
Definition: RSha256.hxx:100
#define c(i)
Definition: RSha256.hxx:101
static RooMathCoreReg dummy
long long Long64_t
Definition: RtypesCore.h:69
unsigned long long ULong64_t
Definition: RtypesCore.h:70
void Info(const char *location, const char *msgfmt,...)
char name[80]
Definition: TGX11.cxx:109
#define gInterpreter
Definition: TInterpreter.h:555
RDataSource defines an API that RDataFrame can use to read arbitrary data formats.
virtual bool HasColumn(std::string_view) const =0
Checks if the dataset has a certain column.
virtual std::string GetTypeName(std::string_view) const =0
Type of a column as a string, e.g.
A Branch for the case of an object.
virtual TClass * GetClass() const
TObjArray * GetListOfLeaves()
Definition: TBranch.h:245
TClassRef is used to implement a permanent reference to a TClass object.
Definition: TClassRef.h:29
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition: TClass.cxx:2906
A TLeaf describes individual elements of a TBranch See TBranch structure in TTree.
Definition: TLeaf.h:49
virtual const char * GetTypeName() const
Definition: TLeaf.h:130
virtual TLeaf * GetLeafCount() const
If this leaf stores a variable-sized array or a multi-dimensional array whose last dimension has vari...
Definition: TLeaf.h:112
virtual TString GetFullName() const
Return the full name (including the parent's branch names) of the leaf.
Definition: TLeaf.cxx:199
virtual Int_t GetLenStatic() const
Return the fixed length of this leaf.
Definition: TLeaf.h:123
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
A TTree represents a columnar dataset.
Definition: TTree.h:72
virtual TBranch * GetBranch(const char *name)
Return pointer to the branch with the given name in this tree or its friends.
Definition: TTree.cxx:5170
virtual TLeaf * GetLeaf(const char *branchname, const char *leafname)
Return pointer to the 1st Leaf named name in any Branch of this Tree or any branch in the list of fri...
Definition: TTree.cxx:6051
std::vector< std::string > ReplaceDotWithUnderscore(const std::vector< std::string > &columnNames)
Replace occurrences of '.
Definition: RDFUtils.cxx:283
const std::type_info & TypeName2TypeID(const std::string &name)
Return the type_info associated to a name.
Definition: RDFUtils.cxx:41
unsigned int GetNSlots()
Definition: RDFUtils.cxx:270
std::string ComposeRVecTypeName(const std::string &valueType)
Definition: RDFUtils.cxx:117
std::string GetLeafTypeName(TLeaf *leaf, const std::string &colName)
Definition: RDFUtils.cxx:122
char TypeName2ROOTTypeName(const std::string &b)
Convert type name (e.g.
Definition: RDFUtils.cxx:243
std::string TypeID2TypeName(const std::type_info &id)
Returns the name of a type starting from its type_info An empty string is returned in case of failure...
Definition: RDFUtils.cxx:83
std::string GetBranchOrLeafTypeName(TTree &t, const std::string &colName)
Return the typename of object colName stored in t, if any.
Definition: RDFUtils.cxx:148
Long64_t InterpreterCalc(const std::string &code, const std::string &context)
Definition: RDFUtils.cxx:310
std::string ColumnName2ColumnTypeName(const std::string &colName, unsigned int namespaceID, TTree *tree, RDataSource *ds, bool isCustomColumn, bool vector2rvec, unsigned int customColID)
Return a string containing the type of the given branch.
Definition: RDFUtils.cxx:210
void InterpreterDeclare(const std::string &code)
Definition: RDFUtils.cxx:302
VSD Structures.
Definition: StringConv.hxx:21
Bool_t IsImplicitMTEnabled()
Returns true if the implicit multi-threading in ROOT is enabled.
Definition: TROOT.cxx:611
@ kSTLvector
Definition: ESTLType.h:30
UInt_t GetImplicitMTPoolSize()
Returns the size of the pool used for implicit multi-threading.
Definition: TROOT.cxx:618
ROOT::ESTLType IsSTLCont(std::string_view type)
type : type name: vector<list<classA,allocator>,allocator> result: 0 : not stl container code of cont...
int GetSplit(const char *type, std::vector< std::string > &output, int &nestedLoc, EModType mode=TClassEdit::kNone)
Stores in output (after emptying it) the split type.
Definition: TClassEdit.cxx:995
Definition: tree.py:1