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 <Roo1DTable.h>
27#include <RooAbsData.h>
28#include <RooAbsPdf.h>
29#include <RooCategory.h>
30#include <RooMsgService.h>
31#include <RooRealVar.h>
32#include <RooSimultaneous.h>
33
35#include "RooFitImplHelpers.h"
36
37#include <ROOT/StringUtils.hxx>
38#include <TInterpreter.h>
39
40#include <algorithm>
41#include <fstream>
42#include <functional>
43#include <limits>
44
45namespace {
46
47// Throws an exception if any value in `span` is outside of the (default,
48// unnamed) range of `var`. The `obsName` is used only for the error message,
49// because it might differ from `var.GetName()` (e.g. the per-channel prefix
50// that RooSimultaneous adds is stripped for readability).
51void checkObservableSpanInRange(RooRealVar const &var, std::string const &obsName, std::string const &datasetName,
52 std::span<const double> span)
53{
54 for (double val : span) {
55 if (!var.inRange(val, nullptr)) {
56 const double lo = var.getMin();
57 const double hi = var.getMax();
58 std::stringstream errMsg;
59 errMsg << "RooAbsPdf::fitTo/createNLL: cannot evaluate the likelihood because dataset \"" << datasetName
60 << "\" has an entry for observable \"" << obsName << "\" with value " << val
61 << ", which is outside of its range [" << lo << ", " << hi << "]. The probability density is "
62 << "normalized over exactly that range, so events outside of it would silently bias the fit. If "
63 << "you want to fit only a subset of the data, define a named range and use it in the fit, for example:\n"
64 << " " << obsName << ".setRange(\"fitRange\", " << lo << ", " << hi << ");\n"
65 << " pdf.fitTo(data, RooFit::Range(\"fitRange\"));\n"
66 << "This way, only the events inside \"fitRange\" enter the likelihood, consistent with how the "
67 << "pdf is normalized.";
68 oocoutE(nullptr, InputArguments) << errMsg.str() << std::endl;
69 throw std::runtime_error(errMsg.str());
70 }
71 }
72}
73
74// Validates that no dataset entry lies outside of the range of the
75// corresponding observable, for every real-valued observable of `pdf`. This
76// check is skipped when a range name was explicitly given to the fit,
77// because in that case out-of-range events are intentionally and
78// consistently dropped by RooFit::BatchModeDataHelpers::getDataSpans().
79void validateObservableRanges(RooAbsPdf const *pdf, RooAbsData const &data,
80 std::map<RooFit::Detail::DataKey, std::span<const double>> const &dataSpans)
81{
82 if (!pdf)
83 return;
84
85 if (auto const *simPdf = dynamic_cast<RooSimultaneous const *>(pdf)) {
86 // The per-channel pdfs coming out of RooSimultaneous::compileForNormSet()
87 // have their observables cloned and renamed with a "_<channel>_" prefix
88 // (and tagged with the "__obs__" attribute), so that the shared data map
89 // can hold independent columns for each channel. We look those up the
90 // same way, and strip the prefix again for a readable error message.
91 for (auto const &nameIdx : simPdf->indexCat()) {
92 RooAbsPdf *channelPdf = simPdf->getPdf(nameIdx.first);
93 if (!channelPdf)
94 continue;
95 const std::string prefix = "_" + nameIdx.first + "_";
96 std::unique_ptr<RooArgSet> vars{channelPdf->getVariables()};
97 std::unique_ptr<RooArgSet> obs{vars->selectByAttrib("__obs__", true)};
98 for (RooAbsArg *arg : *obs) {
99 auto *realVar = dynamic_cast<RooRealVar *>(arg);
100 if (!realVar)
101 continue;
102 auto it = dataSpans.find(RooFit::Detail::DataKey(realVar));
103 if (it == dataSpans.end())
104 continue;
105 std::string obsName = realVar->GetName();
106 if (obsName.rfind(prefix, 0) == 0) {
107 obsName = obsName.substr(prefix.size());
108 }
109 checkObservableSpanInRange(*realVar, obsName, data.GetName(), it->second);
110 }
111 }
112 return;
113 }
114
115 RooArgSet obs;
116 pdf->getObservables(data.get(), obs);
117 for (RooAbsArg *arg : obs) {
118 auto *realVar = dynamic_cast<RooRealVar *>(arg);
119 if (!realVar)
120 continue;
121 auto it = dataSpans.find(RooFit::Detail::DataKey(realVar));
122 if (it == dataSpans.end())
123 continue;
124 checkObservableSpanInRange(*realVar, realVar->GetName(), data.GetName(), it->second);
125 }
126}
127
128// Throws an exception if the data for a pdf that is evaluated with the binned
129// likelihood optimization doesn't consist of exactly one entry per bin of the
130// pdf, ordered like the bins of a RooDataHist (last observable varying
131// fastest). The optimization takes each entry as a bin, so any other layout
132// gives a wrong likelihood. Only bins that are not fully in the fit range can
133// be missing, and empty data is accepted, e.g. for a channel that is not in
134// the dataset. The `observables` are the ones of the pdf, named like the data
135// variables with a `prefix`, which is not empty for a RooSimultaneous channel.
136// `hasEntries` tells if there are entries before the range selection.
137void checkBinnedLikelihoodData(RooAbsPdf const &pdf, RooArgSet const &observables, RooAbsData const &data,
138 std::string const &prefix, std::string const &channelName, std::string const &rangeName,
139 std::map<RooFit::Detail::DataKey, std::span<const double>> const &dataSpans,
140 std::function<bool()> const &hasEntries)
141{
142 auto fail = [&](std::string const &reason) {
143 std::stringstream errMsg;
144 errMsg << "RooAbsPdf::fitTo/createNLL: the dataset \"" << data.GetName() << "\" ";
145 if (!channelName.empty()) {
146 errMsg << "in channel \"" << channelName << "\" ";
147 }
148 errMsg << "can't be used with the binned likelihood optimization: " << reason
149 << ". The optimization requires exactly one entry in each bin of the pdf, in the order of the bins, "
150 "like in a RooDataHist with the binning of the pdf. To create the likelihood with this dataset, "
151 "disable the binned likelihood optimization by calling "
152 "setAttribute(\"BinnedLikelihood\", false) on the pdf that has this attribute. If you think that the "
153 "optimization should work with this dataset, please report it by opening an issue on the ROOT GitHub "
154 "repository.";
155 oocoutE(nullptr, InputArguments) << errMsg.str() << std::endl;
156 throw std::invalid_argument(errMsg.str());
157 };
158
159 const std::vector<std::string> subRanges = ROOT::Split(rangeName, ",", /*skipEmpty=*/true);
160
161 // A bin that is partially in the range is `Maybe` in the range, because
162 // the range selection of its entry depends on where it is in the bin.
163 enum RangeState : char {
164 Out,
165 Maybe,
166 In
167 };
168
169 struct Dim {
170 std::string name;
171 std::span<const double> values;
172 std::vector<double> boundaries;
173 std::vector<std::vector<RangeState>> inSubRange; // for each sub-range and bin
174 std::size_t stride = 1; // in the index of all bins
175 double tol = 0.; // a few times the precision of the boundaries
176
177 std::size_t nBins() const { return boundaries.size() - 1; }
178 std::size_t bin(std::size_t iBin) const { return (iBin / stride) % nBins(); }
179 double binWidth(std::size_t i) const { return boundaries[i + 1] - boundaries[i]; }
180 };
181 std::vector<Dim> dims;
182
183 std::size_t nBins = 1;
184 for (auto *dataVar : dynamic_range_cast<RooAbsRealLValue *>(*data.get())) {
185 auto *obs =
186 dataVar ? dynamic_cast<RooRealVar *>(observables.find((prefix + dataVar->GetName()).c_str())) : nullptr;
187 if (!obs)
188 continue;
189 auto found = dataSpans.find(RooFit::Detail::DataKey(obs));
190 std::unique_ptr<std::list<double>> boundaries{pdf.binBoundaries(*obs, obs->getMin(), obs->getMax())};
191 if (!boundaries || boundaries->size() < 2) {
192 fail(std::string("the pdf provides no bin boundaries for the observable \"") + dataVar->GetName() + "\"");
193 }
194 dims.push_back({dataVar->GetName(),
195 found != dataSpans.end() ? found->second : std::span<const double>{},
196 {boundaries->begin(), boundaries->end()},
197 {}});
198 Dim &dim = dims.back();
199 dim.tol = 8 * std::numeric_limits<double>::epsilon() *
200 std::max(std::abs(dim.boundaries.front()), std::abs(dim.boundaries.back()));
201 // The range selection is done with the ranges of the data variables
202 for (std::string const &subRange : subRanges) {
203 dim.inSubRange.emplace_back();
204 const double rangeLo = dataVar->getMin(subRange.c_str());
205 const double rangeHi = dataVar->getMax(subRange.c_str());
206 for (std::size_t i = 0; i < dim.nBins(); ++i) {
207 const double lo = dim.boundaries[i];
208 const double hi = dim.boundaries[i + 1];
209 const bool isOut = rangeHi < lo - dim.tol || rangeLo > hi + dim.tol;
210 dim.inSubRange.back().push_back(rangeLo <= lo && hi <= rangeHi ? In : (isOut ? Out : Maybe));
211 }
212 }
213 nBins *= dim.nBins();
214 }
215 if (dims.empty())
216 return;
217
218 // The last observable varies fastest
219 for (std::size_t i = dims.size() - 1; i > 0; --i) {
220 dims[i - 1].stride = dims[i].stride * dims[i].nBins();
221 }
222
223 const std::size_t nEntries = dims.front().values.size();
224
225 // The range selection is not applied to data with a single entry
226 const bool isRanged = !subRanges.empty() && !(nBins == 1 && nEntries == 1);
227
228 // No entries is only a mismatch if the range selection removed all of them
229 if (nEntries == 0 && (!isRanged || !hasEntries()))
230 return;
231
232 // Like the range selection of the data, a bin is in the range if it is in
233 // a sub-range in all observables
234 std::vector<RangeState> binStates(nBins, isRanged ? Out : In);
235 std::size_t nBinsInRange = 0;
236 std::size_t nBinsMaybeInRange = 0;
237 std::size_t endOfBinsInRange = 0;
238 for (std::size_t iBin = 0; iBin < nBins; ++iBin) {
239 RangeState &state = binStates[iBin];
240 for (std::size_t iSub = 0; isRanged && iSub < subRanges.size(); ++iSub) {
241 RangeState inSub = In;
242 for (Dim const &dim : dims) {
243 inSub = std::min(inSub, dim.inSubRange[iSub][dim.bin(iBin)]);
244 }
245 state = std::max(state, inSub);
246 }
247 nBinsMaybeInRange += state == Maybe;
248 if (state == In) {
249 ++nBinsInRange;
250 endOfBinsInRange = iBin + 1;
251 }
252 }
253 auto failNumEntries = [&]() {
254 const std::string inRange = isRanged ? " in the fit range" : "";
255 fail("it has " + std::to_string(nEntries) + " entries" + inRange + ", which doesn't match the " +
256 std::to_string(nBinsInRange) + " bins of the pdf" + inRange);
257 };
258 if (nEntries < nBinsInRange || nEntries > nBinsInRange + nBinsMaybeInRange) {
259 failNumEntries();
260 }
261
262 // The upper boundary belongs to the next bin, except for the last bin. A
263 // value just below the lower boundary is accepted, because the bin that
264 // the pdf finds for it depends on the rounding.
265 auto isInBin = [&](std::size_t iEntry, std::size_t iBin) {
266 return std::all_of(dims.begin(), dims.end(), [&](Dim const &dim) {
267 const double val = dim.values[iEntry];
268 const std::size_t i = dim.bin(iBin);
269 return val >= dim.boundaries[i] - dim.tol &&
270 (val < dim.boundaries[i + 1] || (i + 1 == dim.nBins() && val <= dim.boundaries[i + 1] + dim.tol));
271 });
272 };
273 // If the entry might as well be in a next bin
274 auto isAtUpperEdge = [&](std::size_t iEntry, std::size_t iBin) {
275 return std::any_of(dims.begin(), dims.end(), [&](Dim const &dim) {
276 return dim.values[iEntry] >= dim.boundaries[dim.bin(iBin) + 1] - dim.tol;
277 });
278 };
279
280 // Without RooBinWidthFunctions in the pdf, the likelihood multiplies the
281 // pdf values with the width of the bin at the position of the entry
282 const bool usesBinWidths = !pdf.getAttribute("BinnedLikelihoodActiveYields") && dims.size() == 1;
283
284 // The bins that the next entry can be in start at one of these positions.
285 // There is more than one if an entry at a bin boundary could be in a bin
286 // that might have been removed by the range selection, or in the next one.
287 std::vector<std::size_t> positions{0};
288 std::vector<std::size_t> nextPositions;
289
290 for (std::size_t iEntry = 0; iEntry < nEntries; ++iEntry) {
291 Dim const &dim0 = dims.front();
292 bool binWidthMismatch = false;
293 nextPositions.clear();
294 for (std::size_t iBin : positions) {
295 // An entry at a boundary is in one of the next bins up to this one
296 std::size_t iBinEnd = nBins;
297 for (; iBin < iBinEnd; ++iBin) {
298 const RangeState state = binStates[iBin];
299 if (state != Out && isInBin(iEntry, iBin)) {
300 if (usesBinWidths &&
301 std::abs(dim0.binWidth(iBin) - dim0.binWidth(iEntry)) > 1e-6 * dim0.binWidth(iEntry)) {
302 binWidthMismatch = true;
303 } else if (std::find(nextPositions.begin(), nextPositions.end(), iBin + 1) == nextPositions.end()) {
304 nextPositions.push_back(iBin + 1);
305 }
306 if (state == In || !isAtUpperEdge(iEntry, iBin))
307 break;
308 iBinEnd = std::min(iBinEnd, iBin + dim0.stride + 1);
309 } else if (state == In) {
310 // Bins in the range can't be skipped
311 break;
312 }
313 }
314 }
315 if (nextPositions.empty()) {
316 if (binWidthMismatch) {
317 fail("the fit range excludes bins, which is not supported for a pdf with bins of different widths that "
318 "is not built with RooBinWidthFunctions");
319 }
320 std::stringstream reason;
321 reason << "entry " << iEntry << " (";
322 for (Dim const &dim : dims) {
323 reason << (&dim == &dims.front() ? "" : ", ") << dim.name << " = " << dim.values[iEntry];
324 }
325 reason << ") is not in the bin that is expected at its position";
326 fail(reason.str());
327 }
328 positions.swap(nextPositions);
329 }
330 // All remaining bins must have been removed by the range selection
331 if (std::none_of(positions.begin(), positions.end(), [&](std::size_t iBin) { return iBin >= endOfBinsInRange; })) {
332 failNumEntries();
333 }
334}
335
336// Runs checkBinnedLikelihoodData() for the pdf, or for the channels of a
337// RooSimultaneous, where the binned likelihood optimization is active.
338void validateBinnedLikelihoodData(RooAbsPdf const *pdf, RooAbsData const &data, std::string const &rangeName,
339 std::map<RooFit::Detail::DataKey, std::span<const double>> const &dataSpans)
340{
341 if (!pdf)
342 return;
343
344 auto const *simPdf = dynamic_cast<RooSimultaneous const *>(pdf);
345 if (simPdf && simPdf->indexCatIsObservable(*data.get())) {
346 RooAbsCategoryLValue const &simCat = simPdf->indexCat();
347 auto *simCatAsRooCategory = dynamic_cast<RooCategory const *>(&simCat);
348 const bool splitRange = simPdf->getAttribute("SplitRange");
349 // Only filled if needed, because it requires a loop over the data
350 std::unique_ptr<Roo1DTable> table;
351 for (auto const &nameIdx : simCat) {
352 std::string const &channelName = nameIdx.first;
353 RooAbsPdf *channelPdf = simPdf->getPdf(channelName);
354 if (!channelPdf || !channelPdf->getAttribute("BinnedLikelihoodActive"))
355 continue;
356 // Channels excluded by a category range are not in the likelihood
357 if (!rangeName.empty() && simCatAsRooCategory &&
358 !simCatAsRooCategory->isStateInRange(rangeName.c_str(), nameIdx.second))
359 continue;
360 auto hasEntries = [&]() {
361 if (!table) {
362 table.reset(data.table(simCat));
363 }
364 return table->get(channelName.c_str(), /*silent=*/true) != 0.;
365 };
366 // See validateObservableRanges() for the observables and their prefix
367 std::unique_ptr<RooArgSet> vars{channelPdf->getVariables()};
368 std::unique_ptr<RooArgSet> obs{vars->selectByAttrib("__obs__", true)};
369 checkBinnedLikelihoodData(*channelPdf, *obs, data, "_" + channelName + "_", channelName,
371 dataSpans, hasEntries);
372 }
373 } else if (pdf->getAttribute("BinnedLikelihoodActive")) {
374 RooArgSet obs;
375 pdf->getObservables(data.get(), obs);
376 checkBinnedLikelihoodData(*pdf, obs, data, "", "", rangeName, dataSpans, [&]() { return data.numEntries() > 0; });
377 }
378}
379
380} // namespace
381
382namespace RooFit::Experimental {
383
384RooEvaluatorWrapper::RooEvaluatorWrapper(RooAbsReal &topNode, RooAbsData *data, bool useGPU,
385 std::string const &rangeName, RooAbsPdf const *pdf,
386 bool takeGlobalObservablesFromData, int nWorkers)
387 : RooAbsReal{"RooEvaluatorWrapper", "RooEvaluatorWrapper"},
388 _evaluator{std::make_unique<RooFit::Evaluator>(topNode, useGPU)},
389 _topNode("topNode", "top node", this, topNode, false, false),
390 _data{data},
391 _paramSet("paramSet", "Set of parameters", this),
392 _rangeName{rangeName},
393 _pdf{pdf},
394 _takeGlobalObservablesFromData{takeGlobalObservablesFromData}
395{
396 if (nWorkers > 1 && !useGPU) {
397 _evaluator->setNThreads(nWorkers);
398 }
399 if (data) {
400 setData(*data, false);
401 }
402 _paramSet.add(_evaluator->getParameters());
403 for (auto const &item : _dataSpans) {
404 _paramSet.remove(*_paramSet.find(item.first->GetName()));
405 }
406}
407
408RooEvaluatorWrapper::RooEvaluatorWrapper(const RooEvaluatorWrapper &other, const char *name)
409 : RooAbsReal{other, name},
410 _evaluator{other._evaluator},
411 _topNode("topNode", this, other._topNode),
412 _data{other._data},
413 _paramSet("paramSet", "Set of parameters", this),
414 _rangeName{other._rangeName},
415 _pdf{other._pdf},
416 _takeGlobalObservablesFromData{other._takeGlobalObservablesFromData},
417 _dataSpans{other._dataSpans}
418{
419 _paramSet.add(other._paramSet);
420}
421
422RooEvaluatorWrapper::~RooEvaluatorWrapper() = default;
423
424bool RooEvaluatorWrapper::getParameters(const RooArgSet *observables, RooArgSet &outputSet,
425 bool stripDisconnected) const
426{
427 outputSet.add(_evaluator->getParameters());
428 if (observables) {
429 outputSet.remove(*observables, /*silent*/ false, /*matchByNameOnly*/ true);
430 }
431 // Exclude the data variables from the parameters which are not global observables
432 for (auto const &item : _dataSpans) {
433 if (_data->getGlobalObservables() && _data->getGlobalObservables()->find(item.first->GetName())) {
434 continue;
435 }
436 RooAbsArg *found = outputSet.find(item.first->GetName());
437 if (found) {
438 outputSet.remove(*found);
439 }
440 }
441 // If we take the global observables as data, we have to return these as
442 // parameters instead of the parameters in the model. Otherwise, the
443 // constant parameters in the fit result that are global observables will
444 // not have the right values.
445 if (_takeGlobalObservablesFromData && _data->getGlobalObservables()) {
446 outputSet.replace(*_data->getGlobalObservables());
447 }
448
449 // The disconnected parameters are stripped away in
450 // RooAbsArg::getParametersHook(), that is only called in the original
451 // RooAbsArg::getParameters() implementation. So he have to call it to
452 // identify disconnected parameters to remove.
453 if (stripDisconnected) {
454 RooArgSet paramsStripped;
455 _topNode->getParameters(observables, paramsStripped, true);
456 RooArgSet toRemove;
457 for (RooAbsArg *param : outputSet) {
458 if (!paramsStripped.find(param->GetName())) {
459 toRemove.add(*param);
460 }
461 }
462 outputSet.remove(toRemove, /*silent*/ false, /*matchByNameOnly*/ true);
463 }
464
465 return false;
466}
467
468/// @brief A wrapper class to store a C++ function of type 'double (*)(double*, double*)'.
469/// The parameters can be accessed as params[<relative position of param in paramSet>] in the function body.
470/// The observables can be accessed as obs[i + j], where i represents the observable position and j
471/// represents the data entry.
472class RooFuncWrapper {
473public:
474 RooFuncWrapper(RooAbsReal &obj, const RooAbsData *data, RooSimultaneous const *simPdf, RooArgSet const &paramSet,
475 std::string const &rangeName, bool skipZeroWeights);
476
477 bool hasGradient() const { return _hasGradient; }
478 bool hasHessian() const { return _hasHessian; }
479 void gradient(double *out) const
480 {
481 updateGradientVarBuffer();
482 std::fill(out, out + _params.size(), 0.0);
483 _grad(_varBuffer.data(), _observables.data(), _xlArr.data(), out);
484 }
485 void hessian(double *out) const
486 {
487 updateGradientVarBuffer();
488 std::fill(out, out + _params.size() * _params.size(), 0.0);
489 _hessian(_varBuffer.data(), _observables.data(), _xlArr.data(), out);
490 }
491
492 void createGradient();
493 void createHessian();
494
495 void writeDebugMacro(std::string const &) const;
496
497 std::vector<std::string> const &collectedFunctions() { return _collectedFunctions; }
498
499 double evaluate() const
500 {
501 updateGradientVarBuffer();
502 return _func(_varBuffer.data(), _observables.data(), _xlArr.data());
503 }
504
505 void
506 loadData(RooAbsData const &data, RooSimultaneous const *simPdf, std::string const &rangeName, bool skipZeroWeights);
507
508private:
509 void updateGradientVarBuffer() const;
510
511 void buildFuncAndGradFunctors();
512
513 using Func = double (*)(double *, double const *, double const *);
514 using Grad = void (*)(double *, double const *, double const *, double *);
515 using Hessian = void (*)(double *, double const *, double const *, double *);
516
517 RooArgList _params;
518 std::string _funcName;
519 Func _func;
520 Grad _grad;
521 Hessian _hessian;
522 bool _hasGradient = false;
523 bool _hasHessian = false;
524 mutable std::vector<double> _varBuffer;
525 std::vector<double> _observables;
526 std::unordered_map<RooFit::Detail::DataKey, std::size_t> _obsInfos;
527 std::vector<double> _xlArr;
528 std::vector<std::string> _collectedFunctions;
529};
530
531namespace {
532
533void replaceAll(std::string &str, const std::string &from, const std::string &to)
534{
535 if (from.empty())
536 return;
537 size_t start_pos = 0;
538 while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
539 str.replace(start_pos, from.length(), to);
540 start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
541 }
542}
543
544auto getDependsOnData(RooAbsReal &obj, RooArgSet const &dataObs)
545{
546 RooArgSet serverSet;
548
549 std::unordered_set<RooFit::Detail::DataKey> dependsOnData;
550 for (RooAbsArg *arg : dataObs) {
551 dependsOnData.insert(arg);
552 }
553
554 for (RooAbsArg *arg : serverSet) {
555 if (arg->getAttribute("__obs__")) {
556 dependsOnData.insert(arg);
557 }
558 for (RooAbsArg *server : arg->servers()) {
559 if (server->isValueServer(*arg)) {
560 if (dependsOnData.find(server) != dependsOnData.end() && !arg->isReducerNode()) {
561 dependsOnData.insert(arg);
562 break;
563 }
564 }
565 }
566 }
567
568 return dependsOnData;
569}
570
571} // namespace
572
573RooFuncWrapper::RooFuncWrapper(RooAbsReal &obj, const RooAbsData *data, RooSimultaneous const *simPdf,
574 RooArgSet const &paramSet, std::string const &rangeName, bool skipZeroWeights)
575{
576 // Load the observables from the dataset
577 if (data) {
578 loadData(*data, simPdf, rangeName, skipZeroWeights);
579 }
580
581 // Define the parameters
582 for (auto *param : paramSet) {
583 if (_obsInfos.find(param) == _obsInfos.end()) {
584 _params.add(*param);
585 }
586 }
587 _varBuffer.resize(_params.size());
588
589 // Figure out which part of the computation graph depends on data
590 std::unordered_set<RooFit::Detail::DataKey> dependsOnData;
591 if (data) {
592 dependsOnData = getDependsOnData(obj, *data->get());
593 }
594
595 // Set up the code generation context
597
598 // First update the result variable of params in the compute graph to in[<position>].
599 int idx = 0;
600 for (RooAbsArg *param : _params) {
601 ctx.addResult(param, "params[" + std::to_string(idx) + "]");
602 idx++;
603 }
604
605 for (auto const &item : _obsInfos) {
606 const char *obsName = item.first->GetName();
607 ctx.addResult(obsName, "obs");
608 ctx.addVecObs(obsName, item.second);
609 }
610
611 // Declare the function and create its derivative.
612 auto print = [](std::string const &msg) { oocoutI(nullptr, Fitting) << msg << std::endl; };
613 ROOT::Math::Util::TimingScope timingScope(print, "Function JIT time:");
614 _funcName = ctx.buildFunction(obj, dependsOnData);
615
616 // Make sure the codegen implementations are known to the interpreter
617 gInterpreter->Declare("#include <RooFit/CodegenImpl.h>\n");
618
619 if (!gInterpreter->Declare(ctx.collectedCode().c_str())) {
620 std::stringstream errorMsg;
621 std::string debugFileName = "_codegen_" + _funcName + ".cxx";
622 errorMsg << "Function " << _funcName << " could not be compiled. See above for details. Full code dumped to file "
623 << debugFileName << " for debugging";
624 {
625 std::ofstream outFile;
626 outFile.open(debugFileName.c_str());
627 outFile << ctx.collectedCode();
628 }
629 oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl;
630 throw std::runtime_error(errorMsg.str().c_str());
631 }
632
633 _func = reinterpret_cast<Func>(gInterpreter->ProcessLine((_funcName + ";").c_str()));
634
635 _xlArr = ctx.xlArr();
636 _collectedFunctions = ctx.collectedFunctions();
637}
638
639void RooFuncWrapper::loadData(RooAbsData const &data, RooSimultaneous const *simPdf, std::string const &rangeName,
640 bool skipZeroWeights)
641{
642 // Extract observables
643 std::stack<std::vector<double>> vectorBuffers; // for data loading
644 auto spans =
645 RooFit::BatchModeDataHelpers::getDataSpans(data, rangeName, simPdf, skipZeroWeights, false, vectorBuffers);
646
647 _observables.clear();
648 // The first elements contain the sizes of the packed observable arrays
649 std::size_t total = 0;
650 _observables.reserve(2 * spans.size());
651 std::size_t idx = 0;
652 for (auto const &item : spans) {
653 _obsInfos.emplace(item.first, idx);
654 _observables.push_back(total + 2 * spans.size());
655 _observables.push_back(item.second.size());
656 total += item.second.size();
657 idx += 1;
658 }
659 idx = 0;
660 for (auto const &item : spans) {
661 std::size_t n = item.second.size();
662 _observables.reserve(_observables.size() + n);
663 for (std::size_t i = 0; i < n; ++i) {
664 _observables.push_back(item.second[i]);
665 }
666 idx += n;
667 }
668}
669
670void RooFuncWrapper::createGradient()
671{
672#ifdef ROOFIT_CLAD
673 std::string gradName = _funcName + "_grad_0";
674 std::string requestName = _funcName + "_req";
675
676 // Calculate gradient
677 gInterpreter->Declare("#include <Math/CladDerivator.h>\n");
678 // disable clang-format for making the following code unreadable.
679 // clang-format off
680 std::stringstream requestFuncStrm;
681 requestFuncStrm << "#pragma clad ON\n"
682 "void " << requestName << "() {\n"
683 " clad::gradient(" << _funcName << ", \"params\");\n"
684 "}\n"
685 "#pragma clad OFF";
686 // clang-format on
687 auto print = [](std::string const &msg) { oocoutI(nullptr, Fitting) << msg << std::endl; };
688
689 bool cladSuccess = false;
690 {
691 ROOT::Math::Util::TimingScope timingScope(print, "Gradient generation time:");
692 cladSuccess = !gInterpreter->Declare(requestFuncStrm.str().c_str());
693 }
694 if (cladSuccess) {
695 std::stringstream errorMsg;
696 errorMsg << "Function could not be differentiated. See above for details.";
697 oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl;
698 throw std::runtime_error(errorMsg.str().c_str());
699 }
700
701 // Clad provides different overloads for the gradient, and we need to
702 // resolve to the one that we want. Without the static_cast, getting the
703 // function pointer would be ambiguous.
704 std::stringstream ss;
705 ROOT::Math::Util::TimingScope timingScope(print, "Gradient IR to machine code time:");
706 ss << "static_cast<void (*)(double *, double const *, double const *, double *)>(" << gradName << ");";
707 _grad = reinterpret_cast<Grad>(gInterpreter->ProcessLine(ss.str().c_str()));
708 _hasGradient = true;
709#else
710 _hasGradient = false;
711 std::stringstream errorMsg;
712 errorMsg << "Function could not be differentiated since ROOT was built without Clad support.";
713 oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl;
714 throw std::runtime_error(errorMsg.str().c_str());
715#endif
716}
717
718void RooFuncWrapper::createHessian()
719{
720#ifdef ROOFIT_CLAD
721 std::string hessianName = _funcName + "_hessian_0";
722 std::string requestName = _funcName + "_hessian_req";
723
724 // Calculate Hessian
725 gInterpreter->Declare("#include <Math/CladDerivator.h>\n");
726 // disable clang-format for making the following code unreadable.
727 // clang-format off
728 std::stringstream requestFuncStrm;
729 std::string paramsStr =
730 _params.size() == 1 ? "\"params[0]\"" : ("\"params[0:" + std::to_string(_params.size() - 1) + "]\"");
731 requestFuncStrm << "#pragma clad ON\n"
732 "void " << requestName << "() {\n"
733 " clad::hessian(" << _funcName << ", " << paramsStr << ");\n"
734 "}\n"
735 "#pragma clad OFF";
736 // clang-format on
737 auto print = [](std::string const &msg) { oocoutI(nullptr, Fitting) << msg << std::endl; };
738
739 bool cladSuccess = false;
740 {
741 ROOT::Math::Util::TimingScope timingScope(print, "Hessian generation time:");
742 cladSuccess = !gInterpreter->Declare(requestFuncStrm.str().c_str());
743 }
744 if (cladSuccess) {
745 std::stringstream errorMsg;
746 errorMsg << "Function could not be differentiated. See above for details.";
747 oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl;
748 throw std::runtime_error(errorMsg.str().c_str());
749 }
750
751 // Clad provides different overloads for the Hessian, and we need to
752 // resolve to the one that we want. Without the static_cast, getting the
753 // function pointer would be ambiguous.
754 std::stringstream ss;
755 ROOT::Math::Util::TimingScope timingScope(print, "Hessian IR to machine code time:");
756 ss << "static_cast<void (*)(double *, double const *, double const *, double *)>(" << hessianName << ");";
757 _hessian = reinterpret_cast<Hessian>(gInterpreter->ProcessLine(ss.str().c_str()));
758 _hasHessian = true;
759#else
760 _hasHessian = false;
761 std::stringstream errorMsg;
762 errorMsg << "Function could not be differentiated since ROOT was built without Clad support.";
763 oocoutE(nullptr, InputArguments) << errorMsg.str() << std::endl;
764 throw std::runtime_error(errorMsg.str().c_str());
765#endif
766}
767
768void RooFuncWrapper::updateGradientVarBuffer() const
769{
770 std::transform(_params.begin(), _params.end(), _varBuffer.begin(), [](RooAbsArg *obj) {
771 return obj->isCategory() ? static_cast<RooAbsCategory *>(obj)->getCurrentIndex()
772 : static_cast<RooAbsReal *>(obj)->getVal();
773 });
774}
775
776/// @brief Dumps a macro "filename.C" that can be used to test and debug the generated code and gradient.
777void RooFuncWrapper::writeDebugMacro(std::string const &filename) const
778{
779 std::stringstream allCode;
780 std::set<std::string> seenFunctions;
781
782 // Remove duplicated declared functions
783 for (std::string const &name : _collectedFunctions) {
784 if (seenFunctions.count(name) > 0) {
785 continue;
786 }
787 seenFunctions.insert(name);
788 std::unique_ptr<TInterpreterValue> v = gInterpreter->MakeInterpreterValue();
789 gInterpreter->Evaluate(name.c_str(), *v);
790 std::string s = v->ToString();
791 for (int i = 0; i < 2; ++i) {
792 s = s.erase(0, s.find('\n') + 1);
793 }
794 allCode << s << std::endl;
795 }
796
797 std::ofstream outFile;
798 std::string paramsStr =
799 _params.size() == 1 ? "\"params[0]\"" : ("\"params[0:" + std::to_string(_params.size() - 1) + "]\"");
800 outFile.open(filename + ".C");
801 outFile << R"(//auto-generated test macro
802#include <RooFit/Detail/MathFuncs.h>
803#include <Math/CladDerivator.h>
804
805//#define DO_HESSIAN
806
807)" << allCode.str()
808 << R"(
809#pragma clad ON
810void gradient_request() {
811 clad::gradient()"
812 << _funcName << R"(, "params");
813#ifdef DO_HESSIAN
814 clad::hessian()"
815 << _funcName << ", " << paramsStr << R"();
816#endif
817}
818#pragma clad OFF
819)";
820
821 updateGradientVarBuffer();
822
823 auto writeVector = [&](std::string const &name, std::span<const double> vec) {
824 std::stringstream decl;
825 decl << "std::vector<double> " << name << " = {";
826 for (std::size_t i = 0; i < vec.size(); ++i) {
827 if (i % 10 == 0)
828 decl << "\n ";
829 decl << vec[i];
830 if (i < vec.size() - 1)
831 decl << ", ";
832 }
833 decl << "\n};\n";
834
835 std::string declStr = decl.str();
836
837 replaceAll(declStr, "inf", "std::numeric_limits<double>::infinity()");
838 replaceAll(declStr, "nan", "NAN");
839
840 outFile << declStr;
841 };
842
843 outFile << "// clang-format off\n" << std::endl;
844 writeVector("parametersVec", _varBuffer);
845 outFile << std::endl;
846 writeVector("observablesVec", _observables);
847 outFile << std::endl;
848 writeVector("auxConstantsVec", _xlArr);
849 outFile << std::endl;
850 outFile << "// clang-format on\n" << std::endl;
851
852 outFile << R"(
853// To run as a ROOT macro
854void )" << filename
855 << R"(()
856{
857 const std::size_t n = parametersVec.size();
858
859 std::vector<double> gradientVec(n);
860
861 auto func = [&](std::span<double> params) {
862 return )"
863 << _funcName << R"((params.data(), observablesVec.data(), auxConstantsVec.data());
864 };
865 auto grad = [&](std::span<double> params, std::span<double> out) {
866 return )"
867 << _funcName << R"(_grad_0(parametersVec.data(), observablesVec.data(), auxConstantsVec.data(),
868 out.data());
869 };
870
871 grad(parametersVec, gradientVec);
872
873 auto numDiff = [&](int i) {
874 const double eps = 1e-6;
875 std::vector<double> p{parametersVec};
876 p[i] = parametersVec[i] - eps;
877 double funcValDown = func(p);
878 p[i] = parametersVec[i] + eps;
879 double funcValUp = func(p);
880 return (funcValUp - funcValDown) / (2 * eps);
881 };
882
883 for (std::size_t i = 0; i < parametersVec.size(); ++i) {
884 std::cout << i << ":" << std::endl;
885 std::cout << " numr : " << numDiff(i) << std::endl;
886 std::cout << " clad : " << gradientVec[i] << std::endl;
887 }
888
889#ifdef DO_HESSIAN
890 std::cout << "\n";
891
892 auto hess = [&](std::span<double> params, std::span<double> out) {
893 return )"
894 << _funcName << R"(_hessian_0(params.data(), observablesVec.data(), auxConstantsVec.data(), out.data());
895 };
896
897 std::vector<double> hessianVec(n * n);
898 hess(parametersVec, hessianVec);
899
900 // ---------- Numerical Hessian ----------
901 // Uses central differences:
902 // diag: (f(x+ei)-2f(x)+f(x-ei))/eps^2
903 // offdiag: (f(++ ) - f(+-) - f(-+) + f(--)) / (4 eps^2)
904 auto numHess = [&](std::size_t i, std::size_t j) {
905 const double eps = 1e-5; // often needs to be a bit larger than grad eps
906 std::vector<double> p(parametersVec.begin(), parametersVec.end());
907
908 if (i == j) {
909 const double f0 = func(p);
910
911 p[i] = parametersVec[i] + eps;
912 const double fUp = func(p);
913
914 p[i] = parametersVec[i] - eps;
915 const double fDown = func(p);
916
917 return (fUp - 2.0 * f0 + fDown) / (eps * eps);
918 } else {
919 // f(x_i + eps, x_j + eps)
920 p[i] = parametersVec[i] + eps;
921 p[j] = parametersVec[j] + eps;
922 const double fPP = func(p);
923
924 // f(x_i + eps, x_j - eps)
925 p[i] = parametersVec[i] + eps;
926 p[j] = parametersVec[j] - eps;
927 const double fPM = func(p);
928
929 // f(x_i - eps, x_j + eps)
930 p[i] = parametersVec[i] - eps;
931 p[j] = parametersVec[j] + eps;
932 const double fMP = func(p);
933
934 // f(x_i - eps, x_j - eps)
935 p[i] = parametersVec[i] - eps;
936 p[j] = parametersVec[j] - eps;
937 const double fMM = func(p);
938
939 return (fPP - fPM - fMP + fMM) / (4.0 * eps * eps);
940 }
941 };
942
943 // Compute full numerical Hessian
944 std::vector<double> numHessianVec(n * n);
945 for (std::size_t i = 0; i < n; ++i) {
946 for (std::size_t j = 0; j < n; ++j) {
947 numHessianVec[i + n * j] = numHess(i, j); // keep same layout as your print
948 }
949 }
950
951 // ---------- Compare & print ----------
952 std::cout << "Hessian comparison (clad vs numeric vs diff):\n\n";
953
954 for (std::size_t i = 0; i < n; ++i) {
955 for (std::size_t j = 0; j < n; ++j) {
956 const std::size_t idx = i + n * j; // same indexing you used
957 const double cladH = hessianVec[idx];
958 const double numH = numHessianVec[idx];
959 const double diff = cladH - numH;
960
961 std::cout << "[" << i << "," << j << "] "
962 << "clad=" << cladH << " num=" << numH << " diff=" << diff << "\n";
963 }
964 }
965
966 std::cout << "\nRaw Clad Hessian matrix:\n";
967 for (std::size_t i = 0; i < n; ++i) {
968 for (std::size_t j = 0; j < n; ++j) {
969 std::cout << hessianVec[i + n * j] << " ";
970 }
971 std::cout << "\n";
972 }
973
974 std::cout << "\nRaw Numerical Hessian matrix:\n";
975 for (std::size_t i = 0; i < n; ++i) {
976 for (std::size_t j = 0; j < n; ++j) {
977 std::cout << numHessianVec[i + n * j] << " ";
978 }
979 std::cout << "\n";
980 }
981#endif
982}
983)";
984}
985
986double RooEvaluatorWrapper::evaluate() const
987{
988 if (_useGeneratedFunctionCode)
989 return _funcWrapper->evaluate();
990
991 if (!_evaluator)
992 return 0.0;
993
994 _evaluator->setOffsetMode(hideOffset() ? RooFit::EvalContext::OffsetMode::WithoutOffset
995 : RooFit::EvalContext::OffsetMode::WithOffset);
996
997 return _evaluator->run()[0];
998}
999
1000bool RooEvaluatorWrapper::setData(RooAbsData &data, bool /*cloneData*/)
1001{
1002 // To make things easier for RooFit, we only support resetting with
1003 // datasets that have the same structure, e.g. the same columns and global
1004 // observables. This is anyway the usecase: resetting same-structured data
1005 // when iterating over toys.
1006 constexpr auto errMsg = "Error in RooAbsReal::setData(): only resetting with same-structured data is supported.";
1007
1008 _data = &data;
1009 bool isInitializing = _paramSet.empty();
1010 const std::size_t oldSize = _dataSpans.size();
1011
1012 std::stack<std::vector<double>>{}.swap(_vectorBuffers);
1013 const bool isChi2 = _topNode->getAttribute("Chi2EvaluationActive");
1014 bool skipZeroWeights = !isChi2 && (!_pdf || !_pdf->getAttribute("BinnedLikelihoodActive"));
1015 auto simPdf = dynamic_cast<RooSimultaneous const *>(_pdf);
1016 _dataSpans = RooFit::BatchModeDataHelpers::getDataSpans(*_data, _rangeName, simPdf, skipZeroWeights,
1017 _takeGlobalObservablesFromData, _vectorBuffers);
1018 if (_rangeName.empty()) {
1019 validateObservableRanges(_pdf, *_data, _dataSpans);
1020 }
1021 validateBinnedLikelihoodData(_pdf, *_data, _rangeName, _dataSpans);
1022 if (!isInitializing && _dataSpans.size() != oldSize) {
1023 coutE(DataHandling) << errMsg << std::endl;
1024 throw std::runtime_error(errMsg);
1025 }
1026 for (auto const &item : _dataSpans) {
1027 const char *name = item.first->GetName();
1028 _evaluator->setInput(name, item.second, false);
1029 if (_paramSet.find(name)) {
1030 coutE(DataHandling) << errMsg << std::endl;
1031 throw std::runtime_error(errMsg);
1032 }
1033 }
1034 if (_funcWrapper) {
1035 _funcWrapper->loadData(*_data, simPdf, _rangeName, skipZeroWeights);
1036 }
1037 return true;
1038}
1039
1040void RooEvaluatorWrapper::createFuncWrapper()
1041{
1042 // Get the parameters.
1043 RooArgSet paramSet;
1044 this->getParameters(_data ? _data->get() : nullptr, paramSet, /*sripDisconnectedParams=*/false);
1045
1046 const bool isChi2 = _topNode->getAttribute("Chi2EvaluationActive");
1047 const bool skipZeroWeights = !isChi2 && (!_pdf || !_pdf->getAttribute("BinnedLikelihoodActive"));
1048 _funcWrapper = std::make_unique<RooFuncWrapper>(*_topNode, _data, dynamic_cast<RooSimultaneous const *>(_pdf),
1049 paramSet, _rangeName, skipZeroWeights);
1050}
1051
1052void RooEvaluatorWrapper::generateGradient()
1053{
1054 if (!_funcWrapper)
1055 createFuncWrapper();
1056 if (!_funcWrapper->hasGradient())
1057 _funcWrapper->createGradient();
1058}
1059
1060void RooEvaluatorWrapper::generateHessian()
1061{
1062 if (!_funcWrapper)
1063 createFuncWrapper();
1064 if (!_funcWrapper->hasHessian())
1065 _funcWrapper->createHessian();
1066}
1067
1068void RooEvaluatorWrapper::setUseGeneratedFunctionCode(bool flag)
1069{
1070 _useGeneratedFunctionCode = flag;
1071 if (!_funcWrapper && _useGeneratedFunctionCode)
1072 createFuncWrapper();
1073}
1074
1075void RooEvaluatorWrapper::gradient(double *out) const
1076{
1077 _funcWrapper->gradient(out);
1078}
1079
1080void RooEvaluatorWrapper::hessian(double *out) const
1081{
1082 _funcWrapper->hessian(out);
1083}
1084
1085bool RooEvaluatorWrapper::hasGradient() const
1086{
1087 return _funcWrapper && _funcWrapper->hasGradient();
1088}
1089
1090bool RooEvaluatorWrapper::hasHessian() const
1091{
1092 return _funcWrapper && _funcWrapper->hasHessian();
1093}
1094
1095void RooEvaluatorWrapper::writeDebugMacro(std::string const &filename) const
1096{
1097 if (_funcWrapper)
1098 return _funcWrapper->writeDebugMacro(filename);
1099}
1100
1101std::unique_ptr<ChangeOperModeRAII> RooEvaluatorWrapper::setOperModes(RooAbsArg::OperMode opMode)
1102{
1103 return _evaluator->setOperModes(opMode);
1104}
1105
1106} // namespace RooFit::Experimental
1107
1108/// \endcond
std::string channelName
#define e(i)
Definition RSha256.hxx:103
ROOT::RRangeCast< T, true, Range_t > dynamic_range_cast(Range_t &&coll)
#define oocoutE(o, a)
#define oocoutI(o, a)
#define coutE(a)
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
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
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.
bool getAttribute(const Text_t *name) const
Check if a named attribute is set. By default, all attributes are unset.
RooFit::OwningPtr< RooArgSet > getVariables(bool stripDisconnected=true) const
Return RooArgSet with all variables (tree leaf nodes of expression tree)
Abstract base class for objects that represent a discrete value that can be set from the outside,...
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
virtual bool replace(const RooAbsArg &var1, const RooAbsArg &var2)
Replace var1 with var2 and return true for success.
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:55
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
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
virtual std::list< double > * binBoundaries(RooAbsRealLValue &obs, double xlo, double xhi) const
Retrieve bin boundaries if this distribution is binned in obs.
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
RooArgSet * selectByAttrib(const char *name, bool value) const
Use RooAbsCollection::selectByAttrib(), but return as RooArgSet.
Definition RooArgSet.h:144
Object to represent discrete states.
Definition RooCategory.h:28
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::vector< double > const & xlArr()
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
CoordSystem::Scalar get(DisplacementVector2D< CoordSystem, Tag > const &p)
std::vector< std::string > Split(std::string_view str, std::string_view delims, bool skipEmpty=false)
Splits a string at each character in delims.
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
std::string getRangeNameForSimComponent(std::string const &rangeName, bool splitRange, std::string const &catName)
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