Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
CodegenContext.cxx
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 * Authors:
4 * Garima Singh, CERN 2023
5 * Jonas Rembser, CERN 2023
6 *
7 * Copyright (c) 2023, CERN
8 *
9 * Redistribution and use in source and binary forms,
10 * with or without modification, are permitted according to the terms
11 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
12 */
13
15#include <RooAbsArg.h>
16
17#include "RooFitImplHelpers.h"
18
19#include <TInterpreter.h>
20
21#include <algorithm>
22#include <cctype>
23#include <charconv>
24#include <fstream>
25#include <type_traits>
26#include <unordered_map>
27#include <unordered_set>
28
29namespace {
30
31bool startsWith(std::string_view str, std::string_view prefix)
32{
33 return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix);
34}
35
36} // namespace
37
38namespace RooFit {
39namespace Experimental {
40
41/// @brief Adds (or overwrites) the string representing the result of a node.
42/// @param key The name of the node to add the result for.
43/// @param value The new name to assign/overwrite.
44void CodegenContext::addResult(const char *key, std::string const &value)
45{
46 const TNamed *namePtr = RooNameReg::known(key);
47 if (namePtr)
48 addResult(namePtr, value);
49}
50
51void CodegenContext::addResult(TNamed const *key, std::string const &value)
52{
53 _nodeNames[key] = value;
54}
55
56/// @brief Gets the result for the given node using the node name. This node also performs the necessary
57/// code generation through recursive calls to 'translate'. A call to this function modifies the already
58/// existing code body.
59/// @param key The node to get the result string for.
60/// @return String representing the result of this node.
61std::string const &CodegenContext::getResult(RooAbsArg const &arg)
62{
63 // If the result has already been recorded, just return the result.
64 // It is usually the responsibility of each translate function to assign
65 // the proper result to its class. Hence, if a result has already been recorded
66 // for a particular node, it means the node has already been 'translate'd and we
67 // dont need to visit it again.
68 auto found = _nodeNames.find(arg.namePtr());
69 if (found != _nodeNames.end())
70 return found->second;
71
72 // The result for vector observables should already be in the map if you
73 // opened the loop scope. This is just to check if we did not request the
74 // result of a vector-valued observable outside of the scope of a loop.
75 auto foundVecObs = _vecObsIndices.find(arg.namePtr());
76 if (foundVecObs != _vecObsIndices.end()) {
77 throw std::runtime_error("You requested the result of a vector observable outside a loop scope for it!");
78 }
79
80 // Now, recursively call translate into the current argument to load the correct result.
81 codegen(const_cast<RooAbsArg &>(arg), *this);
82
83 return _nodeNames.at(arg.namePtr());
84}
85
86/// @brief Adds the given string to the string block that will be emitted at the top of the squashed function. Useful
87/// for variable declarations.
88/// @param str The string to add to the global scope.
89void CodegenContext::addToGlobalScope(std::string const &str)
90{
91 // Introduce proper indentation for multiline strings.
92 _code[0] += str;
93}
94
95/// @brief Since the squashed code represents all observables as a single flattened array, it is important
96/// to keep track of the start index for a vector valued observable which can later be expanded to access the correct
97/// element. For example, a vector valued variable x with 10 entries will be squashed to obs[start_idx + i].
98/// @param key The name of the node representing the vector valued observable.
99/// @param idx The start index (or relative position of the observable in the set of all observables).
100void CodegenContext::addVecObs(const char *key, int idx)
101{
102 const TNamed *namePtr = RooNameReg::known(key);
103 if (namePtr)
104 _vecObsIndices[namePtr] = idx;
105}
106
108{
109 auto it = _vecObsIndices.find(arg.namePtr());
110 if (it != _vecObsIndices.end()) {
111 return it->second;
112 }
113
114 return -1; // Not found
115}
116/// @brief Adds the input string to the squashed code body. If a class implements a translate function that wants to
117/// emit something to the squashed code body, it must call this function with the code it wants to emit. In case of
118/// loops, automatically determines if code needs to be stored inside or outside loop scope.
119/// @param klass The class requesting this addition, usually 'this'.
120/// @param in String to add to the squashed code.
121void CodegenContext::addToCodeBody(RooAbsArg const *klass, std::string const &in)
122{
123 // If we are in a loop and the value is scope independent, save it at the top of the loop.
124 // else, just save it in the current scope.
126}
127
128/// @brief A variation of the previous addToCodeBody that takes in a bool value that determines
129/// if input is independent. This overload exists because there might other ways to determine if
130/// a value/collection of values is scope independent.
131/// @param in String to add to the squashed code.
132/// @param isScopeIndep The value determining if the input is scope dependent.
133void CodegenContext::addToCodeBody(std::string const &in, bool isScopeIndep /* = false */)
134{
135 TString trimmed = in;
136 trimmed = trimmed.Strip(TString::kBoth);
137 // Always end the line, so that the code can't affect what is added next,
138 // like a preprocessor directive that has to start a line.
139 if (!trimmed.EndsWith("\n")) {
140 trimmed += "\n";
141 }
142
143 // If we are in a loop and the value is scope independent, save it at the top of the loop.
144 // else, just save it in the current scope.
145 if (_code.size() > 2 && isScopeIndep) {
146 _code[_code.size() - 2] += trimmed;
147 } else {
148 _code.back() += trimmed;
149 }
150}
151
152/// @brief Create a RAII scope for iterating over vector observables. You can't use the result of vector observables
153/// outside these loop scopes.
154/// @param in A pointer to the calling class, used to determine the loop dependent variables.
155std::unique_ptr<CodegenContext::LoopScope> CodegenContext::beginLoop(RooAbsArg const *in)
156{
157 pushScope();
158 unsigned loopLevel = _code.size() - 2; // subtract global + function scope.
159 std::string idx = "loopIdx" + std::to_string(loopLevel);
160
161 std::vector<TNamed const *> vars;
162
163 // Figure out which vector observables are in the server tree of "in" with
164 // a single depth-first traversal that visits each node only once. This is
165 // equivalent to calling RooAbsArg::dependsOn() for each vector observable,
166 // but much faster for large computation graphs: dependsOn() doesn't
167 // deduplicate the visited nodes, so its cost scales with the number of
168 // paths in the graph instead of the number of nodes.
169 std::unordered_set<TNamed const *> reachableVecObs;
170 {
171 std::unordered_set<RooAbsArg const *> visited;
172 std::vector<RooAbsArg const *> stack{in};
173 while (!stack.empty()) {
174 RooAbsArg const *arg = stack.back();
175 stack.pop_back();
176 if (!visited.insert(arg).second)
177 continue;
178 if (_vecObsIndices.find(arg->namePtr()) != _vecObsIndices.end())
179 reachableVecObs.insert(arg->namePtr());
180 for (RooAbsArg const *server : arg->servers())
181 stack.push_back(server);
182 }
183 }
184
185 // Set the results of the vector observables.
186 // TODO: we are using the size of the first loop variable to the the number
187 // of iterations, but it should be made sure that all loop vars are either
188 // scalar or have the same size.
189 int firstObsIdx = -1;
190 for (auto const &it : _vecObsIndices) {
191 if (reachableVecObs.find(it.first) == reachableVecObs.end())
192 continue;
193
194 vars.push_back(it.first);
195 _nodeNames[it.first] = "obs[static_cast<int>(obs[" + std::to_string(2 * it.second) + "]) + " + idx + "]";
196 if (firstObsIdx == -1) {
197 firstObsIdx = it.second;
198 }
199 }
200
201 if (firstObsIdx == -1) {
202 throw std::runtime_error("Trying to loop over variables that are not observables!");
203 }
204
205 // Make sure that the name of this variable doesn't clash with other stuff
206 addToCodeBody(in, "#pragma clad checkpoint loop\n");
207 addToCodeBody(in, "for(int " + idx + " = 0; " + idx + " < obs[" + std::to_string(2 * firstObsIdx + 1) + "]; " + idx +
208 "++) {\n");
209
210 return std::make_unique<LoopScope>(*this, std::move(vars));
211}
212
214{
215 addToCodeBody("}\n");
216
217 // clear the results of the loop variables if they were vector observables
218 for (auto const &ptr : scope.vars()) {
219 if (_vecObsIndices.find(ptr) != _vecObsIndices.end())
220 _nodeNames.erase(ptr);
221 }
222 popScope();
223}
224
225/// @brief Get a unique variable name to be used in the generated code.
227{
228 return "t" + std::to_string(_tmpVarIdx++);
229}
230
231/// @brief A function to save an expression that includes/depends on the result of the input node.
232/// @param in The node on which the valueToSave depends on/belongs to.
233/// @param valueToSave The actual string value to save as a temporary.
234void CodegenContext::addResult(RooAbsArg const *in, std::string const &valueToSave)
235{
236 addResult(in->namePtr(), saveResult(in, valueToSave));
237}
238
239/// @brief Save an expression that depends on the input node in a temporary if it is worth it.
240/// @return The name of the temporary, or the expression itself.
241std::string CodegenContext::saveResult(RooAbsArg const *in, std::string const &valueToSave)
242{
243 // std::string savedName = RooFit::Detail::makeValidVarName(in->GetName());
244 std::string savedName = getTmpVarName();
245
246 // Only save values if they contain operations or they are numerals. Otherwise, we can use them directly.
247
248 // Check if string is numeric.
249 char *end;
250 std::strtod(valueToSave.c_str(), &end);
251 bool isNumeric = (*end == '\0');
252
253 const bool hasOperations = valueToSave.find_first_of(":-+/*") != std::string::npos;
254
255 // If the name is not empty and this value is worth saving, save it to the correct scope.
256 // otherwise, just return the actual value itself
257 if (hasOperations || isNumeric) {
258 std::string outVarDecl = "const double " + savedName + " = " + valueToSave + ";\n";
259 addToCodeBody(in, outVarDecl);
260 } else {
261 savedName = valueToSave;
262 }
263
264 return savedName;
265}
266
267/// @brief Function to save a RooListProxy as an array in the squashed code.
268/// @param in The list to convert to array.
269/// @return Name of the array that stores the input list in the squashed code.
270std::string CodegenContext::buildArg(RooAbsCollection const &in, std::string const &arrayType)
271{
272 if (in.empty()) {
273 return "nullptr";
274 }
275
276 auto it = _listNames.find(in.uniqueId().value());
277 if (it != _listNames.end())
278 return it->second;
279
280 std::string savedName = getTmpVarName();
281 bool canSaveOutside = true;
282
283 std::stringstream declStrm;
284 declStrm << arrayType << " " << savedName << "[]{";
285 for (const auto arg : in) {
286 declStrm << getResult(*arg) << ",";
287 canSaveOutside = canSaveOutside && isScopeIndependent(arg);
288 }
289 declStrm.seekp(-1, declStrm.cur);
290 declStrm << "};\n";
291
292 addToCodeBody(declStrm.str(), canSaveOutside);
293
294 _listNames.insert({in.uniqueId().value(), savedName});
295 return savedName;
296}
297
298std::string CodegenContext::buildArg(std::span<const double> arr)
299{
300 std::string offset = std::to_string(_xlArr.size());
301 // No reserve() of the exact new size here: it would defeat the geometric growth of the vector, so that every call
302 // copies the whole array, which is quadratic in the number of calls for large models.
303 _xlArr.insert(_xlArr.end(), arr.begin(), arr.end());
304 return "xlArr + " + offset;
305}
306
308{
309 _code.push_back("");
310}
311
313{
314 std::string active_scope = _code.back();
315 _code.pop_back();
316 _code.back() += active_scope;
317}
318
320{
321 return !in->isReducerNode() && _dependsOnData.find(in) == _dependsOnData.end();
322}
323
324/// @brief Register a function that is only know to the interpreter to the context.
325/// This is useful to dump the standalone C++ code for the computation graph.
326void CodegenContext::collectFunction(std::string const &name)
327{
328 _collectedFunctions.emplace_back(name);
329}
330
331/// @brief Assemble and return the final code with the return expression and global statements.
332/// @param returnExpr The string representation of what the squashed function should return, usually the head node.
333/// @return The name of the declared function.
334std::string
335CodegenContext::buildFunction(RooAbsArg const &arg, std::unordered_set<RooFit::Detail::DataKey> const &dependsOnData)
336{
337 CodegenContext ctx;
338 ctx.pushScope(); // push our global scope.
341 // We only want to take over parameters and observables
342 for (auto const &item : _nodeNames) {
343 if (startsWith(item.second, "params[") || startsWith(item.second, "obs[")) {
344 ctx._nodeNames.insert(item);
345 }
346 }
347 ctx._xlArr = _xlArr;
350
351 static int iCodegen = 0;
352 auto funcName = "roo_codegen_" + std::to_string(iCodegen++);
353
354 ctx.pushScope();
355 std::string funcBody = ctx.getResult(arg);
356 ctx.popScope();
357 funcBody = ctx._code[0] + "\n return " + funcBody + ";\n";
358
359 // Declare the function
360 std::stringstream bodyWithSigStrm;
361 bodyWithSigStrm << "double " << funcName << "(double* params, double const* obs, double const* xlArr) {\n"
362 << "constexpr double inf = std::numeric_limits<double>::infinity();\n"
363 << funcBody << "\n}\n\n";
364 ctx._collectedFunctions.emplace_back(funcName);
365 ctx._collectedCode += bodyWithSigStrm.str();
366
367 _xlArr = ctx._xlArr;
370
371 return funcName;
372}
373
374void declareDispatcherCode(std::string const &funcName)
375{
376 std::string dispatcherCode = R"(
377namespace RooFit {
378namespace Experimental {
379
380template <class Arg_t, int P>
381auto FUNC_NAME(Arg_t &arg, CodegenContext &ctx, Prio<P> p)
382{
383 if constexpr (std::is_same<Prio<P>, PrioLowest>::value) {
384 return FUNC_NAME(arg, ctx);
385 } else {
386 return FUNC_NAME(arg, ctx, p.next());
387 }
388}
389
390template <class Arg_t>
391struct Caller_FUNC_NAME {
392
393 static auto call(RooAbsArg &arg, CodegenContext &ctx)
394 {
395 return FUNC_NAME(static_cast<Arg_t &>(arg), ctx, PrioHighest{});
396 }
397};
398
399} // namespace Experimental
400} // namespace RooFit
401 )";
402
403 RooFit::Detail::replaceAll(dispatcherCode, "FUNC_NAME", funcName);
404 gInterpreter->Declare(dispatcherCode.c_str());
405}
406
407namespace {
408
409/// Get the overload of the function `funcName` for the class of the given
410/// argument, as resolved by the interpreter.
411template <class Func>
412Func getDispatchedFunc(std::string const &funcName, RooAbsArg const &arg)
413{
414 // Cache the overload resolutions
415 static std::unordered_map<std::string, std::unordered_map<TClass *, Func>> dispatchMaps;
416
417 auto [entry, isNew] = dispatchMaps.try_emplace(funcName);
418 if (isNew) {
419 declareDispatcherCode(funcName);
420 }
421 auto &dispatchMap = entry->second;
422
423 TClass *tclass = arg.IsA();
424 auto found = dispatchMap.find(tclass);
425 if (found != dispatchMap.end()) {
426 return found->second;
427 }
428
429 // Can probably done with CppInterop in the future to avoid string manipulation.
430 std::stringstream cmd;
431 cmd << "&RooFit::Experimental::Caller_" << funcName << "<" << tclass->GetName() << ">::call;";
432 auto func = reinterpret_cast<Func>(gInterpreter->ProcessLine(cmd.str().c_str()));
433 dispatchMap[tclass] = func;
434 return func;
435}
436
437} // namespace
438
440{
441 getDispatchedFunc<void (*)(RooAbsArg &, CodegenContext &)>("codegenImpl", arg)(arg, ctx);
442}
443
444std::string const &CodegenContext::getLogResult(RooAbsArg const &arg)
445{
446 auto found = _logNodeNames.find(arg.namePtr());
447 if (found != _logNodeNames.end())
448 return found->second;
449
450 using Func = std::string (*)(RooAbsArg &, CodegenContext &);
451 const std::string logValue = getDispatchedFunc<Func>("codegenLogImpl", arg)(const_cast<RooAbsArg &>(arg), *this);
452 return _logNodeNames[arg.namePtr()] = saveResult(&arg, logValue);
453}
454
455} // namespace Experimental
456} // namespace RooFit
bool startsWith(std::string_view str, std::string_view prefix)
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
char name[80]
Definition TGX11.cxx:142
#define gInterpreter
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
TClass * IsA() const override
Definition RooAbsArg.h:674
const TNamed * namePtr() const
De-duplicated pointer to this object's name.
Definition RooAbsArg.h:484
const RefCountList_t & servers() const
List of all servers of this object.
Definition RooAbsArg.h:146
virtual bool isReducerNode() const
Definition RooAbsArg.h:508
Abstract container object that can hold multiple RooAbsArg objects.
RooFit::UniqueId< RooAbsCollection > const & uniqueId() const
Returns a unique ID that is different for every instantiated RooAbsCollection.
A class to manage loop scopes using the RAII technique.
std::vector< TNamed const * > const & vars() const
A class to maintain the context for squashing of RooFit models into code.
std::unordered_map< RooFit::UniqueId< RooAbsCollection >::Value_t, std::string > _listNames
A map to keep track of list names as assigned by addResult.
void addToGlobalScope(std::string const &str)
Adds the given string to the string block that will be emitted at the top of the squashed function.
std::string const & getResult(RooAbsArg const &arg)
Gets the result for the given node using the node name.
std::string getTmpVarName() const
Get a unique variable name to be used in the generated code.
void addToCodeBody(RooAbsArg const *klass, std::string const &in)
Adds the input string to the squashed code body.
std::unique_ptr< LoopScope > beginLoop(RooAbsArg const *in)
Create a RAII scope for iterating over vector observables.
void addResult(RooAbsArg const *in, std::string const &value)
A function to save an expression that includes/depends on the result of the input node.
void collectFunction(std::string const &name)
Register a function that is only know to the interpreter to the context.
void addVecObs(const char *key, int idx)
Since the squashed code represents all observables as a single flattened array, it is important to ke...
std::unordered_map< const TNamed *, int > _vecObsIndices
A map to keep track of the observable indices if they are non scalar.
int observableIndexOf(const RooAbsArg &arg) const
std::string const & getLogResult(RooAbsArg const &arg)
Like getResult(), but for the logarithm of the value.
std::unordered_map< const TNamed *, std::string > _logNodeNames
void endLoop(LoopScope const &scope)
std::unordered_set< RooFit::Detail::DataKey > _dependsOnData
Indicate whether a node depends on the dataset.
std::vector< std::string > _collectedFunctions
bool isScopeIndependent(RooAbsArg const *in) const
std::vector< std::string > _code
The code layered by lexical scopes used as a stack.
std::string buildFunction(RooAbsArg const &arg, std::unordered_set< RooFit::Detail::DataKey > const &dependsOnData={})
Assemble and return the final code with the return expression and global statements.
std::string saveResult(RooAbsArg const *in, std::string const &value)
Save an expression that depends on the input node in a temporary if it is worth it.
std::unordered_map< const TNamed *, std::string > _nodeNames
Map of node names to their result strings.
std::string buildArg(RooAbsCollection const &in, std::string const &arrayType="double")
Function to save a RooListProxy as an array in the squashed code.
int _tmpVarIdx
Index to get unique names for temporary variables.
static const TNamed * known(const char *inStr)
If the name is already known, return its TNamed pointer. Otherwise return 0 (don't register the name)...
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
Basic string class.
Definition TString.h:137
Bool_t EndsWith(const char *pat, ECaseCompare cmp=kExact) const
Return true if string ends with the specified string.
Definition TString.cxx:2325
TSubString Strip(EStripType s=kTrailing, char c=' ') const
Return a substring of self stripped at beginning and/or end.
Definition TString.cxx:1171
@ kBoth
Definition TString.h:283
void replaceAll(std::string &inOut, std::string_view what, std::string_view with)
void declareDispatcherCode(std::string const &funcName)
void codegen(RooAbsArg &arg, CodegenContext &ctx)
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:73
constexpr Value_t value() const
Return numerical value of ID.
Definition UniqueId.h:59