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