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, Experimental::RooFuncWrapper &wrapper);
45
46 void addResult(RooAbsArg const *key, std::string const &value);
47 void addResult(const char *key, std::string const &value);
48
49 std::string const &getResult(RooAbsArg const &arg);
50
51 template <class T>
52 std::string const &getResult(RooTemplateProxy<T> const &key)
53 {
54 return getResult(key.arg());
55 }
56
57 /// @brief Figure out the output size of a node. It is the size of the
58 /// vector observable that it depends on, or 1 if it doesn't depend on any
59 /// or is a reducer node.
60 /// @param key The node to look up the size for.
61 std::size_t outputSize(RooFit::Detail::DataKey key) const
62 {
63 auto found = _nodeOutputSizes.find(key);
64 if (found != _nodeOutputSizes.end())
65 return found->second;
66 return 1;
67 }
68
69 void addToGlobalScope(std::string const &str);
70 std::string assembleCode(std::string const &returnExpr);
71 void addVecObs(const char *key, int idx);
72
73 void addToCodeBody(RooAbsArg const *klass, std::string const &in);
74
75 void addToCodeBody(std::string const &in, bool isScopeIndep = false);
76
77 /// @brief Build the code to call the function with name `funcname`, passing some arguments.
78 /// The arguments can either be doubles or some RooFit arguments whose
79 /// results will be looked up in the context.
80 template <typename... Args_t>
81 std::string buildCall(std::string const &funcname, Args_t const &...args)
82 {
83 std::stringstream ss;
84 ss << funcname << "(" << buildArgs(args...) << ")";
85 return ss.str();
86 }
87
88 /// @brief A class to manage loop scopes using the RAII technique. To wrap your code around a loop,
89 /// simply place it between a brace inclosed scope with a call to beginLoop at the top. For e.g.
90 /// {
91 /// auto scope = ctx.beginLoop({<-set of vector observables to loop over->});
92 /// // your loop body code goes here.
93 /// }
94 class LoopScope {
95 public:
96 LoopScope(CodeSquashContext &ctx, std::vector<TNamed const *> &&vars) : _ctx{ctx}, _vars{vars} {}
97 ~LoopScope() { _ctx.endLoop(*this); }
98
99 std::vector<TNamed const *> const &vars() const { return _vars; }
100
101 private:
103 const std::vector<TNamed const *> _vars;
104 };
105
106 std::unique_ptr<LoopScope> beginLoop(RooAbsArg const *in);
107
108 std::string getTmpVarName() const;
109
110 std::string buildArg(RooAbsCollection const &x);
111
112 std::string buildArg(std::span<const double> arr);
113 std::string buildArg(std::span<const int> arr) { return buildArgSpanImpl(arr); }
114
116
117private:
118 template <class T>
119 std::string buildArgSpanImpl(std::span<const T> arr);
120
121 bool isScopeIndependent(RooAbsArg const *in) const;
122
123 void endLoop(LoopScope const &scope);
124
125 void addResult(TNamed const *key, std::string const &value);
126
127 template <class T, typename std::enable_if<std::is_floating_point<T>{}, bool>::type = true>
128 std::string buildArg(T x)
129 {
130 return RooNumber::toString(x);
131 }
132
133 // If input is integer, we want to print it into the code like one (i.e. avoid the unnecessary '.0000').
134 template <class T, typename std::enable_if<std::is_integral<T>{}, bool>::type = true>
135 std::string buildArg(T x)
136 {
137 return std::to_string(x);
138 }
139
140 std::string buildArg(std::string const &x) { return x; }
141
142 std::string buildArg(std::nullptr_t) { return "nullptr"; }
143
144 std::string buildArg(RooAbsArg const &arg) { return getResult(arg); }
145
146 template <class T>
147 std::string buildArg(RooTemplateProxy<T> const &arg)
148 {
149 return getResult(arg);
150 }
151
152 std::string buildArgs() { return ""; }
153
154 template <class Arg_t>
155 std::string buildArgs(Arg_t const &arg)
156 {
157 return buildArg(arg);
158 }
159
160 template <typename Arg_t, typename... Args_t>
161 std::string buildArgs(Arg_t const &arg, Args_t const &...args)
162 {
163 return buildArg(arg) + ", " + buildArgs(args...);
164 }
165
166 template <class T>
167 std::string typeName() const;
168
169 /// @brief Map of node names to their result strings.
170 std::unordered_map<const TNamed *, std::string> _nodeNames;
171 /// @brief Block of code that is placed before the rest of the function body.
172 std::string _globalScope;
173 /// @brief A map to keep track of the observable indices if they are non scalar.
174 std::unordered_map<const TNamed *, int> _vecObsIndices;
175 /// @brief Map of node output sizes.
176 std::map<RooFit::Detail::DataKey, std::size_t> _nodeOutputSizes;
177 /// @brief Stores the squashed code body.
178 std::string _code;
179 /// @brief The current number of for loops the started.
180 int _loopLevel = 0;
181 /// @brief Index to get unique names for temporary variables.
182 mutable int _tmpVarIdx = 0;
183 /// @brief Keeps track of the position to go back and insert code to.
184 int _scopePtr = -1;
185 /// @brief Stores code that eventually gets injected into main code body.
186 /// Mainly used for placing decls outside of loops.
187 std::string _tempScope;
188 /// @brief A map to keep track of list names as assigned by addResult.
189 std::unordered_map<RooFit::UniqueId<RooAbsCollection>::Value_t, std::string> listNames;
190 std::vector<double> &_xlArr;
191};
192
193template <>
194inline std::string CodeSquashContext::typeName<double>() const
195{
196 return "double";
197}
198template <>
199inline std::string CodeSquashContext::typeName<int>() const
200{
201 return "int";
202}
203
204template <class T>
205std::string CodeSquashContext::buildArgSpanImpl(std::span<const T> arr)
206{
207 unsigned int n = arr.size();
208 std::string arrName = getTmpVarName();
209 std::string arrDecl = typeName<T>() + " " + arrName + "[" + std::to_string(n) + "] = {";
210 for (unsigned int i = 0; i < n; i++) {
211 arrDecl += " " + std::to_string(arr[i]) + ",";
212 }
213 arrDecl.back() = '}';
214 arrDecl += ";\n";
215 addToCodeBody(arrDecl, true);
216
217 return arrName;
218}
219
220} // namespace Detail
221
222} // namespace RooFit
223
224#endif
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
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
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)
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
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
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition JSONIO.h:26