Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooEvaluatorWrapper.cxx
Go to the documentation of this file.
1/// \cond ROOFIT_INTERNAL
2
3/*
4 * Project: RooFit
5 * Authors:
6 * Jonas Rembser, CERN 2023
7 *
8 * Copyright (c) 2023, CERN
9 *
10 * Redistribution and use in source and binary forms,
11 * with or without modification, are permitted according to the terms
12 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
13 */
14
15/**
16\internal
17\file RooEvaluatorWrapper.cxx
18\class RooEvaluatorWrapper
19\ingroup Roofitcore
20
21Wraps a RooFit::Evaluator that evaluates a RooAbsReal back into a RooAbsReal.
22**/
23
24#include "RooEvaluatorWrapper.h"
25
26#include <RooAbsData.h>
27#include <RooAbsPdf.h>
28#include <RooMsgService.h>
29#include <RooRealVar.h>
30#include <RooSimultaneous.h>
31
33#include "RooFitImplHelpers.h"
34
35#include <TInterpreter.h>
36
37#include <fstream>
38
39namespace {
40
41// Throws an exception if any value in `span` is outside of the (default,
42// unnamed) range of `var`. The `obsName` is used only for the error message,
43// because it might differ from `var.GetName()` (e.g. the per-channel prefix
44// that RooSimultaneous adds is stripped for readability).
45void checkObservableSpanInRange(RooRealVar const &var, std::string const &obsName, std::string const &datasetName,
46 std::span<const double> span)
47{
48 for (double val : span) {
49 if (!var.inRange(val, nullptr)) {
50 const double lo = var.getMin();
51 const double hi = var.getMax();
52 std::stringstream errMsg;
53 errMsg << "RooAbsPdf::fitTo/createNLL: cannot evaluate the likelihood because dataset \"" << datasetName
54 << "\" has an entry for observable \"" << obsName << "\" with value " << val
55 << ", which is outside of its range [" << lo << ", " << hi << "]. The probability density is "
56 << "normalized over exactly that range, so events outside of it would silently bias the fit. If "
57 << "you want to fit only a subset of the data, define a named range and use it in the fit, for example:\n"
58 << " " << obsName << ".setRange(\"fitRange\", " << lo << ", " << hi << ");\n"
59 << " pdf.fitTo(data, RooFit::Range(\"fitRange\"));\n"
60 << "This way, only the events inside \"fitRange\" enter the likelihood, consistent with how the "
61 << "pdf is normalized.";
62 oocoutE(nullptr, InputArguments) << errMsg.str() << std::endl;
63 throw std::runtime_error(errMsg.str());
64 }
65 }
66}
67
68// Validates that no dataset entry lies outside of the range of the
69// corresponding observable, for every real-valued observable of `pdf`. This
70// check is skipped when a range name was explicitly given to the fit,
71// because in that case out-of-range events are intentionally and
72// consistently dropped by RooFit::BatchModeDataHelpers::getDataSpans().
74 std::map<RooFit::Detail::DataKey, std::span<const double>> const &dataSpans)
75{
76 if (!pdf)
77 return;
78
79 if (auto const *simPdf = dynamic_cast<RooSimultaneous const *>(pdf)) {
80 // The per-channel pdfs coming out of RooSimultaneous::compileForNormSet()
81 // have their observables cloned and renamed with a "_<channel>_" prefix
82 // (and tagged with the "__obs__" attribute), so that the shared data map
83 // can hold independent columns for each channel. We look those up the
84 // same way, and strip the prefix again for a readable error message.
85 for (auto const &nameIdx : simPdf->indexCat()) {
86 RooAbsPdf *channelPdf = simPdf->getPdf(nameIdx.first);
87 if (!channelPdf)
88 continue;
89 const std::string prefix = "_" + nameIdx.first + "_";
90 std::unique_ptr<RooArgSet> vars{channelPdf->getVariables()};
91 std::unique_ptr<RooArgSet> obs{vars->selectByAttrib("__obs__", true)};
92 for (RooAbsArg *arg : *obs) {
93 auto *realVar = dynamic_cast<RooRealVar *>(arg);
94 if (!realVar)
95 continue;
97 if (it == dataSpans.end())
98 continue;
99 std::string obsName = realVar->GetName();
100 if (obsName.rfind(prefix, 0) == 0) {
101 obsName = obsName.substr(prefix.size());
102 }
103 checkObservableSpanInRange(*realVar, obsName, data.GetName(), it->second);
104 }
105 }
106 return;
107 }
108
109 RooArgSet obs;
110 pdf->getObservables(data.get(), obs);
111 for (RooAbsArg *arg : obs) {
112 auto *realVar = dynamic_cast<RooRealVar *>(arg);
113 if (!realVar)
114 continue;
116 if (it == dataSpans.end())
117 continue;
118 checkObservableSpanInRange(*realVar, realVar->GetName(), data.GetName(), it->second);
119 }
120}
121
122} // namespace
123
124namespace RooFit::Experimental {
125
126RooEvaluatorWrapper::RooEvaluatorWrapper(RooAbsReal &topNode, RooAbsData *data, bool useGPU,
127 std::string const &rangeName, RooAbsPdf const *pdf,
129 : RooAbsReal{"RooEvaluatorWrapper", "RooEvaluatorWrapper"},
130 _evaluator{std::make_unique<RooFit::Evaluator>(topNode, useGPU)},
131 _topNode("topNode", "top node", this, topNode, false, false),
132 _data{data},
133 _paramSet("paramSet", "Set of parameters", this),
134 _rangeName{rangeName},
135 _pdf{pdf},
136 _takeGlobalObservablesFromData{takeGlobalObservablesFromData}
137{
138 if (nWorkers > 1 && !useGPU) {
139 _evaluator->setNThreads(nWorkers);
140 }
141 if (data) {
142 setData(*data, false);
143 }
144 _paramSet.add(_evaluator->getParameters());
145 for (auto const &item : _dataSpans) {
146 _paramSet.remove(*_paramSet.find(item.first->GetName()));
147 }
148}
149
150RooEvaluatorWrapper::RooEvaluatorWrapper(const RooEvaluatorWrapper &other, const char *name)
152 _evaluator{other._evaluator},
153 _topNode("topNode", this, other._topNode),
154 _data{other._data},
155 _paramSet("paramSet", "Set of parameters", this),
156 _rangeName{other._rangeName},
157 _pdf{other._pdf},
158 _takeGlobalObservablesFromData{other._takeGlobalObservablesFromData},
160{
161 _paramSet.add(other._paramSet);
162}
163
164RooEvaluatorWrapper::~RooEvaluatorWrapper() = default;
165
166bool RooEvaluatorWrapper::getParameters(const RooArgSet *observables, RooArgSet &outputSet,
167 bool stripDisconnected) const
168{
169 outputSet.add(_evaluator->getParameters());
170 if (observables) {
171 outputSet.remove(*observables, /*silent*/ false, /*matchByNameOnly*/ true);
172 }
173 // Exclude the data variables from the parameters which are not global observables
174 for (auto const &item : _dataSpans) {
175 if (_data->getGlobalObservables() && _data->getGlobalObservables()->find(item.first->GetName())) {
176 continue;
177 }
178 RooAbsArg *found = outputSet.find(item.first->GetName());
179 if (found) {
180 outputSet.remove(*found);
181 }
182 }
183 // If we take the global observables as data, we have to return these as
184 // parameters instead of the parameters in the model. Otherwise, the
185 // constant parameters in the fit result that are global observables will
186 // not have the right values.
187 if (_takeGlobalObservablesFromData && _data->getGlobalObservables()) {
188 outputSet.replace(*_data->getGlobalObservables());
189 }
190
191 // The disconnected parameters are stripped away in
192 // RooAbsArg::getParametersHook(), that is only called in the original
193 // RooAbsArg::getParameters() implementation. So he have to call it to
194 // identify disconnected parameters to remove.
195 if (stripDisconnected) {
197 _topNode->getParameters(observables, paramsStripped, true);
199 for (RooAbsArg *param : outputSet) {
200 if (!paramsStripped.find(param->GetName())) {
201 toRemove.add(*param);
202 }
203 }
204 outputSet.remove(toRemove, /*silent*/ false, /*matchByNameOnly*/ true);
205 }
206
207 return false;
208}
209
210/// @brief A wrapper class to store a C++ function of type 'double (*)(double*, double*)'.
211/// The parameters can be accessed as params[<relative position of param in paramSet>] in the function body.
212/// The observables can be accessed as obs[i + j], where i represents the observable position and j
213/// represents the data entry.
214class RooFuncWrapper {
215public:
217 std::string const &rangeName, bool skipZeroWeights);
218
219 bool hasGradient() const { return _hasGradient; }
220 bool hasHessian() const { return _hasHessian; }
221 void gradient(double *out) const
222 {
224 std::fill(out, out + _params.size(), 0.0);
225 _grad(_varBuffer.data(), _observables.data(), _xlArr.data(), out);
226 }
227 void hessian(double *out) const
228 {
230 std::fill(out, out + _params.size() * _params.size(), 0.0);
231 _hessian(_varBuffer.data(), _observables.data(), _xlArr.data(), out);
232 }
233
234 void createGradient();
235 void createHessian();
236
237 void writeDebugMacro(std::string const &) const;
238
239 std::vector<std::string> const &collectedFunctions() { return _collectedFunctions; }
240
241 double evaluate() const
242 {
244 return _func(_varBuffer.data(), _observables.data(), _xlArr.data());
245 }
246
247 void
248 loadData(RooAbsData const &data, RooSimultaneous const *simPdf, std::string const &rangeName, bool skipZeroWeights);
249
250private:
251 void updateGradientVarBuffer() const;
252
254
255 using Func = double (*)(double *, double const *, double const *);
256 using Grad = void (*)(double *, double const *, double const *, double *);
257 using Hessian = void (*)(double *, double const *, double const *, double *);
258
259 RooArgList _params;
260 std::string _funcName;
261 Func _func;
262 Grad _grad;
263 Hessian _hessian;
264 bool _hasGradient = false;
265 bool _hasHessian = false;
266 mutable std::vector<double> _varBuffer;
267 std::vector<double> _observables;
268 std::unordered_map<RooFit::Detail::DataKey, std::size_t> _obsInfos;
269 std::vector<double> _xlArr;
270 std::vector<std::string> _collectedFunctions;
271};
272
273namespace {
274
275void replaceAll(std::string &str, const std::string &from, const std::string &to)
276{
277 if (from.empty())
278 return;
279 size_t start_pos = 0;
280 while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
281 str.replace(start_pos, from.length(), to);
282 start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
283 }
284}
285
287{
290
291 std::unordered_set<RooFit::Detail::DataKey> dependsOnData;
292 for (RooAbsArg *arg : dataObs) {
293 dependsOnData.insert(arg);
294 }
295
296 for (RooAbsArg *arg : serverSet) {
297 if (arg->getAttribute("__obs__")) {
298 dependsOnData.insert(arg);
299 }
300 for (RooAbsArg *server : arg->servers()) {
301 if (server->isValueServer(*arg)) {
302 if (dependsOnData.find(server) != dependsOnData.end() && !arg->isReducerNode()) {
303 dependsOnData.insert(arg);
304 break;
305 }
306 }
307 }
308 }
309
310 return dependsOnData;
311}
312
313} // namespace
314
315RooFuncWrapper::RooFuncWrapper(RooAbsReal &obj, const RooAbsData *data, RooSimultaneous const *simPdf,
316 RooArgSet const &paramSet, std::string const &rangeName, bool skipZeroWeights)
317{
318 // Load the observables from the dataset
319 if (data) {
321 }
322
323 // Define the parameters
324 for (auto *param : paramSet) {
325 if (_obsInfos.find(param) == _obsInfos.end()) {
326 _params.add(*param);
327 }
328 }
329 _varBuffer.resize(_params.size());
330
331 // Figure out which part of the computation graph depends on data
332 std::unordered_set<RooFit::Detail::DataKey> dependsOnData;
333 if (data) {
334 dependsOnData = getDependsOnData(obj, *data->get());
335 }
336
337 // Set up the code generation context
339
340 // First update the result variable of params in the compute graph to in[<position>].
341 int idx = 0;
342 for (RooAbsArg *param : _params) {
343 ctx.addResult(param, "params[" + std::to_string(idx) + "]");
344 idx++;
345 }
346
347 for (auto const &item : _obsInfos) {
348 const char *obsName = item.first->GetName();
349 ctx.addResult(obsName, "obs");
350 ctx.addVecObs(obsName, item.second);
351 }
352
353 // Declare the function and create its derivative.
354 auto print = [](std::string const &msg) { oocoutI(nullptr, Fitting) << msg << std::endl; };
355 ROOT::Math::Util::TimingScope timingScope(print, "Function JIT time:");
356 _funcName = ctx.buildFunction(obj, dependsOnData);
357
358 // Make sure the codegen implementations are known to the interpreter
359 gInterpreter->Declare("#include <RooFit/CodegenImpl.h>\n");
360
361 if (!gInterpreter->Declare(ctx.collectedCode().c_str())) {
362 std::stringstream errorMsg;
363 std::string debugFileName = "_codegen_" + _funcName + ".cxx";
364 errorMsg << "Function " << _funcName << " could not be compiled. See above for details. Full code dumped to file "
365 << debugFileName << " for debugging";
366 {
367 std::ofstream outFile;
368 outFile.open(debugFileName.c_str());
369 outFile << ctx.collectedCode();
370 }
371 oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl;
372 throw std::runtime_error(errorMsg.str().c_str());
373 }
374
375 _func = reinterpret_cast<Func>(gInterpreter->ProcessLine((_funcName + ";").c_str()));
376
377 _xlArr = ctx.xlArr();
378 _collectedFunctions = ctx.collectedFunctions();
379}
380
381void RooFuncWrapper::loadData(RooAbsData const &data, RooSimultaneous const *simPdf, std::string const &rangeName,
382 bool skipZeroWeights)
383{
384 // Extract observables
385 std::stack<std::vector<double>> vectorBuffers; // for data loading
386 auto spans =
387 RooFit::BatchModeDataHelpers::getDataSpans(data, rangeName, simPdf, skipZeroWeights, false, vectorBuffers);
388
389 _observables.clear();
390 // The first elements contain the sizes of the packed observable arrays
391 std::size_t total = 0;
392 _observables.reserve(2 * spans.size());
393 std::size_t idx = 0;
394 for (auto const &item : spans) {
395 _obsInfos.emplace(item.first, idx);
396 _observables.push_back(total + 2 * spans.size());
397 _observables.push_back(item.second.size());
398 total += item.second.size();
399 idx += 1;
400 }
401 idx = 0;
402 for (auto const &item : spans) {
403 std::size_t n = item.second.size();
404 _observables.reserve(_observables.size() + n);
405 for (std::size_t i = 0; i < n; ++i) {
406 _observables.push_back(item.second[i]);
407 }
408 idx += n;
409 }
410}
411
412void RooFuncWrapper::createGradient()
413{
414#ifdef ROOFIT_CLAD
415 std::string gradName = _funcName + "_grad_0";
416 std::string requestName = _funcName + "_req";
417
418 // Calculate gradient
419 gInterpreter->Declare("#include <Math/CladDerivator.h>\n");
420 // disable clang-format for making the following code unreadable.
421 // clang-format off
422 std::stringstream requestFuncStrm;
423 requestFuncStrm << "#pragma clad ON\n"
424 "void " << requestName << "() {\n"
425 " clad::gradient(" << _funcName << ", \"params\");\n"
426 "}\n"
427 "#pragma clad OFF";
428 // clang-format on
429 auto print = [](std::string const &msg) { oocoutI(nullptr, Fitting) << msg << std::endl; };
430
431 bool cladSuccess = false;
432 {
433 ROOT::Math::Util::TimingScope timingScope(print, "Gradient generation time:");
434 cladSuccess = !gInterpreter->Declare(requestFuncStrm.str().c_str());
435 }
436 if (cladSuccess) {
437 std::stringstream errorMsg;
438 errorMsg << "Function could not be differentiated. See above for details.";
439 oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl;
440 throw std::runtime_error(errorMsg.str().c_str());
441 }
442
443 // Clad provides different overloads for the gradient, and we need to
444 // resolve to the one that we want. Without the static_cast, getting the
445 // function pointer would be ambiguous.
446 std::stringstream ss;
447 ROOT::Math::Util::TimingScope timingScope(print, "Gradient IR to machine code time:");
448 ss << "static_cast<void (*)(double *, double const *, double const *, double *)>(" << gradName << ");";
449 _grad = reinterpret_cast<Grad>(gInterpreter->ProcessLine(ss.str().c_str()));
450 _hasGradient = true;
451#else
452 _hasGradient = false;
453 std::stringstream errorMsg;
454 errorMsg << "Function could not be differentiated since ROOT was built without Clad support.";
455 oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl;
456 throw std::runtime_error(errorMsg.str().c_str());
457#endif
458}
459
460void RooFuncWrapper::createHessian()
461{
462#ifdef ROOFIT_CLAD
463 std::string hessianName = _funcName + "_hessian_0";
464 std::string requestName = _funcName + "_hessian_req";
465
466 // Calculate Hessian
467 gInterpreter->Declare("#include <Math/CladDerivator.h>\n");
468 // disable clang-format for making the following code unreadable.
469 // clang-format off
470 std::stringstream requestFuncStrm;
471 std::string paramsStr =
472 _params.size() == 1 ? "\"params[0]\"" : ("\"params[0:" + std::to_string(_params.size() - 1) + "]\"");
473 requestFuncStrm << "#pragma clad ON\n"
474 "void " << requestName << "() {\n"
475 " clad::hessian(" << _funcName << ", " << paramsStr << ");\n"
476 "}\n"
477 "#pragma clad OFF";
478 // clang-format on
479 auto print = [](std::string const &msg) { oocoutI(nullptr, Fitting) << msg << std::endl; };
480
481 bool cladSuccess = false;
482 {
483 ROOT::Math::Util::TimingScope timingScope(print, "Hessian generation time:");
484 cladSuccess = !gInterpreter->Declare(requestFuncStrm.str().c_str());
485 }
486 if (cladSuccess) {
487 std::stringstream errorMsg;
488 errorMsg << "Function could not be differentiated. See above for details.";
489 oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl;
490 throw std::runtime_error(errorMsg.str().c_str());
491 }
492
493 // Clad provides different overloads for the Hessian, and we need to
494 // resolve to the one that we want. Without the static_cast, getting the
495 // function pointer would be ambiguous.
496 std::stringstream ss;
497 ROOT::Math::Util::TimingScope timingScope(print, "Hessian IR to machine code time:");
498 ss << "static_cast<void (*)(double *, double const *, double const *, double *)>(" << hessianName << ");";
499 _hessian = reinterpret_cast<Hessian>(gInterpreter->ProcessLine(ss.str().c_str()));
500 _hasHessian = true;
501#else
502 _hasHessian = false;
503 std::stringstream errorMsg;
504 errorMsg << "Function could not be differentiated since ROOT was built without Clad support.";
505 oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl;
506 throw std::runtime_error(errorMsg.str().c_str());
507#endif
508}
509
510void RooFuncWrapper::updateGradientVarBuffer() const
511{
512 std::transform(_params.begin(), _params.end(), _varBuffer.begin(), [](RooAbsArg *obj) {
513 return obj->isCategory() ? static_cast<RooAbsCategory *>(obj)->getCurrentIndex()
514 : static_cast<RooAbsReal *>(obj)->getVal();
515 });
516}
517
518/// @brief Dumps a macro "filename.C" that can be used to test and debug the generated code and gradient.
519void RooFuncWrapper::writeDebugMacro(std::string const &filename) const
520{
521 std::stringstream allCode;
522 std::set<std::string> seenFunctions;
523
524 // Remove duplicated declared functions
525 for (std::string const &name : _collectedFunctions) {
526 if (seenFunctions.count(name) > 0) {
527 continue;
528 }
529 seenFunctions.insert(name);
530 std::unique_ptr<TInterpreterValue> v = gInterpreter->MakeInterpreterValue();
531 gInterpreter->Evaluate(name.c_str(), *v);
532 std::string s = v->ToString();
533 for (int i = 0; i < 2; ++i) {
534 s = s.erase(0, s.find("\n") + 1);
535 }
536 allCode << s << std::endl;
537 }
538
539 std::ofstream outFile;
540 std::string paramsStr =
541 _params.size() == 1 ? "\"params[0]\"" : ("\"params[0:" + std::to_string(_params.size() - 1) + "]\"");
542 outFile.open(filename + ".C");
543 outFile << R"(//auto-generated test macro
544#include <RooFit/Detail/MathFuncs.h>
545#include <Math/CladDerivator.h>
546
547//#define DO_HESSIAN
548
549)" << allCode.str()
550 << R"(
551#pragma clad ON
552void gradient_request() {
553 clad::gradient()"
554 << _funcName << R"(, "params");
555#ifdef DO_HESSIAN
556 clad::hessian()"
557 << _funcName << ", " << paramsStr << R"();
558#endif
559}
560#pragma clad OFF
561)";
562
564
565 auto writeVector = [&](std::string const &name, std::span<const double> vec) {
566 std::stringstream decl;
567 decl << "std::vector<double> " << name << " = {";
568 for (std::size_t i = 0; i < vec.size(); ++i) {
569 if (i % 10 == 0)
570 decl << "\n ";
571 decl << vec[i];
572 if (i < vec.size() - 1)
573 decl << ", ";
574 }
575 decl << "\n};\n";
576
577 std::string declStr = decl.str();
578
579 replaceAll(declStr, "inf", "std::numeric_limits<double>::infinity()");
580 replaceAll(declStr, "nan", "NAN");
581
582 outFile << declStr;
583 };
584
585 outFile << "// clang-format off\n" << std::endl;
586 writeVector("parametersVec", _varBuffer);
587 outFile << std::endl;
588 writeVector("observablesVec", _observables);
589 outFile << std::endl;
590 writeVector("auxConstantsVec", _xlArr);
591 outFile << std::endl;
592 outFile << "// clang-format on\n" << std::endl;
593
594 outFile << R"(
595// To run as a ROOT macro
596void )" << filename
597 << R"(()
598{
599 const std::size_t n = parametersVec.size();
600
601 std::vector<double> gradientVec(n);
602
603 auto func = [&](std::span<double> params) {
604 return )"
605 << _funcName << R"((params.data(), observablesVec.data(), auxConstantsVec.data());
606 };
607 auto grad = [&](std::span<double> params, std::span<double> out) {
608 return )"
609 << _funcName << R"(_grad_0(parametersVec.data(), observablesVec.data(), auxConstantsVec.data(),
610 out.data());
611 };
612
613 grad(parametersVec, gradientVec);
614
615 auto numDiff = [&](int i) {
616 const double eps = 1e-6;
617 std::vector<double> p{parametersVec};
618 p[i] = parametersVec[i] - eps;
619 double funcValDown = func(p);
620 p[i] = parametersVec[i] + eps;
621 double funcValUp = func(p);
622 return (funcValUp - funcValDown) / (2 * eps);
623 };
624
625 for (std::size_t i = 0; i < parametersVec.size(); ++i) {
626 std::cout << i << ":" << std::endl;
627 std::cout << " numr : " << numDiff(i) << std::endl;
628 std::cout << " clad : " << gradientVec[i] << std::endl;
629 }
630
631#ifdef DO_HESSIAN
632 std::cout << "\n";
633
634 auto hess = [&](std::span<double> params, std::span<double> out) {
635 return )"
636 << _funcName << R"(_hessian_0(params.data(), observablesVec.data(), auxConstantsVec.data(), out.data());
637 };
638
639 std::vector<double> hessianVec(n * n);
640 hess(parametersVec, hessianVec);
641
642 // ---------- Numerical Hessian ----------
643 // Uses central differences:
644 // diag: (f(x+ei)-2f(x)+f(x-ei))/eps^2
645 // offdiag: (f(++ ) - f(+-) - f(-+) + f(--)) / (4 eps^2)
646 auto numHess = [&](std::size_t i, std::size_t j) {
647 const double eps = 1e-5; // often needs to be a bit larger than grad eps
648 std::vector<double> p(parametersVec.begin(), parametersVec.end());
649
650 if (i == j) {
651 const double f0 = func(p);
652
653 p[i] = parametersVec[i] + eps;
654 const double fUp = func(p);
655
656 p[i] = parametersVec[i] - eps;
657 const double fDown = func(p);
658
659 return (fUp - 2.0 * f0 + fDown) / (eps * eps);
660 } else {
661 // f(x_i + eps, x_j + eps)
662 p[i] = parametersVec[i] + eps;
663 p[j] = parametersVec[j] + eps;
664 const double fPP = func(p);
665
666 // f(x_i + eps, x_j - eps)
667 p[i] = parametersVec[i] + eps;
668 p[j] = parametersVec[j] - eps;
669 const double fPM = func(p);
670
671 // f(x_i - eps, x_j + eps)
672 p[i] = parametersVec[i] - eps;
673 p[j] = parametersVec[j] + eps;
674 const double fMP = func(p);
675
676 // f(x_i - eps, x_j - eps)
677 p[i] = parametersVec[i] - eps;
678 p[j] = parametersVec[j] - eps;
679 const double fMM = func(p);
680
681 return (fPP - fPM - fMP + fMM) / (4.0 * eps * eps);
682 }
683 };
684
685 // Compute full numerical Hessian
686 std::vector<double> numHessianVec(n * n);
687 for (std::size_t i = 0; i < n; ++i) {
688 for (std::size_t j = 0; j < n; ++j) {
689 numHessianVec[i + n * j] = numHess(i, j); // keep same layout as your print
690 }
691 }
692
693 // ---------- Compare & print ----------
694 std::cout << "Hessian comparison (clad vs numeric vs diff):\n\n";
695
696 for (std::size_t i = 0; i < n; ++i) {
697 for (std::size_t j = 0; j < n; ++j) {
698 const std::size_t idx = i + n * j; // same indexing you used
699 const double cladH = hessianVec[idx];
700 const double numH = numHessianVec[idx];
701 const double diff = cladH - numH;
702
703 std::cout << "[" << i << "," << j << "] "
704 << "clad=" << cladH << " num=" << numH << " diff=" << diff << "\n";
705 }
706 }
707
708 std::cout << "\nRaw Clad Hessian matrix:\n";
709 for (std::size_t i = 0; i < n; ++i) {
710 for (std::size_t j = 0; j < n; ++j) {
711 std::cout << hessianVec[i + n * j] << " ";
712 }
713 std::cout << "\n";
714 }
715
716 std::cout << "\nRaw Numerical Hessian matrix:\n";
717 for (std::size_t i = 0; i < n; ++i) {
718 for (std::size_t j = 0; j < n; ++j) {
719 std::cout << numHessianVec[i + n * j] << " ";
720 }
721 std::cout << "\n";
722 }
723#endif
724}
725)";
726}
727
728double RooEvaluatorWrapper::evaluate() const
729{
731 return _funcWrapper->evaluate();
732
733 if (!_evaluator)
734 return 0.0;
735
736 _evaluator->setOffsetMode(hideOffset() ? RooFit::EvalContext::OffsetMode::WithoutOffset
737 : RooFit::EvalContext::OffsetMode::WithOffset);
738
739 return _evaluator->run()[0];
740}
741
742bool RooEvaluatorWrapper::setData(RooAbsData &data, bool /*cloneData*/)
743{
744 // To make things easier for RooFit, we only support resetting with
745 // datasets that have the same structure, e.g. the same columns and global
746 // observables. This is anyway the usecase: resetting same-structured data
747 // when iterating over toys.
748 constexpr auto errMsg = "Error in RooAbsReal::setData(): only resetting with same-structured data is supported.";
749
750 _data = &data;
751 bool isInitializing = _paramSet.empty();
752 const std::size_t oldSize = _dataSpans.size();
753
754 std::stack<std::vector<double>>{}.swap(_vectorBuffers);
755 const bool isChi2 = _topNode->getAttribute("Chi2EvaluationActive");
756 bool skipZeroWeights = !isChi2 && (!_pdf || !_pdf->getAttribute("BinnedLikelihoodActive"));
757 auto simPdf = dynamic_cast<RooSimultaneous const *>(_pdf);
758 _dataSpans = RooFit::BatchModeDataHelpers::getDataSpans(*_data, _rangeName, simPdf, skipZeroWeights,
759 _takeGlobalObservablesFromData, _vectorBuffers);
760 if (_rangeName.empty()) {
762 }
763 if (!isInitializing && _dataSpans.size() != oldSize) {
764 coutE(DataHandling) << errMsg << std::endl;
765 throw std::runtime_error(errMsg);
766 }
767 for (auto const &item : _dataSpans) {
768 const char *name = item.first->GetName();
769 _evaluator->setInput(name, item.second, false);
770 if (_paramSet.find(name)) {
771 coutE(DataHandling) << errMsg << std::endl;
772 throw std::runtime_error(errMsg);
773 }
774 }
775 if (_funcWrapper) {
776 _funcWrapper->loadData(*_data, simPdf, _rangeName, skipZeroWeights);
777 }
778 return true;
779}
780
781void RooEvaluatorWrapper::createFuncWrapper()
782{
783 // Get the parameters.
785 this->getParameters(_data ? _data->get() : nullptr, paramSet, /*sripDisconnectedParams=*/false);
786
787 const bool isChi2 = _topNode->getAttribute("Chi2EvaluationActive");
788 const bool skipZeroWeights = !isChi2 && (!_pdf || !_pdf->getAttribute("BinnedLikelihoodActive"));
789 _funcWrapper = std::make_unique<RooFuncWrapper>(*_topNode, _data, dynamic_cast<RooSimultaneous const *>(_pdf),
790 paramSet, _rangeName, skipZeroWeights);
791}
792
793void RooEvaluatorWrapper::generateGradient()
794{
795 if (!_funcWrapper)
797 if (!_funcWrapper->hasGradient())
798 _funcWrapper->createGradient();
799}
800
801void RooEvaluatorWrapper::generateHessian()
802{
803 if (!_funcWrapper)
805 if (!_funcWrapper->hasHessian())
806 _funcWrapper->createHessian();
807}
808
809void RooEvaluatorWrapper::setUseGeneratedFunctionCode(bool flag)
810{
814}
815
816void RooEvaluatorWrapper::gradient(double *out) const
817{
818 _funcWrapper->gradient(out);
819}
820
821void RooEvaluatorWrapper::hessian(double *out) const
822{
823 _funcWrapper->hessian(out);
824}
825
826bool RooEvaluatorWrapper::hasGradient() const
827{
828 return _funcWrapper && _funcWrapper->hasGradient();
829}
830
831bool RooEvaluatorWrapper::hasHessian() const
832{
833 return _funcWrapper && _funcWrapper->hasHessian();
834}
835
836void RooEvaluatorWrapper::writeDebugMacro(std::string const &filename) const
837{
838 if (_funcWrapper)
839 return _funcWrapper->writeDebugMacro(filename);
840}
841
842std::unique_ptr<ChangeOperModeRAII> RooEvaluatorWrapper::setOperModes(RooAbsArg::OperMode opMode)
843{
844 return _evaluator->setOperModes(opMode);
845}
846
847} // namespace RooFit::Experimental
848
849/// \endcond
#define oocoutE(o, a)
#define oocoutI(o, a)
#define coutE(a)
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
char name[80]
Definition TGX11.cxx:142
#define hi
#define gInterpreter
const_iterator begin() const
const_iterator end() const
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:76
RooFit::OwningPtr< RooArgSet > getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:55
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
virtual double getMax(const char *name=nullptr) const
Get maximum of currently defined range.
virtual double getMin(const char *name=nullptr) const
Get minimum of currently defined range.
bool inRange(const char *name) const override
Check if current value is inside range with given name.
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
A class to maintain the context for squashing of RooFit models into code.
Variable that can be changed from the outside.
Definition RooRealVar.h:37
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
const Int_t n
Definition legend1.C:16
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...
Definition CodegenImpl.h:73
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.
Definition Functions.h:98