Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
CodeSquashContext.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_CodeSquashContext_h
15#define RooFit_Detail_CodeSquashContext_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 {
34
35namespace Experimental {
36class RooFuncWrapper;
37}
38
39namespace Detail {
40
41/// @brief A class to maintain the context for squashing of RooFit models into code.
43public:
44 CodeSquashContext(std::map<RooFit::Detail::DataKey, std::size_t> const &outputSizes, std::vector<double> &xlarr,
46
47 void addResult(RooAbsArg const *key, std::string const &value);
48 void addResult(const char *key, std::string const &value);
49
50 std::string const &getResult(RooAbsArg const &arg);
51
52 template <class T>
53 std::string const &getResult(RooTemplateProxy<T> const &key)
54 {
55 return getResult(key.arg());
56 }
57
58 /// @brief Figure out the output size of a node. It is the size of the
59 /// vector observable that it depends on, or 1 if it doesn't depend on any
60 /// or is a reducer node.
61 /// @param key The node to look up the size for.
62 std::size_t outputSize(RooFit::Detail::DataKey key) const
63 {
64 auto found = _nodeOutputSizes.find(key);
65 if (found != _nodeOutputSizes.end())
66 return found->second;
67 return 1;
68 }
69
70 void addToGlobalScope(std::string const &str);
71 std::string assembleCode(std::string const &returnExpr);
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(CodeSquashContext &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 void collectFunction(std::string const &name);
117
119
120private:
121 template <class T>
122 std::string buildArgSpanImpl(std::span<const T> arr);
123
124 bool isScopeIndependent(RooAbsArg const *in) const;
125
126 void endLoop(LoopScope const &scope);
127
128 void addResult(TNamed const *key, std::string const &value);
129
130 template <class T, typename std::enable_if<std::is_floating_point<T>{}, bool>::type = true>
131 std::string buildArg(T x)
132 {
133 return RooNumber::toString(x);
134 }
135
136 // If input is integer, we want to print it into the code like one (i.e. avoid the unnecessary '.0000').
137 template <class T, typename std::enable_if<std::is_integral<T>{}, bool>::type = true>
138 std::string buildArg(T x)
139 {
140 return std::to_string(x);
141 }
142
143 std::string buildArg(std::string const &x) { return x; }
144
145 std::string buildArg(std::nullptr_t) { return "nullptr"; }
146
147 std::string buildArg(RooAbsArg const &arg) { return getResult(arg); }
148
149 template <class T>
150 std::string buildArg(RooTemplateProxy<T> const &arg)
151 {
152 return getResult(arg);
153 }
154
155 std::string buildArgs() { return ""; }
156
157 template <class Arg_t>
158 std::string buildArgs(Arg_t const &arg)
159 {
160 return buildArg(arg);
161 }
162
163 template <typename Arg_t, typename... Args_t>
164 std::string buildArgs(Arg_t const &arg, Args_t const &...args)
165 {
166 return buildArg(arg) + ", " + buildArgs(args...);
167 }
168
169 template <class T>
170 std::string typeName() const;
171
172 /// @brief Map of node names to their result strings.
173 std::unordered_map<const TNamed *, std::string> _nodeNames;
174 /// @brief Block of code that is placed before the rest of the function body.
175 std::string _globalScope;
176 /// @brief A map to keep track of the observable indices if they are non scalar.
177 std::unordered_map<const TNamed *, int> _vecObsIndices;
178 /// @brief Map of node output sizes.
179 std::map<RooFit::Detail::DataKey, std::size_t> _nodeOutputSizes;
180 /// @brief Stores the squashed code body.
181 std::string _code;
182 /// @brief The current number of for loops the started.
183 int _loopLevel = 0;
184 /// @brief Index to get unique names for temporary variables.
185 mutable int _tmpVarIdx = 0;
186 /// @brief Keeps track of the position to go back and insert code to.
187 int _scopePtr = -1;
188 /// @brief Stores code that eventually gets injected into main code body.
189 /// Mainly used for placing decls outside of loops.
190 std::string _tempScope;
191 /// @brief A map to keep track of list names as assigned by addResult.
192 std::unordered_map<RooFit::UniqueId<RooAbsCollection>::Value_t, std::string> listNames;
193 std::vector<double> &_xlArr;
194};
195
196template <>
197inline std::string CodeSquashContext::typeName<double>() const
198{
199 return "double";
200}
201template <>
202inline std::string CodeSquashContext::typeName<int>() const
203{
204 return "int";
205}
206
207template <class T>
208std::string CodeSquashContext::buildArgSpanImpl(std::span<const T> arr)
209{
210 unsigned int n = arr.size();
211 std::string arrName = getTmpVarName();
212 std::string arrDecl = typeName<T>() + " " + arrName + "[" + std::to_string(n) + "] = {";
213 for (unsigned int i = 0; i < n; i++) {
214 arrDecl += " " + std::to_string(arr[i]) + ",";
215 }
216 arrDecl.back() = '}';
217 arrDecl += ";\n";
218 addToCodeBody(arrDecl, true);
219
220 return arrName;
221}
222
223} // namespace Detail
224
225} // namespace RooFit
226
227#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:79
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
LoopScope(CodeSquashContext &ctx, std::vector< TNamed const * > &&vars)
const std::vector< TNamed const * > _vars
A class to maintain the context for squashing of RooFit models into code.
std::string assembleCode(std::string const &returnExpr)
Assemble and return the final code with the return expression and global statements.
std::map< RooFit::Detail::DataKey, std::size_t > _nodeOutputSizes
Map of node output sizes.
std::string _tempScope
Stores code that eventually gets injected into main code body.
std::string buildCall(std::string const &funcname, Args_t const &...args)
Build the code to call the function with name funcname, passing some arguments.
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.
std::string buildArg(std::string const &x)
void endLoop(LoopScope const &scope)
std::unordered_map< const TNamed *, int > _vecObsIndices
A map to keep track of the observable indices if they are non scalar.
int _loopLevel
The current number of for loops the started.
int _tmpVarIdx
Index to get unique names for temporary variables.
std::size_t outputSize(RooFit::Detail::DataKey key) const
Figure out the output size of a node.
std::unordered_map< const TNamed *, std::string > _nodeNames
Map of node names to their result strings.
void addToCodeBody(RooAbsArg const *klass, std::string const &in)
Adds the input string to the squashed code body.
void addVecObs(const char *key, int idx)
Since the squashed code represents all observables as a single flattened array, it is important to ke...
bool isScopeIndependent(RooAbsArg const *in) const
std::string getTmpVarName() const
Get a unique variable name to be used in the generated code.
std::string const & getResult(RooTemplateProxy< T > const &key)
std::string const & getResult(RooAbsArg const &arg)
Gets the result for the given node using the node name.
std::string _code
Stores the squashed code body.
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::unordered_map< RooFit::UniqueId< RooAbsCollection >::Value_t, std::string > listNames
A map to keep track of list names as assigned by addResult.
std::string buildArgs(Arg_t const &arg, Args_t const &...args)
std::string buildArg(std::span< const int > arr)
std::string buildArg(RooAbsCollection const &x)
Function to save a RooListProxy as an array in the squashed code.
Experimental::RooFuncWrapper * _wrapper
std::string buildArgs(Arg_t const &arg)
std::string buildArgSpanImpl(std::span< const T > arr)
void collectFunction(std::string const &name)
Register a function that is only know to the interpreter to the context.
std::string buildArg(RooAbsArg const &arg)
int _scopePtr
Keeps track of the position to go back and insert code to.
std::string _globalScope
Block of code that is placed before the rest of the function body.
std::unique_ptr< LoopScope > beginLoop(RooAbsArg const *in)
Create a RAII scope for iterating over vector observables.
std::string buildArg(RooTemplateProxy< T > const &arg)
std::string buildArg(std::nullptr_t)
A wrapper class to store a C++ function of type 'double (*)(double*, double*)'.
static std::string toString(double x)
Returns an std::to_string compatible number (i.e.
Definition RooNumber.cxx:31
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
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition JSONIO.h:26