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