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
20#include <ROOT/RSpan.hxx>
21
22#include <cstddef>
23#include <iomanip>
24#include <sstream>
25#include <string>
26#include <type_traits>
27#include <unordered_map>
28#include <unordered_set>
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 void addToGlobalScope(std::string const &str);
60 void addVecObs(const char *key, int idx);
61 int observableIndexOf(const RooAbsArg &arg) const;
62
63 void addToCodeBody(RooAbsArg const *klass, std::string const &in);
64
65 void addToCodeBody(std::string const &in, bool isScopeIndep = false);
66
67 /// @brief Build the code to call the function with name `funcname`, passing some arguments.
68 /// The arguments can either be doubles or some RooFit arguments whose
69 /// results will be looked up in the context.
70 template <typename... Args_t>
71 std::string buildCall(std::string const &funcname, Args_t const &...args)
72 {
73 std::stringstream ss;
74 ss << funcname << "(" << buildArgs(args...) << ")";
75 return ss.str();
76 }
77
78 /// @brief A class to manage loop scopes using the RAII technique. To wrap your code around a loop,
79 /// simply place it between a brace inclosed scope with a call to beginLoop at the top. For e.g.
80 /// {
81 /// auto scope = ctx.beginLoop({<-set of vector observables to loop over->});
82 /// // your loop body code goes here.
83 /// }
84 class LoopScope {
85 public:
86 LoopScope(CodegenContext &ctx, std::vector<TNamed const *> &&vars) : _ctx{ctx}, _vars{vars} {}
87 ~LoopScope() { _ctx.endLoop(*this); }
88
89 std::vector<TNamed const *> const &vars() const { return _vars; }
90
91 private:
93 const std::vector<TNamed const *> _vars;
94 };
95
96 std::unique_ptr<LoopScope> beginLoop(RooAbsArg const *in);
97
98 std::string getTmpVarName() const;
99
100 std::string buildArg(RooAbsCollection const &x, std::string const &arrayType = "double");
101
102 std::string buildArg(std::span<const double> arr);
103 std::string buildArg(std::span<const int> arr) { return buildArgSpanImpl(arr); }
104
105 std::vector<double> const &xlArr() { return _xlArr; }
106
107 void collectFunction(std::string const &name);
108 std::string const &collectedCode() { return _collectedCode; }
109 std::vector<std::string> const &collectedFunctions() { return _collectedFunctions; }
110
111 auto const &dependsOnData() const { return _dependsOnData; }
112 std::string
113 buildFunction(RooAbsArg const &arg, std::unordered_set<RooFit::Detail::DataKey> const &dependsOnData = {});
114
115 struct ScopeRAII {
116 std::string _fn;
119
120 public:
121 ScopeRAII(RooAbsArg const *arg, CodegenContext &ctx);
122 ~ScopeRAII();
123 };
124 ScopeRAII OutputScopeRangeComment(RooAbsArg const *arg) { return {arg, *this}; }
125
126private:
127 void pushScope();
128 void popScope();
129 template <class T>
130 std::string buildArgSpanImpl(std::span<const T> arr);
131
132 bool isScopeIndependent(RooAbsArg const *in) const;
133
134 void endLoop(LoopScope const &scope);
135
136 void addResult(TNamed const *key, std::string const &value);
137
138 template <class T, typename std::enable_if<std::is_floating_point<T>{}, bool>::type = true>
139 std::string buildArg(T x)
140 {
141 std::stringstream ss;
142 ss << std::setprecision(std::numeric_limits<double>::max_digits10) << x;
143 return ss.str();
144 }
145
146 // If input is integer, we want to print it into the code like one (i.e. avoid the unnecessary '.0000').
147 template <class T, typename std::enable_if<std::is_integral<T>{}, bool>::type = true>
148 std::string buildArg(T x)
149 {
150 return std::to_string(x);
151 }
152
153 std::string buildArg(std::string const &x) { return x; }
154
155 std::string buildArg(std::nullptr_t) { return "nullptr"; }
156
157 std::string buildArg(RooAbsArg const &arg) { return getResult(arg); }
158
159 template <class T>
160 std::string buildArg(RooTemplateProxy<T> const &arg)
161 {
162 return getResult(arg);
163 }
164
165 std::string buildArgs() { return ""; }
166
167 template <class Arg_t>
168 std::string buildArgs(Arg_t const &arg)
169 {
170 return buildArg(arg);
171 }
172
173 template <typename Arg_t, typename... Args_t>
174 std::string buildArgs(Arg_t const &arg, Args_t const &...args)
175 {
176 return buildArg(arg) + ", " + buildArgs(args...);
177 }
178
179 template <class T>
180 std::string typeName() const;
181
182 /// @brief Map of node names to their result strings.
183 std::unordered_map<const TNamed *, std::string> _nodeNames;
184 /// @brief A map to keep track of the observable indices if they are non scalar.
185 std::unordered_map<const TNamed *, int> _vecObsIndices;
186 /// @brief Indicate whether a node depends on the dataset.
187 std::unordered_set<RooFit::Detail::DataKey> _dependsOnData;
188 /// @brief The code layered by lexical scopes used as a stack.
189 std::vector<std::string> _code;
190 /// @brief The indentation level for pretty-printing.
191 unsigned _indent = 0;
192 /// @brief Index to get unique names for temporary variables.
193 mutable int _tmpVarIdx = 0;
194 /// @brief A map to keep track of list names as assigned by addResult.
195 std::unordered_map<RooFit::UniqueId<RooAbsCollection>::Value_t, std::string> _listNames;
196 std::vector<double> _xlArr;
197 std::vector<std::string> _collectedFunctions;
198 std::string _collectedCode;
199};
200
201template <>
202inline std::string CodegenContext::typeName<double>() const
203{
204 return "double";
205}
206template <>
207inline std::string CodegenContext::typeName<int>() const
208{
209 return "int";
210}
211
212template <class T>
213std::string CodegenContext::buildArgSpanImpl(std::span<const T> arr)
214{
215 unsigned int n = arr.size();
216 std::string arrName = getTmpVarName();
217 std::stringstream ss;
218 ss << typeName<T>() << " " << arrName << "[" << n << "] = {";
219 for (unsigned int i = 0; i < n; i++) {
220 ss << " " << arr[i] << ",";
221 }
222 std::string arrDecl = ss.str();
223 arrDecl.back() = '}';
224 arrDecl += ";\n";
225 addToCodeBody(arrDecl, true);
226
227 return arrName;
228}
229
230void declareDispatcherCode(std::string const &funcName);
231
232void codegen(RooAbsArg &arg, CodegenContext &ctx);
233
234} // namespace Experimental
235} // namespace RooFit
236
237#endif
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
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:76
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.
int observableIndexOf(const RooAbsArg &arg) const
std::string buildArg(RooAbsCollection const &x, std::string const &arrayType="double")
Function to save a RooListProxy as an array in the squashed code.
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 buildArgSpanImpl(std::span< const T > arr)
unsigned _indent
The indentation level for pretty-printing.
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 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.
ScopeRAII OutputScopeRangeComment(RooAbsArg const *arg)
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)
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:67
ScopeRAII(RooAbsArg const *arg, CodegenContext &ctx)