26#include <unordered_map>
27#include <unordered_set>
31bool startsWith(std::string_view str, std::string_view prefix)
33 return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix);
39namespace Experimental {
77 throw std::runtime_error(
"You requested the result of a vector observable outside a loop scope for it!");
145 if (
_code.size() > 2 && isScopeIndep) {
148 _code.back() += trimmed;
158 unsigned loopLevel =
_code.size() - 2;
159 std::string idx =
"loopIdx" + std::to_string(loopLevel);
161 std::vector<TNamed const *> vars;
169 std::unordered_set<TNamed const *> reachableVecObs;
171 std::unordered_set<RooAbsArg const *> visited;
172 std::vector<RooAbsArg const *> stack{in};
173 while (!stack.empty()) {
176 if (!visited.insert(arg).second)
179 reachableVecObs.insert(arg->
namePtr());
181 stack.push_back(server);
189 int firstObsIdx = -1;
191 if (reachableVecObs.find(it.first) == reachableVecObs.end())
194 vars.push_back(it.first);
195 _nodeNames[it.first] =
"obs[static_cast<int>(obs[" + std::to_string(2 * it.second) +
"]) + " + idx +
"]";
196 if (firstObsIdx == -1) {
197 firstObsIdx = it.second;
201 if (firstObsIdx == -1) {
202 throw std::runtime_error(
"Trying to loop over variables that are not observables!");
207 addToCodeBody(in,
"for(int " + idx +
" = 0; " + idx +
" < obs[" + std::to_string(2 * firstObsIdx + 1) +
"]; " + idx +
210 return std::make_unique<LoopScope>(*
this, std::move(vars));
218 for (
auto const &ptr : scope.
vars()) {
250 std::strtod(valueToSave.c_str(), &end);
251 bool isNumeric = (*end ==
'\0');
253 const bool hasOperations = valueToSave.find_first_of(
":-+/*") != std::string::npos;
257 if (hasOperations || isNumeric) {
258 std::string outVarDecl =
"const double " + savedName +
" = " + valueToSave +
";\n";
261 savedName = valueToSave;
281 bool canSaveOutside =
true;
283 std::stringstream declStrm;
284 declStrm << arrayType <<
" " << savedName <<
"[]{";
285 for (
const auto arg : in) {
289 declStrm.seekp(-1, declStrm.cur);
304 return "xlArr + " +
offset;
314 std::string active_scope =
_code.back();
316 _code.back() += active_scope;
351 static int iCodegen = 0;
352 auto funcName =
"roo_codegen_" + std::to_string(iCodegen++);
355 std::string funcBody = ctx.
getResult(arg);
357 funcBody = ctx.
_code[0] +
"\n return " + funcBody +
";\n";
360 std::stringstream bodyWithSigStrm;
361 bodyWithSigStrm <<
"double " << funcName <<
"(double* params, double const* obs, double const* xlArr) {\n"
362 <<
"constexpr double inf = std::numeric_limits<double>::infinity();\n"
363 << funcBody <<
"\n}\n\n";
376 std::string dispatcherCode = R
"(
378namespace Experimental {
380template <class Arg_t, int P>
381auto FUNC_NAME(Arg_t &arg, CodegenContext &ctx, Prio<P> p)
383 if constexpr (std::is_same<Prio<P>, PrioLowest>::value) {
384 return FUNC_NAME(arg, ctx);
386 return FUNC_NAME(arg, ctx, p.next());
390template <class Arg_t>
391struct Caller_FUNC_NAME {
393 static auto call(RooAbsArg &arg, CodegenContext &ctx)
395 return FUNC_NAME(static_cast<Arg_t &>(arg), ctx, PrioHighest{});
399} // namespace Experimental
412Func getDispatchedFunc(std::string
const &funcName,
RooAbsArg const &arg)
415 static std::unordered_map<std::string, std::unordered_map<TClass *, Func>> dispatchMaps;
417 auto [entry, isNew] = dispatchMaps.try_emplace(funcName);
421 auto &dispatchMap = entry->second;
424 auto found = dispatchMap.find(tclass);
425 if (found != dispatchMap.end()) {
426 return found->second;
430 std::stringstream cmd;
431 cmd <<
"&RooFit::Experimental::Caller_" << funcName <<
"<" << tclass->
GetName() <<
">::call;";
432 auto func =
reinterpret_cast<Func
>(
gInterpreter->ProcessLine(cmd.str().c_str()));
433 dispatchMap[tclass] = func;
441 getDispatchedFunc<void (*)(RooAbsArg &, CodegenContext &)>(
"codegenImpl", arg)(arg, ctx);
448 return found->second;
451 const std::string logValue = getDispatchedFunc<Func>(
"codegenLogImpl", arg)(
const_cast<RooAbsArg &
>(arg), *
this);
bool startsWith(std::string_view str, std::string_view prefix)
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
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.
TClass * IsA() const override
const TNamed * namePtr() const
De-duplicated pointer to this object's name.
const RefCountList_t & servers() const
List of all servers of this object.
virtual bool isReducerNode() const
Abstract container object that can hold multiple RooAbsArg objects.
RooFit::UniqueId< RooAbsCollection > const & uniqueId() const
Returns a unique ID that is different for every instantiated RooAbsCollection.
A class to manage loop scopes using the RAII technique.
std::vector< TNamed const * > const & vars() const
A class to maintain the context for squashing of RooFit models into code.
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 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.
void addResult(RooAbsArg const *in, std::string const &value)
A function to save an expression that includes/depends on the result of the input node.
void collectFunction(std::string const &name)
Register a function that is only know to the interpreter to the context.
std::vector< double > _xlArr
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 const & getLogResult(RooAbsArg const &arg)
Like getResult(), but for the logarithm of the value.
std::unordered_map< const TNamed *, std::string > _logNodeNames
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
std::string _collectedCode
bool isScopeIndependent(RooAbsArg const *in) const
std::vector< std::string > _code
The code layered by lexical scopes used as a stack.
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 saveResult(RooAbsArg const *in, std::string const &value)
Save an expression that depends on the input node in a temporary if it is worth it.
std::unordered_map< const TNamed *, std::string > _nodeNames
Map of node names to their result strings.
auto const & dependsOnData() const
std::string buildArg(RooAbsCollection const &in, std::string const &arrayType="double")
Function to save a RooListProxy as an array in the squashed code.
int _tmpVarIdx
Index to get unique names for temporary variables.
static const TNamed * known(const char *inStr)
If the name is already known, return its TNamed pointer. Otherwise return 0 (don't register the name)...
TClass instances represent classes, structs and namespaces in the ROOT type system.
The TNamed class is the base class for all named ROOT classes.
const char * GetName() const override
Returns name of object.
Bool_t EndsWith(const char *pat, ECaseCompare cmp=kExact) const
Return true if string ends with the specified string.
TSubString Strip(EStripType s=kTrailing, char c=' ') const
Return a substring of self stripped at beginning and/or end.
void replaceAll(std::string &inOut, std::string_view what, std::string_view with)
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...
constexpr Value_t value() const
Return numerical value of ID.