Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
CodegenContext.h
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
14#ifndef RooFit_Detail_CodegenContext_h
15#define RooFit_Detail_CodegenContext_h
16
17#include <RooAbsCollection.h>
18#include <RooFit/EvalContext.h>
19#include <RooNumber.h>
20
21#include <ROOT/RSpan.hxx>
22
23#include <cstddef>
24#include <map>
25#include <sstream>
26#include <string>
27#include <type_traits>
28#include <unordered_map>
29
30template <class T>
32
33namespace RooFit {
34namespace Experimental {
35
36template <int P>
37struct Prio {
38 static_assert(P >= 1 && P <= 10, "P must be 1 <= P <= 10!");
39 static auto next() { return Prio<P + 1>{}; }
40};
41
44
45/// @brief A class to maintain the context for squashing of RooFit models into code.
47public:
48 void addResult(RooAbsArg const *key, std::string const &value);
49 void addResult(const char *key, std::string const &value);
50
51 std::string const &getResult(RooAbsArg const &arg);
52
53 template <class T>
54 std::string const &getResult(RooTemplateProxy<T> const &key)
55 {
56 return getResult(key.arg());
57 }
58
59 /// @brief Figure out the output size of a node. It is the size of the
60 /// vector observable that it depends on, or 1 if it doesn't depend on any
61 /// or is a reducer node.
62 /// @param key The node to look up the size for.
63 std::size_t outputSize(RooFit::Detail::DataKey key) const
64 {
65 auto found = _nodeOutputSizes.find(key);
66 if (found != _nodeOutputSizes.end())
67 return found->second;
68 return 1;
69 }
70
71 void addToGlobalScope(std::string const &str);
72 void addVecObs(const char *key, int idx);
73
74 void addToCodeBody(RooAbsArg const *klass, std::string const &in);
75
76 void addToCodeBody(std::string const &in, bool isScopeIndep = false);
77
78 /// @brief Build the code to call the function with name `funcname`, passing some arguments.
79 /// The arguments can either be doubles or some RooFit arguments whose
80 /// results will be looked up in the context.
81 template <typename... Args_t>
82 std::string buildCall(std::string const &funcname, Args_t const &...args)
83 {
84 std::stringstream ss;
85 ss << funcname << "(" << buildArgs(args...) << ")";
86 return ss.str();
87 }
88
89 /// @brief A class to manage loop scopes using the RAII technique. To wrap your code around a loop,
90 /// simply place it between a brace inclosed scope with a call to beginLoop at the top. For e.g.
91 /// {
92 /// auto scope = ctx.beginLoop({<-set of vector observables to loop over->});
93 /// // your loop body code goes here.
94 /// }
95 class LoopScope {
96 public:
97 LoopScope(CodegenContext &ctx, std::vector<TNamed const *> &&vars) : _ctx{ctx}, _vars{vars} {}
98 ~LoopScope() { _ctx.endLoop(*this); }
99
100 std::vector<TNamed const *> const &vars() const { return _vars; }
101
102 private:
104 const std::vector<TNamed const *> _vars;
105 };
106
107 std::unique_ptr<LoopScope> beginLoop(RooAbsArg const *in);
108
109 std::string getTmpVarName() const;
110
111 std::string buildArg(RooAbsCollection const &x);
112
113 std::string buildArg(std::span<const double> arr);
114 std::string buildArg(std::span<const int> arr) { return buildArgSpanImpl(arr); }
115
116 std::vector<double> const &xlArr() { return _xlArr; }
117
118 void collectFunction(std::string const &name);
119 std::vector<std::string> const &collectedFunctions() { return _collectedFunctions; }
120
121 std::string
122 buildFunction(RooAbsArg const &arg, std::map<RooFit::Detail::DataKey, std::size_t> const &outputSizes = {});
123
124 auto const &outputSizes() const { return _nodeOutputSizes; }
125
126 struct ScopeRAII {
127 std::string _fn;
130
131 public:
132 ScopeRAII(RooAbsArg const *arg, CodegenContext &ctx);
133 ~ScopeRAII();
134 };
135 ScopeRAII OutputScopeRangeComment(RooAbsArg const *arg) { return {arg, *this}; }
136
137private:
138 void pushScope();
139 void popScope();
140 template <class T>
141 std::string buildArgSpanImpl(std::span<const T> arr);
142
143 bool isScopeIndependent(RooAbsArg const *in) const;
144
145 void endLoop(LoopScope const &scope);
146
147 void addResult(TNamed const *key, std::string const &value);
148
149 template <class T, typename std::enable_if<std::is_floating_point<T>{}, bool>::type = true>
150 std::string buildArg(T x)
151 {
152 return RooNumber::toString(x);
153 }
154
155 // If input is integer, we want to print it into the code like one (i.e. avoid the unnecessary '.0000').
156 template <class T, typename std::enable_if<std::is_integral<T>{}, bool>::type = true>
157 std::string buildArg(T x)
158 {
159 return std::to_string(x);
160 }
161
162 std::string buildArg(std::string const &x) { return x; }
163
164 std::string buildArg(std::nullptr_t) { return "nullptr"; }
165
166 std::string buildArg(RooAbsArg const &arg) { return getResult(arg); }
167
168 template <class T>
169 std::string buildArg(RooTemplateProxy<T> const &arg)
170 {
171 return getResult(arg);
172 }
173
174 std::string buildArgs() { return ""; }
175
176 template <class Arg_t>
177 std::string buildArgs(Arg_t const &arg)
178 {
179 return buildArg(arg);
180 }
181
182 template <typename Arg_t, typename... Args_t>
183 std::string buildArgs(Arg_t const &arg, Args_t const &...args)
184 {
185 return buildArg(arg) + ", " + buildArgs(args...);
186 }
187
188 template <class T>
189 std::string typeName() const;
190
191 /// @brief Map of node names to their result strings.
192 std::unordered_map<const TNamed *, std::string> _nodeNames;
193 /// @brief A map to keep track of the observable indices if they are non scalar.
194 std::unordered_map<const TNamed *, int> _vecObsIndices;
195 /// @brief Map of node output sizes.
196 std::map<RooFit::Detail::DataKey, std::size_t> _nodeOutputSizes;
197 /// @brief The code layered by lexical scopes used as a stack.
198 std::vector<std::string> _code;
199 /// @brief The indentation level for pretty-printing.
200 unsigned _indent = 0;
201 /// @brief Index to get unique names for temporary variables.
202 mutable int _tmpVarIdx = 0;
203 /// @brief A map to keep track of list names as assigned by addResult.
204 std::unordered_map<RooFit::UniqueId<RooAbsCollection>::Value_t, std::string> _listNames;
205 std::vector<double> _xlArr;
206 std::vector<std::string> _collectedFunctions;
207};
208
209template <>
210inline std::string CodegenContext::typeName<double>() const
211{
212 return "double";
213}
214template <>
215inline std::string CodegenContext::typeName<int>() const
216{
217 return "int";
218}
219
220template <class T>
221std::string CodegenContext::buildArgSpanImpl(std::span<const T> arr)
222{
223 unsigned int n = arr.size();
224 std::string arrName = getTmpVarName();
225 std::string arrDecl = typeName<T>() + " " + arrName + "[" + std::to_string(n) + "] = {";
226 for (unsigned int i = 0; i < n; i++) {
227 arrDecl += " " + std::to_string(arr[i]) + ",";
228 }
229 arrDecl.back() = '}';
230 arrDecl += ";\n";
231 addToCodeBody(arrDecl, true);
232
233 return arrName;
234}
235
236void declareDispatcherCode(std::string const &funcName);
237
238void codegen(RooAbsArg &arg, CodegenContext &ctx);
239
240} // namespace Experimental
241} // namespace RooFit
242
243#endif
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
char name[80]
Definition TGX11.cxx:110
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
Abstract container object that can hold multiple RooAbsArg objects.
A class to manage loop scopes using the RAII technique.
std::vector< TNamed const * > const & vars() const
const std::vector< TNamed const * > _vars
LoopScope(CodegenContext &ctx, std::vector< TNamed const * > &&vars)
A class to maintain the context for squashing of RooFit models into code.
std::string buildArgs(Arg_t const &arg)
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 addResult(RooAbsArg const *key, std::string const &value)
A function to save an expression that includes/depends on the result of the input node.
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.
std::string const & getResult(RooTemplateProxy< T > const &key)
void collectFunction(std::string const &name)
Register a function that is only know to the interpreter to the context.
std::string buildArg(std::string const &x)
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.
std::map< RooFit::Detail::DataKey, std::size_t > _nodeOutputSizes
Map of node output sizes.
std::string buildFunction(RooAbsArg const &arg, std::map< RooFit::Detail::DataKey, std::size_t > const &outputSizes={})
Assemble and return the final code with the return expression and global statements.
void endLoop(LoopScope const &scope)
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 buildArgSpanImpl(std::span< const T > arr)
unsigned _indent
The indentation level for pretty-printing.
std::string buildArg(std::span< const int > arr)
std::string buildCall(std::string const &funcname, Args_t const &...args)
Build the code to call the function with name funcname, passing some arguments.
std::string buildArg(std::nullptr_t)
std::vector< std::string > const & collectedFunctions()
std::unordered_map< const TNamed *, std::string > _nodeNames
Map of node names to their result strings.
std::size_t outputSize(RooFit::Detail::DataKey key) const
Figure out the output size of a node.
ScopeRAII OutputScopeRangeComment(RooAbsArg const *arg)
std::string buildArg(RooAbsCollection const &x)
Function to save a RooListProxy as an array in the squashed code.
std::string buildArg(RooTemplateProxy< T > const &arg)
int _tmpVarIdx
Index to get unique names for temporary variables.
std::vector< double > const & xlArr()
std::string buildArg(RooAbsArg const &arg)
std::string buildArgs(Arg_t const &arg, Args_t const &...args)
static std::string toString(double x)
Returns an std::to_string compatible number (i.e.
Definition RooNumber.cxx:31
const T & arg() const
Return reference to object held in proxy.
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
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:64