44 :
RooAbsReal{
"RooEvaluatorWrapper",
"RooEvaluatorWrapper"},
48 _paramSet(
"paramSet",
"Set of parameters",
this),
54 setData(*
data,
false);
56 _paramSet.add(_evaluator->getParameters());
58 _paramSet.remove(*_paramSet.find(
item.first->GetName()));
64 _evaluator{
other._evaluator},
65 _topNode(
"topNode",
this,
other._topNode),
67 _paramSet(
"paramSet",
"Set of parameters",
this),
68 _rangeName{
other._rangeName},
70 _takeGlobalObservablesFromData{
other._takeGlobalObservablesFromData},
73 _paramSet.add(
other._paramSet);
76RooEvaluatorWrapper::~RooEvaluatorWrapper() =
default;
81 outputSet.add(_evaluator->getParameters());
83 outputSet.remove(*observables,
false,
true);
87 if (_data->getGlobalObservables() && _data->getGlobalObservables()->find(
item.first->GetName())) {
99 if (_takeGlobalObservablesFromData && _data->getGlobalObservables()) {
100 outputSet.replace(*_data->getGlobalObservables());
131 void gradient(
double *out)
const
134 std::fill(out, out + _params.size(), 0.0);
143 std::vector<std::string>
const &collectedFunctions() {
return _collectedFunctions; }
158 using Func =
double (*)(
double *,
double const *,
double const *);
159 using Grad = void (*)(
double *,
double const *,
double const *,
double *);
167 std::vector<double> _observables;
168 std::unordered_map<RooFit::Detail::DataKey, std::size_t>
_obsInfos;
169 std::vector<double> _xlArr;
170 std::vector<std::string> _collectedFunctions;
175void replaceAll(std::string &str,
const std::string &from,
const std::string &to)
181 str.replace(
start_pos, from.length(), to);
191 std::unordered_set<RooFit::Detail::DataKey> dependsOnData;
193 dependsOnData.insert(arg);
197 if (arg->getAttribute(
"__obs__")) {
198 dependsOnData.insert(arg);
201 if (
server->isValueServer(*arg)) {
202 if (dependsOnData.find(
server) != dependsOnData.end() && !arg->isReducerNode()) {
203 dependsOnData.insert(arg);
210 return dependsOnData;
232 std::unordered_set<RooFit::Detail::DataKey> dependsOnData;
243 ctx.
addResult(param,
"params[" + std::to_string(idx) +
"]");
254 auto print = [](std::string
const &
msg) {
oocoutI(
nullptr, Fitting) <<
msg << std::endl; };
259 gInterpreter->Declare(
"#include <RooFit/CodegenImpl.h>\n");
264 errorMsg <<
"Function " <<
_funcName <<
" could not be compiled. See above for details. Full code dumped to file "
272 throw std::runtime_error(
errorMsg.str().c_str());
277 _xlArr = ctx.
xlArr();
287 _observables.clear();
289 std::size_t
total = 0;
290 _observables.reserve(2 *
spans.size());
294 _observables.push_back(
total + 2 *
spans.size());
295 _observables.push_back(
item.second.size());
301 std::size_t
n =
item.second.size();
302 _observables.reserve(_observables.size() +
n);
303 for (std::size_t i = 0; i <
n; ++i) {
304 _observables.push_back(
item.second[i]);
310void RooFuncWrapper::createGradient()
317 gInterpreter->Declare(
"#include <Math/CladDerivator.h>\n");
323 " clad::gradient(" <<
_funcName <<
", \"params\");\n"
327 auto print = [](std::string
const &
msg) {
oocoutI(
nullptr, Fitting) <<
msg << std::endl; };
336 errorMsg <<
"Function could not be differentiated. See above for details.";
338 throw std::runtime_error(
errorMsg.str().c_str());
344 std::stringstream
ss;
346 ss <<
"static_cast<void (*)(double *, double const *, double const *, double *)>(" <<
gradName <<
");";
352 errorMsg <<
"Function could not be differentiated since ROOT was built without Clad support.";
354 throw std::runtime_error(
errorMsg.str().c_str());
358void RooFuncWrapper::updateGradientVarBuffer()
const
361 return obj->isCategory() ? static_cast<RooAbsCategory *>(obj)->getCurrentIndex()
362 : static_cast<RooAbsReal *>(obj)->getVal();
367void RooFuncWrapper::writeDebugMacro(std::string
const &
filename)
const
373 for (std::string
const &
name : _collectedFunctions) {
378 std::unique_ptr<TInterpreterValue>
v =
gInterpreter->MakeInterpreterValue();
380 std::string s =
v->ToString();
381 for (
int i = 0; i < 2; ++i) {
382 s = s.erase(0, s.find(
"\n") + 1);
389 outFile << R
"(//auto-generated test macro
390#include <RooFit/Detail/MathFuncs.h>
391#include <Math/CladDerivator.h>
396void gradient_request() {
406 std::stringstream
decl;
407 decl <<
"std::vector<double> " <<
name <<
" = {";
408 for (std::size_t i = 0; i <
vec.size(); ++i) {
412 if (i <
vec.size() - 1)
425 outFile <<
"// clang-format off\n" << std::endl;
432 outFile <<
"// clang-format on\n" << std::endl;
435// To run as a ROOT macro
439 std::vector<double> gradientVec(parametersVec.size());
441 auto func = [&](std::span<double> params) {
443 << _funcName << R"((params.data(), observablesVec.data(), auxConstantsVec.data());
445 auto grad = [&](std::span<double> params, std::span<double> out) {
447 << _funcName << R"(_grad_0(parametersVec.data(), observablesVec.data(), auxConstantsVec.data(),
451 grad(parametersVec, gradientVec);
453 auto numDiff = [&](int i) {
454 const double eps = 1e-6;
455 std::vector<double> p{parametersVec};
456 p[i] = parametersVec[i] - eps;
457 double funcValDown = func(p);
458 p[i] = parametersVec[i] + eps;
459 double funcValUp = func(p);
460 return (funcValUp - funcValDown) / (2 * eps);
463 for (std::size_t i = 0; i < parametersVec.size(); ++i) {
464 std::cout << i << ":" << std::endl;
465 std::cout << " numr : " << numDiff(i) << std::endl;
466 std::cout << " clad : " << gradientVec[i] << std::endl;
472double RooEvaluatorWrapper::evaluate()
const
481 :
RooFit::EvalContext::OffsetMode::WithOffset);
483 return _evaluator->run()[0];
492 constexpr auto errMsg =
"Error in RooAbsReal::setData(): only resetting with same-structured data is supported.";
498 std::stack<std::vector<double>>{}.swap(_vectorBuffers);
499 bool skipZeroWeights = !_pdf || !_pdf->getAttribute(
"BinnedLikelihoodActive");
502 _takeGlobalObservablesFromData, _vectorBuffers);
505 throw std::runtime_error(
errMsg);
508 const char *
name =
item.first->GetName();
509 _evaluator->setInput(
name,
item.second,
false);
510 if (_paramSet.find(
name)) {
512 throw std::runtime_error(
errMsg);
521void RooEvaluatorWrapper::createFuncWrapper()
525 this->getParameters(_data ? _data->get() : nullptr,
paramSet,
false);
531void RooEvaluatorWrapper::generateGradient()
538void RooEvaluatorWrapper::setUseGeneratedFunctionCode(
bool flag)
545void RooEvaluatorWrapper::gradient(
double *out)
const
550bool RooEvaluatorWrapper::hasGradient()
const
557void RooEvaluatorWrapper::writeDebugMacro(std::string
const &
filename)
const
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
static unsigned int total
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
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 filename
const_iterator begin() const
const_iterator end() const
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Abstract base class for binned and unbinned datasets.
Abstract interface for all probability density functions.
Abstract base class for objects that represent a real value and implements functionality common to al...
RooArgList is a container object that can hold multiple RooAbsArg objects.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
A class to maintain the context for squashing of RooFit models into 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 addVecObs(const char *key, int idx)
Since the squashed code represents all observables as a single flattened array, it is important to ke...
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::vector< std::string > const & collectedFunctions()
std::string const & collectedCode()
std::vector< double > const & xlArr()
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
void replaceAll(std::string &inOut, std::string_view what, std::string_view with)
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
void getSortedComputationGraph(RooAbsArg const &func, RooArgSet &out)
void evaluate(typename Architecture_t::Tensor_t &A, EActivationFunction f)
Apply the given activation function to each value in the given tensor A.