Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
CodegenImpl.cxx
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 * Authors:
4 * Garima Singh, CERN 2023
5 * Jonas Rembser, CERN 2024
6 *
7 * Copyright (c) 2024, CERN
8 *
9 * Redistribution and use in source and binary forms,
10 * with or without modification, are permitted according to the terms
11 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
12 */
13
14#include <RooFit/CodegenImpl.h>
15
17
18#include <RooAddPdf.h>
19#include <RooAddition.h>
20#include <RooBernstein.h>
21#include <RooBifurGauss.h>
22#include <RooCBShape.h>
23#include <RooCategory.h>
24#include <RooChebychev.h>
25#include <RooConstVar.h>
26#include <RooConstraintSum.h>
27#include <RooEffProd.h>
28#include <RooEfficiency.h>
29#include <RooExponential.h>
30#include <RooExtendPdf.h>
33#include <RooFormulaVar.h>
34#include <RooFunctor1DBinding.h>
35#include <RooFunctorBinding.h>
36#include <RooGamma.h>
37#include <RooGaussian.h>
38#include <RooGenericPdf.h>
39#include <RooHistFunc.h>
40#include <RooHistPdf.h>
41#include <RooLandau.h>
42#include <RooLognormal.h>
43#include <RooMultiPdf.h>
44#include <RooMultiVarGaussian.h>
45#include <RooONNXFunc.h>
46#include <RooParamHistFunc.h>
47#include <RooPoisson.h>
48#include <RooPolyVar.h>
49#include <RooPolynomial.h>
50#include <RooProdPdf.h>
51#include <RooProduct.h>
52#include <RooRatio.h>
53#include <RooRealIntegral.h>
54#include <RooRealSumFunc.h>
55#include <RooRealSumPdf.h>
56#include <RooRealVar.h>
58#include <RooSimultaneous.h>
62#include <RooUniform.h>
63#include <RooWrapperPdf.h>
64
65#include "RooFitImplHelpers.h"
66
67#include <TInterpreter.h>
68
69#include <locale>
70#include <unordered_set>
71
72namespace RooFit::Experimental {
73
74namespace {
75
76// Return a stringy-field version of the value, formatted to maximum precision.
77std::string doubleToString(double val)
78{
79 std::stringstream ss;
80 // The formatting must not depend on the global locale: a comma decimal
81 // separator (e.g. from a German locale) would corrupt the generated C++.
82 ss.imbue(std::locale::classic());
83 ss << std::setprecision(std::numeric_limits<double>::max_digits10) << val;
84 return ss.str();
85}
86
87std::string mathFunc(std::string const &name)
88{
89 return "RooFit::Detail::MathFuncs::" + name;
90}
91
92void rooHistTranslateImpl(RooAbsArg const &arg, CodegenContext &ctx, int intOrder, RooDataHist const &dataHist,
93 const RooArgSet &obs, bool correctForBinSize, bool cdfBoundaries)
94{
95 if (intOrder != 0 && !(!cdfBoundaries && !correctForBinSize && intOrder == 1 && obs.size() == 1)) {
96 ooccoutE(&arg, InputArguments) << "RooHistPdf::weight(" << arg.GetName()
97 << ") ERROR: codegen currently only supports non-interpolation cases."
98 << std::endl;
99 return;
100 }
101
102 if (intOrder == 1) {
103 RooAbsBinning const &binning = *dataHist.getBinnings()[0];
104 std::string weightArr = dataHist.declWeightArrayForCodeSquash(ctx, correctForBinSize);
105 ctx.addResult(&arg, ctx.buildCall(mathFunc("interpolate1d"), binning.lowBound(), binning.highBound(), *obs[0],
106 binning.numBins(), weightArr));
107 return;
108 }
109 std::string const &offset = dataHist.calculateTreeIndexForCodeSquash(ctx, obs);
110 std::string weightArr = dataHist.declWeightArrayForCodeSquash(ctx, correctForBinSize);
111 ctx.addResult(&arg, "(" + weightArr + ")[" + offset + "]");
112}
113
114std::string realSumPdfTranslateImpl(CodegenContext &ctx, RooAbsArg const &arg, RooArgList const &funcList,
115 RooArgList const &coefList, bool normalize)
116{
117 bool noLastCoeff = funcList.size() != coefList.size();
118
119 std::string const &funcName = ctx.buildArg(funcList);
120 std::string const &coeffName = ctx.buildArg(coefList);
121 std::string const &coeffSize = std::to_string(coefList.size());
122
123 std::string sum = ctx.getTmpVarName();
124 std::string coeffSum = ctx.getTmpVarName();
125 ctx.addToCodeBody(&arg, "double " + sum + " = 0;\ndouble " + coeffSum + "= 0;\n");
126
127 std::string iterator = "i_" + ctx.getTmpVarName();
128 std::string subscriptExpr = "[" + iterator + "]";
129
130 std::string code = "for(int " + iterator + " = 0; " + iterator + " < " + coeffSize + "; " + iterator + "++) {\n" +
131 sum + " += " + funcName + subscriptExpr + " * " + coeffName + subscriptExpr + ";\n";
132 code += coeffSum + " += " + coeffName + subscriptExpr + ";\n";
133 code += "}\n";
134
135 if (noLastCoeff) {
136 code += sum + " += " + funcName + "[" + coeffSize + "]" + " * (1 - " + coeffSum + ");\n";
137 } else if (normalize) {
138 code += sum + " /= " + coeffSum + ";\n";
139 }
140 ctx.addToCodeBody(&arg, code);
141
142 return sum;
143}
144
145} // namespace
146
148{
149 if (arg.isRearranged()) {
150 ctx.addResult(&arg, ctx.buildCall(mathFunc("ratio"), *arg.rearrangedNum(), *arg.rearrangedDen()));
151 } else {
152 ctx.addResult(&arg, ctx.buildCall(mathFunc("product"), *arg.partList(), arg.partList()->size()));
153 }
154}
155
157{
158 std::string const &idx = arg.dataHist().calculateTreeIndexForCodeSquash(ctx, arg.dataVars(), true);
159 std::string const &paramNames = ctx.buildArg(arg.paramList());
160
161 ctx.addResult(&arg, paramNames + "[" + idx + "]");
162}
163
165{
166 auto const &interpCodes = arg.interpolationCodes();
167
168 std::size_t n = interpCodes.size();
169
170 std::string resName = "total_" + ctx.getTmpVarName();
171 for (std::size_t i = 0; i < n; ++i) {
172 if (interpCodes[i] != interpCodes[0]) {
174 << "FlexibleInterpVar::evaluate ERROR: Code Squashing AD does not yet support having "
175 "different interpolation codes for the same class object "
176 << std::endl;
177 }
178 }
179
180 // The PiecewiseInterpolation class is used in the context of HistFactory
181 // models, where is is always used the same way: all RooAbsReals in _lowSet,
182 // _histSet, and also nominal are 1D RooHistFuncs with with same structure.
183 //
184 // Therefore, we can make a big optimization: we get the bin index only once
185 // here in the generated code for PiecewiseInterpolation. Then, we also
186 // rearrange the histogram data in such a way that we can always pass the
187 // same arrays to the free function that implements the interpolation, just
188 // with a dynamic offset calculated from the bin index.
189 RooDataHist const &nomHist = dynamic_cast<RooHistFunc const &>(*arg.nominalHist()).dataHist();
190 int nBins = nomHist.numEntries();
191 std::vector<double> valsNominal;
192 std::vector<double> valsLow;
193 std::vector<double> valsHigh;
194 for (int i = 0; i < nBins; ++i) {
195 valsNominal.push_back(nomHist.weight(i));
196 }
197 for (int i = 0; i < nBins; ++i) {
198 for (std::size_t iParam = 0; iParam < n; ++iParam) {
199 valsLow.push_back(dynamic_cast<RooHistFunc const &>(arg.lowList()[iParam]).dataHist().weight(i));
200 valsHigh.push_back(dynamic_cast<RooHistFunc const &>(arg.highList()[iParam]).dataHist().weight(i));
201 }
202 }
203 std::string idxName = ctx.getTmpVarName();
204 std::string valsNominalStr = ctx.buildArg(valsNominal);
205 std::string valsLowStr = ctx.buildArg(valsLow);
206 std::string valsHighStr = ctx.buildArg(valsHigh);
207 std::string nStr = std::to_string(n);
208 std::string code;
209
210 std::string lowName = ctx.getTmpVarName();
211 std::string highName = ctx.getTmpVarName();
212 std::string nominalName = ctx.getTmpVarName();
213 code +=
214 "unsigned int " + idxName + " = " +
215 nomHist.calculateTreeIndexForCodeSquash(ctx, dynamic_cast<RooHistFunc const &>(*arg.nominalHist()).variables()) +
216 ";\n";
217 code += "double const* " + lowName + " = " + valsLowStr + " + " + nStr + " * " + idxName + ";\n";
218 code += "double const* " + highName + " = " + valsHighStr + " + " + nStr + " * " + idxName + ";\n";
219 code += "double " + nominalName + " = *(" + valsNominalStr + " + " + idxName + ");\n";
220
221 std::string funcCall = ctx.buildCall(mathFunc("flexibleInterp"), interpCodes[0], arg.paramList(), n, lowName,
222 highName, 1.0, nominalName, 0.0);
223 code += "double " + resName + " = " + funcCall + ";\n";
224
225 if (arg.positiveDefinite()) {
226 code += resName + " = " + resName + " < 0 ? 0 : " + resName + ";\n";
227 }
228
229 ctx.addToCodeBody(&arg, code);
230 ctx.addResult(&arg, resName);
231}
232
233////////////////////////////////////////////////////////////////////////////////
234/// This function defines a translation for each RooAbsReal based object that can be used
235/// to express the class as simple C++ code. The function adds the code represented by
236/// each class as an std::string (that is later concatenated with code strings from translate calls)
237/// to form the C++ code that AD tools can understand. Any class that wants to support AD, has to
238/// implement this function.
239///
240/// \param[in] ctx An object to manage auxiliary information for code-squashing. Also takes the
241/// code string that this class outputs into the squashed code through the 'addToCodeBody' function.
243{
244 std::stringstream errorMsg;
245 errorMsg << "Translate function for class \"" << arg.ClassName() << "\" has not yet been implemented.";
246 oocoutE(&arg, Minimization) << errorMsg.str() << std::endl;
247 return ctx.addResult(&arg, "1.0");
248}
249
251{
252 ctx.addResult(&arg, realSumPdfTranslateImpl(ctx, arg, arg.pdfList(), arg.coefList(), true));
253}
254
256{
257 auto const &covI = arg.covarianceMatrixInverse();
258 std::span<const double> covISpan{covI.GetMatrixArray(), static_cast<size_t>(covI.GetNoElements())};
259 ctx.addResult(&arg,
260 ctx.buildCall(mathFunc("multiVarGaussian"), arg.xVec().size(), arg.xVec(), arg.muVec(), covISpan));
261}
262
264{
265 int numPdfs = arg.getNumPdfs();
266
267 // MathFunc call
268
269 // The value of this number should be discussed. Beyound a certain number of
270 // indices MathFunc call becomes more efficient.
271 if (numPdfs > 2) {
272 ctx.addResult(&arg, ctx.buildCall(mathFunc("multipdf"), arg.indexCategory(), arg.getPdfList()));
273
274 std::cout << "MathFunc call used\n";
275
276 } else {
277
278 // Ternary nested expression
279 std::string indexExpr = ctx.getResult(arg.indexCategory());
280
281 // int numPdfs = arg.getNumPdfs();
282 std::string expr;
283
284 for (int i = 0; i < numPdfs; ++i) {
285 RooAbsPdf *pdf = arg.getPdf(i);
286 std::string pdfExpr = ctx.getResult(*pdf);
287
288 expr += "(" + indexExpr + " == " + std::to_string(i) + " ? (" + pdfExpr + ") : ";
289 }
290
291 expr += "0.0";
292 expr += std::string(numPdfs, ')'); // Close all ternary operators
293
294 ctx.addResult(&arg, expr);
295 std::cout << "Ternary expression call used \n";
296 }
297}
298
300{
301 // A RooSimultaneous appears as a node in the compute graph only when its
302 // index category is not an observable (see the "switch mode" in
303 // RooSimultaneous::compileForNormSet()): its value is then the one of the
304 // component selected by the current category state, like for RooMultiPdf.
305 // With an observable index category, the likelihood is decomposed into
306 // per-channel terms and the RooSimultaneous itself is never translated.
307 if (!arg.indexCat().isFundamental()) {
308 std::stringstream errorMsg;
309 errorMsg << "RooSimultaneous \"" << arg.GetName()
310 << "\" with a derived, non-observable index category can't be translated.";
311 oocoutE(&arg, Minimization) << errorMsg.str() << std::endl;
312 throw std::runtime_error(errorMsg.str());
313 }
314
315 std::string const &indexExpr = ctx.getResult(arg.indexCat());
316
317 // Nested ternary expression that selects the pdf matching the category
318 // state, keyed on the state index numbers.
319 std::string expr;
320 std::size_t numStates = 0;
321 for (auto const &nameIdx : arg.indexCat()) {
322 RooAbsPdf *pdf = arg.getPdf(nameIdx.first.c_str());
323 if (!pdf) {
324 continue;
325 }
326 expr += "(" + indexExpr + " == " + std::to_string(nameIdx.second) + " ? (" + ctx.getResult(*pdf) + ") : ";
327 ++numStates;
328 }
329 expr += "0.0" + std::string(numStates, ')');
330
331 ctx.addResult(&arg, expr);
332}
333
334// RooCategory index added.
336{
337 int idx = ctx.observableIndexOf(arg);
338 if (idx < 0) {
339
340 idx = 1;
341 ctx.addVecObs(arg.GetName(), idx);
342 }
343
344 std::string result = std::to_string(arg.getCurrentIndex());
345 ctx.addResult(&arg, result);
346}
347
349{
350 if (arg.list().empty()) {
351 ctx.addResult(&arg, "0.0");
352 }
353 std::string result;
354 if (arg.list().size() > 1)
355 result += "(";
356
357 std::size_t i = 0;
358 for (auto *component : static_range_cast<RooAbsReal *>(arg.list())) {
359
360 if (!dynamic_cast<RooFit::Detail::RooNLLVarNew *>(component) || arg.list().size() == 1) {
361 result += ctx.getResult(*component);
362 ++i;
363 if (i < arg.list().size())
364 result += '+';
365 continue;
366 }
367 result += ctx.buildFunction(*component, ctx.dependsOnData()) + "(params, obs, xlArr)";
368 ++i;
369 if (i < arg.list().size())
370 result += '+';
371 }
372 if (arg.list().size() > 1)
373 result += ')';
374 ctx.addResult(&arg, result);
375}
376
378{
379 arg.fillBuffer();
380 ctx.addResult(&arg, ctx.buildCall(mathFunc("bernstein"), arg.x(), arg.xmin(), arg.xmax(), arg.coefList(),
381 arg.coefList().size()));
382}
383
385{
386 ctx.addResult(&arg,
387 ctx.buildCall(mathFunc("bifurGauss"), arg.getX(), arg.getMean(), arg.getSigmaL(), arg.getSigmaR()));
388}
389
391{
392 ctx.addResult(
393 &arg, ctx.buildCall(mathFunc("cbShape"), arg.getM(), arg.getM0(), arg.getSigma(), arg.getAlpha(), arg.getN()));
394}
395
397{
398 // first bring the range of the variable _x to the normalised range [-1, 1]
399 // calculate sum_k c_k T_k(x) where x is given in the normalised range,
400 // c_0 = 1, and the higher coefficients are given in _coefList
401 double xmax = static_cast<RooAbsRealLValue const &>(arg.x()).getMax(arg.refRangeName());
402 double xmin = static_cast<RooAbsRealLValue const &>(arg.x()).getMin(arg.refRangeName());
403
404 ctx.addResult(&arg,
405 ctx.buildCall(mathFunc("chebychev"), arg.coefList(), arg.coefList().size(), arg.x(), xmin, xmax));
406}
407
409{
410 ctx.addResult(&arg, doubleToString(arg.getVal()));
411}
412
414{
415 ctx.addResult(&arg, ctx.buildCall(mathFunc("constraintSum"), arg.list(), arg.list().size()));
416}
417
418// Generate RooFit codegen wrappers for RooFunctorBinding and similar objects,
419// emitting both the primal function call and its gradient pullback for
420// Clad-based AD.
421template <class RooArg_t>
422void functorCodegenImpl(RooArg_t &arg, RooArgList const &variables, CodegenContext &ctx)
423{
424 if (!arg.function()->HasGradient()) {
425 std::stringstream errorMsg;
426 errorMsg << "Functor wrapped by \"" << arg.GetName() << "\" doesn't provide a gradient function."
427 << " RooFit codegen is therefore not supported.";
428 oocoutE(&arg, InputArguments) << errorMsg.str() << std::endl;
429 throw std::runtime_error(errorMsg.str());
430 }
431
432 std::string funcAddrStr = TString::Format("0x%zx", reinterpret_cast<std::size_t>(arg.function())).Data();
433 std::string wrapperName = "roo_functor_" + funcAddrStr;
434
435 static std::unordered_set<std::string> wrapperNames;
436
437 if (wrapperNames.find(wrapperName) == wrapperNames.end()) {
438
439 wrapperNames.insert(wrapperName);
440
441 std::string pullbackName = wrapperName + "_pullback";
442 std::string nStr = std::to_string(std::size(variables));
443
444 std::string type;
445 if constexpr (std::is_same_v<RooArg_t, RooFunctor1DBinding> || std::is_same_v<RooArg_t, RooFunctor1DPdfBinding>)
446 type = "::ROOT::Math::IGradientFunctionOneDim";
447 else
448 type = "::ROOT::Math::IGradientFunctionMultiDim";
449
450 std::string funcAddrCasted = "reinterpret_cast<" + type + " const *>(" + funcAddrStr + ")";
451
452 std::string code;
453
454 code += "double " + wrapperName +
455 "(double const *x) {\n"
456 " return " +
457 funcAddrCasted +
458 "->operator()(x);\n"
459 "}\n\n"
460 "namespace clad::custom_derivatives {\n\n"
461 "void " +
462 pullbackName +
463 "(double const* x, double d_y, double *d_x) {\n"
464 " double output[" +
465 nStr +
466 "]{};\n"
467 " " +
468 funcAddrCasted +
469 "->Gradient(x, output);\n"
470 " for (int i = 0; i < " +
471 nStr +
472 "; ++i) {\n"
473 " d_x[i] += output[i] * d_y;\n"
474 " }\n"
475 "}\n"
476 "} // namespace clad::custom_derivatives\n";
477
478 gInterpreter->Declare(code.c_str());
479 }
480
481 ctx.addResult(&arg, ctx.buildCall(wrapperName, variables));
482}
483
485{
486 functorCodegenImpl(arg, arg.variable(), ctx);
487}
488
490{
491 functorCodegenImpl(arg, arg.variable(), ctx);
492}
493
495{
496 functorCodegenImpl(arg, arg.variables(), ctx);
497}
498
500{
501 functorCodegenImpl(arg, arg.variables(), ctx);
502}
503
505{
506 ctx.addResult(&arg, ctx.buildCall("TMath::GammaDist", arg.getX(), arg.getGamma(), arg.getMu(), arg.getBeta()));
507}
508
510{
511 arg.getVal(); // to trigger the creation of the TFormula
512 std::string funcName = arg.getUniqueFuncName();
513 ctx.collectFunction(funcName);
514 // We have to force the array type to be "double" because that's what the
515 // declared function wrapped by the TFormula expects.
516 auto inputVar = ctx.buildArg(arg.dependents(), /*arrayType=*/"double");
517 ctx.addResult(&arg, funcName + "(" + inputVar + ")");
518}
519
521{
522 ctx.addResult(&arg, ctx.buildCall(mathFunc("effProd"), arg.eff(), arg.pdf()));
523}
524
526{
527 RooAbsCategory const &cat = arg.cat();
528 int sigCatIndex = cat.lookupIndex(arg.sigCatName());
529 ctx.addResult(&arg, ctx.buildCall(mathFunc("efficiency"), arg.effFunc(), cat, sigCatIndex));
530}
531
533{
534 // Build a call to the stateless exponential defined later.
535 std::string coef;
536 if (arg.negateCoefficient()) {
537 coef += "-";
538 }
539 coef += ctx.getResult(arg.coefficient());
540 ctx.addResult(&arg, "std::exp(" + coef + " * " + ctx.getResult(arg.variable()) + ")");
541}
542
544{
545 // Use the result of the underlying pdf.
546 ctx.addResult(&arg, ctx.getResult(arg.pdf()));
547}
548
550{
551 // Build a call to the stateless gaussian defined later.
552 ctx.addResult(&arg, ctx.buildCall(mathFunc("gaussian"), arg.getX(), arg.getMean(), arg.getSigma()));
553}
554
556{
557 arg.getVal(); // to trigger the creation of the TFormula
558 std::string funcName = arg.getUniqueFuncName();
559 ctx.collectFunction(funcName);
560 // We have to force the array type to be "double" because that's what the
561 // declared function wrapped by the TFormula expects.
562 auto inputVar = ctx.buildArg(arg.dependents(), /*arrayType=*/"double");
563 ctx.addResult(&arg, funcName + "(" + inputVar + ")");
564}
565
567{
568 rooHistTranslateImpl(arg, ctx, arg.getInterpolationOrder(), arg.dataHist(), arg.variables(), false,
569 arg.getCdfBoundaries());
570}
571
573{
574 rooHistTranslateImpl(arg, ctx, arg.getInterpolationOrder(), arg.dataHist(), arg.variables(), !arg.haveUnitNorm(),
575 arg.getCdfBoundaries());
576}
577
579{
580 ctx.addResult(&arg, ctx.buildCall(mathFunc("landau"), arg.getX(), arg.getMean(), arg.getSigma()));
581}
582
584{
585 std::string funcName = arg.useStandardParametrization() ? "logNormalStandard" : "logNormal";
586 ctx.addResult(&arg, ctx.buildCall(mathFunc(funcName), arg.getX(), arg.getShapeK(), arg.getMedian()));
587}
588
589namespace {
590
591void codegenChi2(RooFit::Detail::RooNLLVarNew &arg, CodegenContext &ctx)
592{
593 using FuncMode = RooFit::Detail::RooNLLVarNew::FuncMode;
594
595 std::string resName = RooFit::Detail::makeValidVarName(arg.GetName()) + "Result";
596 ctx.addResult(&arg, resName);
597 ctx.addToGlobalScope("double " + resName + " = 0.0;\n");
598
599 // DataError::None means "no errors": every bin contributes zero.
600 if (arg.chi2ErrorType() == RooDataHist::None) {
601 return;
602 }
603
604 // Compute the per-bin normalization factor (constant with respect to the
605 // loop).
606 std::string normFactor;
607 if (arg.funcMode() == FuncMode::Function) {
608 normFactor = "1.0";
609 } else if (arg.funcMode() == FuncMode::ExtendedPdf) {
610 normFactor = ctx.getResult(*arg.expectedEvents());
611 } else { // Pdf
612 std::string weightSumName = RooFit::Detail::makeValidVarName(arg.GetName()) + "WeightSum";
613 ctx.addToGlobalScope("double " + weightSumName + " = 0.0;\n");
614 {
615 auto scope = ctx.beginLoop(&arg);
616 ctx.addToCodeBody(weightSumName + " += " + ctx.getResult(arg.weightVar()) + ";\n");
617 }
618 normFactor = weightSumName;
619 }
620
621 auto scope = ctx.beginLoop(&arg);
622 const std::string mu =
623 "(" + ctx.getResult(arg.func()) + " * " + ctx.getResult(*arg.binVolumes()) + " * " + normFactor + ")";
624
625 std::string term;
626 switch (arg.chi2ErrorType()) {
627 case RooDataHist::Expected: term = ctx.buildCall(mathFunc("chi2Expected"), mu, arg.weightVar()); break;
629 term = ctx.buildCall(mathFunc("chi2Symmetric"), mu, arg.weightVar(), arg.weightSquaredVar());
630 break;
632 term = ctx.buildCall(mathFunc("chi2Asymmetric"), mu, arg.weightVar(), *arg.weightErrLo(), *arg.weightErrHi());
633 break;
634 default: break;
635 }
636 ctx.addToCodeBody(&arg, resName + " += " + term + ";");
637}
638
639} // namespace
640
641void codegenImpl(RooFit::Detail::RooNLLVarNew &arg, CodegenContext &ctx)
642{
643 if (arg.statistic() == RooFit::Detail::RooNLLVarNew::Statistic::Chi2) {
644 return codegenChi2(arg, ctx);
645 }
646
647 if (arg.binnedL() && !arg.func().getAttribute("BinnedLikelihoodActiveYields")) {
648 std::stringstream errorMsg;
649 errorMsg << "codegen: binned likelihood optimization is only supported when raw pdf "
650 "values can be interpreted as yields."
651 << " This is not the case for HistFactory models written with ROOT versions before 6.26.00";
652 oocoutE(&arg, InputArguments) << errorMsg.str() << std::endl;
653 throw std::runtime_error(errorMsg.str());
654 }
655
656 std::string weightSumName = RooFit::Detail::makeValidVarName(arg.GetName()) + "WeightSum";
657 std::string resName = RooFit::Detail::makeValidVarName(arg.GetName()) + "Result";
658 ctx.addResult(&arg, resName);
659 ctx.addToGlobalScope("double " + weightSumName + " = 0.0;\n");
660 ctx.addToGlobalScope("double " + resName + " = 0.0;\n");
661
662 const bool needWeightSum = arg.expectedEvents() || arg.simCount() > 1;
663
664 if (needWeightSum) {
665 auto scope = ctx.beginLoop(&arg);
666 ctx.addToCodeBody(weightSumName + " += " + ctx.getResult(arg.weightVar()) + ";\n");
667 }
668 if (arg.simCount() > 1) {
669 std::string simCountStr = std::to_string(static_cast<double>(arg.simCount()));
670 ctx.addToCodeBody(resName + " += " + weightSumName + " * std::log(" + simCountStr + ");\n");
671 }
672
673 // Begin loop scope for the observables and weight variable. If the weight
674 // is a scalar, the context will ignore it for the loop scope. The closing
675 // brackets of the loop is written at the end of the scopes lifetime.
676 {
677 auto scope = ctx.beginLoop(&arg);
678 std::string term = ctx.buildCall(mathFunc("nll"), arg.func(), arg.weightVar(), arg.binnedL(), 0);
679 ctx.addToCodeBody(&arg, resName + " += " + term + ";");
680 }
681 if (arg.expectedEvents()) {
682 std::string expected = ctx.getResult(*arg.expectedEvents());
683 ctx.addToCodeBody(resName + " += " + expected + " - " + weightSumName + " * std::log(" + expected + ");\n");
684 }
685}
686
688{
689 // For now just return function/normalization integral.
690 ctx.addResult(&arg, ctx.getResult(arg.pdf()) + "/" + ctx.getResult(arg.normIntegral()));
691}
692
694{
695 std::string const &idx = arg.dataHist().calculateTreeIndexForCodeSquash(ctx, arg.xList());
696 std::string arrName = ctx.buildArg(arg.paramList());
697 std::stringstream result;
698 result << arrName << "[" << idx << "]";
699 if (arg.relParam()) {
700 // get weight[idx] * binv[idx]. Here we get the bin volume for the first element as we assume the distribution to
701 // be binned uniformly.
702 double binV = arg.dataHist().binVolume(0);
703 std::string weightArr = arg.dataHist().declWeightArrayForCodeSquash(ctx, false);
704 result << " * *(" << weightArr << " + " << idx + ") * " << doubleToString(binV);
705 }
706 ctx.addResult(&arg, result.str());
707}
708
710{
711 std::string xName = ctx.getResult(arg.getX());
712 if (!arg.getNoRounding())
713 xName = "std::floor(" + xName + ")";
714
715 ctx.addResult(&arg, ctx.buildCall(mathFunc("poisson"), xName, arg.getMean()));
716}
717
719{
720 const unsigned sz = arg.coefList().size();
721 if (!sz) {
722 ctx.addResult(&arg, std::to_string(arg.lowestOrder() ? 1. : 0.));
723 return;
724 }
725
726 ctx.addResult(&arg, ctx.buildCall(mathFunc("polynomial"), arg.coefList(), sz, arg.lowestOrder(), arg.x()));
727}
728
730{
731 const unsigned sz = arg.coefList().size();
732 if (!sz) {
733 ctx.addResult(&arg, std::to_string(arg.lowestOrder() ? 1. : 0.));
734 return;
735 }
736
737 ctx.addResult(&arg, ctx.buildCall(mathFunc("polynomial<true>"), arg.coefList(), sz, arg.lowestOrder(), arg.x()));
738}
739
741{
742 ctx.addResult(&arg, ctx.buildCall(mathFunc("product"), arg.realComponents(), arg.realComponents().size()));
743}
744
746{
747 ctx.addResult(&arg, ctx.buildCall(mathFunc("ratio"), arg.numerator(), arg.denominator()));
748}
749
750namespace {
751
752std::string codegenIntegral(RooAbsReal &arg, int code, const char *rangeName, CodegenContext &ctx)
753{
754 using Func = std::string (*)(RooAbsReal &, int, const char *, CodegenContext &);
755
756 Func func;
757
758 TClass *tclass = arg.IsA();
759
760 // Cache the overload resolutions
761 static std::unordered_map<TClass *, Func> dispatchMap;
762
763 auto found = dispatchMap.find(tclass);
764
765 if (found != dispatchMap.end()) {
766 func = found->second;
767 } else {
768 // Can probably done with CppInterop in the future to avoid string manipulation.
769 std::stringstream cmd;
770 cmd << "&RooFit::Experimental::CodegenIntegralImplCaller<" << tclass->GetName() << ">::call;";
771 func = reinterpret_cast<Func>(gInterpreter->ProcessLine(cmd.str().c_str()));
772 dispatchMap[tclass] = func;
773 }
774
775 return func(arg, code, rangeName, ctx);
776}
777
778} // namespace
779
781{
782 if (arg.numIntCatVars().empty() && arg.numIntRealVars().empty()) {
783 ctx.addResult(&arg, codegenIntegral(const_cast<RooAbsReal &>(arg.integrand()), arg.mode(), arg.intRange(), ctx));
784 return;
785 }
786
787 if (arg.intVars().size() != 1 || arg.numIntRealVars().size() != 1) {
788 std::stringstream errorMsg;
789 errorMsg << "Only analytical integrals and 1D numeric integrals are supported for AD for class"
790 << arg.integrand().GetName();
791 oocoutE(&arg, Minimization) << errorMsg.str() << std::endl;
792 throw std::runtime_error(errorMsg.str().c_str());
793 }
794
795 auto &intVar = static_cast<RooAbsRealLValue &>(*arg.numIntRealVars()[0]);
796
797 std::string obsName = ctx.getTmpVarName();
798 std::string oldIntVarResult = ctx.getResult(intVar);
799 ctx.addResult(&intVar, "obs[0]");
800
801 std::string funcName = ctx.buildFunction(arg.integrand(), {});
802
803 std::stringstream ss;
804
805 ss << "double " << obsName << "[1];\n";
806
807 std::string resName = RooFit::Detail::makeValidVarName(arg.GetName()) + "Result";
808 ctx.addResult(&arg, resName);
809 ctx.addToGlobalScope("double " + resName + " = 0.0;\n");
810
811 // TODO: once Clad has support for higher-order functions (follow also the
812 // Clad issue #637), we could refactor this code into an actual function
813 // instead of hardcoding it here as a string.
814 ss << "{\n"
815 << " const int n = 1000; // number of sampling points\n"
816 << " double d = " << intVar.getMax(arg.intRange()) << " - " << intVar.getMin(arg.intRange()) << ";\n"
817 << " double eps = d / n;\n"
818 << " #pragma clad checkpoint loop\n"
819 << " for (int i = 0; i < n; ++i) {\n"
820 << " " << obsName << "[0] = " << intVar.getMin(arg.intRange()) << " + eps * i;\n"
821 << " double tmpA = " << funcName << "(params, " << obsName << ", xlArr);\n"
822 << " " << obsName << "[0] = " << intVar.getMin(arg.intRange()) << " + eps * (i + 1);\n"
823 << " double tmpB = " << funcName << "(params, " << obsName << ", xlArr);\n"
824 << " " << resName << " += (tmpA + tmpB) * 0.5 * eps;\n"
825 << " }\n"
826 << "}\n";
827
828 ctx.addToGlobalScope(ss.str());
829
830 ctx.addResult(&intVar, oldIntVarResult);
831}
832
834{
835 ctx.addResult(&arg, realSumPdfTranslateImpl(ctx, arg, arg.funcList(), arg.coefList(), false));
836}
837
839{
840 ctx.addResult(&arg, realSumPdfTranslateImpl(ctx, arg, arg.funcList(), arg.coefList(), false));
841}
842
844{
845 if (!arg.isConstant()) {
846 ctx.addResult(&arg, arg.GetName());
847 }
848 ctx.addResult(&arg, doubleToString(arg.getVal()));
849}
850
852{
853 ctx.addResult(&arg, ctx.buildCall(mathFunc("recursiveFraction"), arg.variables(), arg.variables().size()));
854}
855
857{
858 auto const &interpCodes = arg.interpolationCodes();
859
860 unsigned int n = interpCodes.size();
861
862 int interpCode = interpCodes[0];
863 // To get consistent codes with the PiecewiseInterpolation
864 if (interpCode == 4) {
865 interpCode = 5;
866 }
867
868 for (unsigned int i = 1; i < n; i++) {
869 if (interpCodes[i] != interpCodes[0]) {
871 << "FlexibleInterpVar::evaluate ERROR: Code Squashing AD does not yet support having "
872 "different interpolation codes for the same class object "
873 << std::endl;
874 }
875 }
876
877 std::string const &resName = ctx.buildCall(mathFunc("flexibleInterp"), interpCode, arg.variables(), n, arg.low(),
878 arg.high(), arg.globalBoundary(), arg.nominal(), 1.0);
879 ctx.addResult(&arg, resName);
880}
881
883{
884 ctx.addResult(&arg, "1.0");
885}
886
888{
889 ctx.addResult(&arg, ctx.getResult(arg.function()));
890}
891
892////////////////////////////////////////////////////////////////////////////////
893/// This function defines the analytical integral translation for the class.
894///
895/// \param[in] code The code that decides the integrands.
896/// \param[in] rangeName Name of the normalization range.
897/// \param[in] ctx An object to manage auxiliary information for code-squashing.
898///
899/// \returns The representative code string of the integral for the given object.
900std::string codegenIntegralImpl(RooAbsReal &arg, int, const char *, CodegenContext &)
901{
902 std::stringstream errorMsg;
903 errorMsg << "An analytical integral function for class \"" << arg.ClassName() << "\" has not yet been implemented.";
904 oocoutE(&arg, Minimization) << errorMsg.str() << std::endl;
905 throw std::runtime_error(errorMsg.str().c_str());
906}
907
908std::string codegenIntegralImpl(RooBernstein &arg, int, const char *rangeName, CodegenContext &ctx)
909{
910 arg.fillBuffer(); // to get the right xmin() and xmax()
911 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.x());
912 return ctx.buildCall(mathFunc("bernsteinIntegral"), x.getMin(rangeName), x.getMax(rangeName), arg.xmin(), arg.xmax(),
913 arg.coefList(), arg.coefList().size());
914}
915
916std::string codegenIntegralImpl(RooBifurGauss &arg, int code, const char *rangeName, CodegenContext &ctx)
917{
918 auto &constant = code == 1 ? arg.getMean() : arg.getX();
919 auto &integrand = dynamic_cast<RooAbsRealLValue const &>(code == 1 ? arg.getX() : arg.getMean());
920
921 return ctx.buildCall(mathFunc("bifurGaussIntegral"), integrand.getMin(rangeName), integrand.getMax(rangeName),
922 constant, arg.getSigmaL(), arg.getSigmaR());
923}
924
925std::string codegenIntegralImpl(RooCBShape &arg, int /*code*/, const char *rangeName, CodegenContext &ctx)
926{
927 auto &m = dynamic_cast<RooAbsRealLValue const &>(arg.getM());
928 return ctx.buildCall(mathFunc("cbShapeIntegral"), m.getMin(rangeName), m.getMax(rangeName), arg.getM0(),
929 arg.getSigma(), arg.getAlpha(), arg.getN());
930}
931
932std::string codegenIntegralImpl(RooChebychev &arg, int, const char *rangeName, CodegenContext &ctx)
933{
934 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.x());
935 double xmax = x.getMax(arg.refRangeName());
936 double xmin = x.getMin(arg.refRangeName());
937 unsigned int sz = arg.coefList().size();
938
939 return ctx.buildCall(mathFunc("chebychevIntegral"), arg.coefList(), sz, xmin, xmax, x.getMin(rangeName),
940 x.getMax(rangeName));
941}
942
943std::string codegenIntegralImpl(RooEfficiency &, int, const char *, CodegenContext &)
944{
945 return "1.0";
946}
947
948std::string codegenIntegralImpl(RooExponential &arg, int code, const char *rangeName, CodegenContext &ctx)
949{
950 bool isOverX = code == 1;
951
952 std::string constant;
953 if (arg.negateCoefficient() && isOverX) {
954 constant += "-";
955 }
956 constant += ctx.getResult(isOverX ? arg.coefficient() : arg.variable());
957
958 auto &integrand = dynamic_cast<RooAbsRealLValue const &>(isOverX ? arg.variable() : arg.coefficient());
959
960 double min = integrand.getMin(rangeName);
961 double max = integrand.getMax(rangeName);
962
963 if (!isOverX && arg.negateCoefficient()) {
964 std::swap(min, max);
965 min = -min;
966 max = -max;
967 }
968
969 return ctx.buildCall(mathFunc("exponentialIntegral"), min, max, constant);
970}
971
972std::string codegenIntegralImpl(RooGamma &arg, int, const char *rangeName, CodegenContext &ctx)
973{
974 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.getX());
975 const std::string a =
976 ctx.buildCall("ROOT::Math::gamma_cdf", x.getMax(rangeName), arg.getGamma(), arg.getBeta(), arg.getMu());
977 const std::string b =
978 ctx.buildCall("ROOT::Math::gamma_cdf", x.getMin(rangeName), arg.getGamma(), arg.getBeta(), arg.getMu());
979 return a + " - " + b;
980}
981
982std::string codegenIntegralImpl(RooGaussian &arg, int code, const char *rangeName, CodegenContext &ctx)
983{
984 auto &constant = code == 1 ? arg.getMean() : arg.getX();
985 auto &integrand = dynamic_cast<RooAbsRealLValue const &>(code == 1 ? arg.getX() : arg.getMean());
986
987 return ctx.buildCall(mathFunc("gaussianIntegral"), integrand.getMin(rangeName), integrand.getMax(rangeName),
988 constant, arg.getSigma());
989}
990
991namespace {
992
993std::string rooHistIntegralTranslateImpl(int code, RooAbsArg const &arg, RooDataHist const &dataHist,
994 const RooArgSet &obs, bool histFuncMode)
995{
996 if (((2 << obs.size()) - 1) != code) {
997 oocoutE(&arg, InputArguments) << "RooHistPdf::integral(" << arg.GetName()
998 << ") ERROR: AD currently only supports integrating over all histogram observables."
999 << std::endl;
1000 return "";
1001 }
1002 return doubleToString(dataHist.sum(histFuncMode));
1003}
1004
1005} // namespace
1006
1007std::string codegenIntegralImpl(RooHistFunc &arg, int code, const char *, CodegenContext &)
1008{
1009 return rooHistIntegralTranslateImpl(code, arg, arg.dataHist(), arg.variables(), true);
1010}
1011
1012std::string codegenIntegralImpl(RooHistPdf &arg, int code, const char *, CodegenContext &)
1013{
1014 return rooHistIntegralTranslateImpl(code, arg, arg.dataHist(), arg.variables(), false);
1015}
1016
1017std::string codegenIntegralImpl(RooLandau &arg, int, const char *rangeName, CodegenContext &ctx)
1018{
1019 // Don't do anything with "code". It can only be "1" anyway (see
1020 // implementation of getAnalyticalIntegral).
1021 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.getX());
1022 const std::string a = ctx.buildCall("ROOT::Math::landau_cdf", x.getMax(rangeName), arg.getSigma(), arg.getMean());
1023 const std::string b = ctx.buildCall("ROOT::Math::landau_cdf", x.getMin(rangeName), arg.getSigma(), arg.getMean());
1024 return ctx.getResult(arg.getSigma()) + " * " + "(" + a + " - " + b + ")";
1025}
1026
1027std::string codegenIntegralImpl(RooLognormal &arg, int, const char *rangeName, CodegenContext &ctx)
1028{
1029 std::string funcName = arg.useStandardParametrization() ? "logNormalIntegralStandard" : "logNormalIntegral";
1030 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.getX());
1031 return ctx.buildCall(mathFunc(funcName), x.getMin(rangeName), x.getMax(rangeName), arg.getMedian(), arg.getShapeK());
1032}
1033
1034std::string codegenIntegralImpl(RooMultiVarGaussian &arg, int code, const char *rangeName, CodegenContext &)
1035{
1036 if (code != -1) {
1037 std::stringstream errorMsg;
1038 errorMsg << "Partial integrals over RooMultiVarGaussian are not supported.";
1039 oocoutE(&arg, Minimization) << errorMsg.str() << std::endl;
1040 throw std::runtime_error(errorMsg.str().c_str());
1041 }
1042
1043 return doubleToString(arg.analyticalIntegral(code, rangeName));
1044}
1045
1047{
1048 std::stringstream ss;
1049 ss << arg.outerWrapperName() << "(";
1050 for (std::size_t i = 0; i < arg.nInputTensors(); ++i) {
1051 ss << ctx.buildArg(arg.inputTensorList(i)) << std::endl;
1052 if (i != arg.nInputTensors() - 1) {
1053 ss << ", ";
1054 }
1055 }
1056 ss << ")";
1057
1058 ctx.addResult(&arg, ss.str());
1059}
1060
1061std::string codegenIntegralImpl(RooPoisson &arg, int code, const char *rangeName, CodegenContext &ctx)
1062{
1063 assert(code == 1 || code == 2);
1064 std::string xName = ctx.getResult(arg.getX());
1065 if (!arg.getNoRounding())
1066 xName = "std::floor(" + xName + ")";
1067
1068 auto &integrand = dynamic_cast<RooAbsRealLValue const &>(code == 1 ? arg.getX() : arg.getMean());
1069 // Since the integral function is the same for both codes, we need to make sure the indexed observables do not appear
1070 // in the function if they are not required.
1071 xName = code == 1 ? "0" : xName;
1072 return ctx.buildCall(mathFunc("poissonIntegral"), code, arg.getMean(), xName, integrand.getMin(rangeName),
1073 integrand.getMax(rangeName), arg.getProtectNegativeMean());
1074}
1075
1076std::string codegenIntegralImpl(RooPolyVar &arg, int, const char *rangeName, CodegenContext &ctx)
1077{
1078 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.x());
1079 const double xmin = x.getMin(rangeName);
1080 const double xmax = x.getMax(rangeName);
1081 const unsigned sz = arg.coefList().size();
1082 if (!sz)
1083 return std::to_string(arg.lowestOrder() ? xmax - xmin : 0.0);
1084
1085 return ctx.buildCall(mathFunc("polynomialIntegral"), arg.coefList(), sz, arg.lowestOrder(), xmin, xmax);
1086}
1087
1088std::string codegenIntegralImpl(RooPolynomial &arg, int, const char *rangeName, CodegenContext &ctx)
1089{
1090 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.x());
1091 const double xmin = x.getMin(rangeName);
1092 const double xmax = x.getMax(rangeName);
1093 const unsigned sz = arg.coefList().size();
1094 if (!sz)
1095 return std::to_string(arg.lowestOrder() ? xmax - xmin : 0.0);
1096
1097 return ctx.buildCall(mathFunc("polynomialIntegral<true>"), arg.coefList(), sz, arg.lowestOrder(), xmin, xmax);
1098}
1099
1100std::string codegenIntegralImpl(RooRealSumPdf &arg, int code, const char *rangeName, CodegenContext &ctx)
1101{
1102 // Re-use translate, since integration is linear.
1103 return realSumPdfTranslateImpl(ctx, arg, arg.funcIntListFromCache(code, rangeName), arg.coefList(), false);
1104}
1105
1106std::string codegenIntegralImpl(RooUniform &arg, int code, const char *rangeName, CodegenContext &)
1107{
1108 // The integral of a uniform distribution is static, so we can just hardcode
1109 // the result in a string.
1110 return doubleToString(arg.analyticalIntegral(code, rangeName));
1111}
1112
1113} // namespace RooFit::Experimental
#define b(i)
Definition RSha256.hxx:100
#define a(i)
Definition RSha256.hxx:99
#define oocoutE(o, a)
#define ooccoutE(o, a)
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 char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
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 Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
char name[80]
Definition TGX11.cxx:142
float xmin
float xmax
#define gInterpreter
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
const RooArgList & paramList() const
const RooArgList & dataVars() const
RooDataHist const & dataHist() const
The PiecewiseInterpolation is a class that can morph distributions into each other,...
const RooArgList & highList() const
const RooAbsReal * nominalHist() const
Return pointer to the nominal hist function.
const RooArgList & lowList() const
const RooArgList & paramList() const
const std::vector< int > & interpolationCodes() const
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:76
bool isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:283
virtual bool isFundamental() const
Is this object a fundamental type that can be added to a dataset? Fundamental-type subclasses overrid...
Definition RooAbsArg.h:175
Abstract base class for RooRealVar binning definitions.
Int_t numBins() const
Return number of bins.
virtual double highBound() const =0
virtual double lowBound() const =0
A space to attach TBranches.
value_type lookupIndex(const std::string &stateName) const
Find the index number corresponding to the state name.
Storage_t::size_type size() const
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
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 getMin(const char *name=nullptr) const
Get minimum of currently defined range.
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:107
TClass * IsA() const override
Definition RooAbsReal.h:553
Efficient implementation of a sum of PDFs of the form.
Definition RooAddPdf.h:32
const RooArgList & coefList() const
Definition RooAddPdf.h:73
const RooArgList & pdfList() const
Definition RooAddPdf.h:69
Calculates the sum of a set of RooAbsReal terms, or when constructed with two sets,...
Definition RooAddition.h:27
const RooArgList & list() const
Definition RooAddition.h:42
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
Bernstein basis polynomials are positive-definite in the range [0,1].
void fillBuffer() const
RooAbsRealLValue const & x() const
RooArgList const & coefList() const
double xmax() const
double xmin() const
Bifurcated Gaussian p.d.f with different widths on left and right side of maximum value.
RooAbsReal const & getSigmaL() const
Get the left sigma parameter.
RooAbsReal const & getSigmaR() const
Get the right sigma parameter.
RooAbsReal const & getX() const
Get the x variable.
RooAbsReal const & getMean() const
Get the mean parameter.
PDF implementing the Crystal Ball line shape.
Definition RooCBShape.h:24
RooAbsReal const & getSigma() const
Definition RooCBShape.h:43
RooAbsReal const & getM() const
Definition RooCBShape.h:41
RooAbsReal const & getN() const
Definition RooCBShape.h:45
RooAbsReal const & getM0() const
Definition RooCBShape.h:42
RooAbsReal const & getAlpha() const
Definition RooCBShape.h:44
Object to represent discrete states.
Definition RooCategory.h:28
value_type getCurrentIndex() const final
Return current index.
Definition RooCategory.h:40
Chebychev polynomial p.d.f.
RooAbsReal const & x() const
RooArgList const & coefList() const
const char * refRangeName() const
Represents a constant real-valued object.
Definition RooConstVar.h:23
Calculates the sum of the -(log) likelihoods of a set of RooAbsPfs that represent constraint function...
const RooArgList & list() const
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
double sum(bool correctForBinSize, bool inverseCorr=false) const
Return the sum of the weights of all bins in the histogram.
std::vector< std::unique_ptr< const RooAbsBinning > > const & getBinnings() const
std::string declWeightArrayForCodeSquash(RooFit::Experimental::CodegenContext &ctx, bool correctForBinSize) const
double weight(std::size_t i) const
Return weight of i-th bin.
std::string calculateTreeIndexForCodeSquash(RooFit::Experimental::CodegenContext &ctx, const RooAbsCollection &coords, bool reverse=false) const
double binVolume(std::size_t i) const
Return bin volume of i-th bin.
The class RooEffProd implements the product of a PDF with an efficiency function.
Definition RooEffProd.h:19
RooAbsReal const & pdf() const
Definition RooEffProd.h:31
RooAbsReal const & eff() const
Definition RooEffProd.h:32
A PDF helper class to fit efficiencies parameterized by a supplied function F.
RooAbsCategory const & cat() const
RooAbsReal const & effFunc() const
std::string sigCatName() const
Exponential PDF.
bool negateCoefficient() const
RooAbsReal const & coefficient() const
Get the coefficient "c".
RooAbsReal const & variable() const
Get the x variable.
RooExtendPdf is a wrapper around an existing PDF that adds a parameteric extended likelihood term to ...
RooAbsPdf const & pdf() const
A RooProdPdf with a fixed normalization set can be replaced by this class.
Definition RooProdPdf.h:209
RooArgSet const * partList() const
Definition RooProdPdf.h:264
RooAbsReal const * rearrangedDen() const
Definition RooProdPdf.h:259
RooAbsReal const * rearrangedNum() const
Definition RooProdPdf.h:255
RooAbsReal const & normIntegral() const
RooAbsPdf const & pdf() const
A class to maintain the context for squashing of RooFit models into code.
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 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 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 collectFunction(std::string const &name)
Register a function that is only know to the interpreter to the context.
void addVecObs(const char *key, int idx)
Since the squashed code represents all observables as a single flattened array, it is important to ke...
int observableIndexOf(const RooAbsArg &arg) const
std::string buildArg(RooAbsCollection const &x, std::string const &arrayType="double")
Function to save a RooListProxy as an array in the squashed code.
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 buildCall(std::string const &funcname, Args_t const &...args)
Build the code to call the function with name funcname, passing some arguments.
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
const RooArgList & dependents() const
std::string getUniqueFuncName() const
RooCFunction1Binding is a templated implementation of class RooAbsReal that binds generic C(++) funct...
RooAbsReal const & variable() const
RooAbsReal const & variable() const
RooFunctorBinding makes math functions from ROOT usable in RooFit.
RooArgList const & variables() const
RooFunctorPdfBinding makes math functions from ROOT usable as PDFs in RooFit.
RooArgList const & variables() const
Implementation of the Gamma PDF for RooFit/RooStats.
Definition RooGamma.h:20
RooAbsReal const & getX() const
Definition RooGamma.h:34
RooAbsReal const & getGamma() const
Definition RooGamma.h:35
RooAbsReal const & getBeta() const
Definition RooGamma.h:36
RooAbsReal const & getMu() const
Definition RooGamma.h:37
Plain Gaussian p.d.f.
Definition RooGaussian.h:24
RooAbsReal const & getX() const
Get the x variable.
Definition RooGaussian.h:45
RooAbsReal const & getMean() const
Get the mean parameter.
Definition RooGaussian.h:48
RooAbsReal const & getSigma() const
Get the sigma parameter.
Definition RooGaussian.h:51
Implementation of a probability density function that takes a RooArgList of servers and a C++ express...
const RooArgList & dependents() const
std::string getUniqueFuncName() const
A real-valued function sampled from a multidimensional histogram.
Definition RooHistFunc.h:29
Int_t getInterpolationOrder() const
Return histogram interpolation order.
Definition RooHistFunc.h:67
bool getCdfBoundaries() const
If true, special boundary conditions for c.d.f.s are used.
Definition RooHistFunc.h:83
RooDataHist & dataHist()
Return RooDataHist that is represented.
Definition RooHistFunc.h:43
RooArgSet const & variables() const
A probability density function sampled from a multidimensional histogram.
Definition RooHistPdf.h:29
Int_t getInterpolationOrder() const
Definition RooHistPdf.h:58
RooDataHist & dataHist()
Definition RooHistPdf.h:41
bool haveUnitNorm() const
Definition RooHistPdf.h:81
bool getCdfBoundaries() const
Definition RooHistPdf.h:72
RooArgSet const & variables() const
Definition RooHistPdf.h:97
Landau distribution p.d.f.
Definition RooLandau.h:24
RooAbsReal const & getSigma() const
Definition RooLandau.h:42
RooAbsReal const & getMean() const
Definition RooLandau.h:41
RooAbsReal const & getX() const
Definition RooLandau.h:40
RooFit Lognormal PDF.
bool useStandardParametrization() const
RooAbsReal const & getMedian() const
Get the median parameter.
RooAbsReal const & getShapeK() const
Get the shape parameter.
RooAbsReal const & getX() const
Get the x variable.
The class RooMultiPdf allows for the creation of a RooMultiPdf object, which can switch between previ...
Definition RooMultiPdf.h:9
const RooCategoryProxy & indexCategory() const
Definition RooMultiPdf.h:25
RooAbsPdf * getPdf(int index) const
Definition RooMultiPdf.h:31
int getNumPdfs() const
Definition RooMultiPdf.h:23
const RooListProxy & getPdfList() const
Definition RooMultiPdf.h:26
Multivariate Gaussian p.d.f.
double analyticalIntegral(Int_t code, const char *rangeName=nullptr) const override
Handle full integral here.
const RooArgList & xVec() const
const TMatrixDSym & covarianceMatrixInverse() const
const RooArgList & muVec() const
RooONNXFunc wraps an ONNX model as a RooAbsReal, allowing it to be used as a building block in likeli...
Definition RooONNXFunc.h:21
std::string outerWrapperName() const
Definition RooONNXFunc.h:37
std::size_t nInputTensors() const
Definition RooONNXFunc.h:33
RooArgList const & inputTensorList(int iTensor) const
Definition RooONNXFunc.h:34
A histogram function that assigns scale parameters to every bin.
const RooArgList & paramList() const
const RooArgList & xList() const
const RooDataHist & dataHist() const
bool relParam() const
Poisson pdf.
Definition RooPoisson.h:18
RooAbsReal const & getX() const
Get the x variable.
Definition RooPoisson.h:44
bool getProtectNegativeMean() const
Definition RooPoisson.h:41
bool getNoRounding() const
Definition RooPoisson.h:36
RooAbsReal const & getMean() const
Get the mean parameter.
Definition RooPoisson.h:47
A RooAbsReal implementing a polynomial in terms of a list of RooAbsReal coefficients.
Definition RooPolyVar.h:25
RooArgList const & coefList() const
Definition RooPolyVar.h:38
int lowestOrder() const
Definition RooPolyVar.h:39
RooAbsReal const & x() const
Definition RooPolyVar.h:37
RooPolynomial implements a polynomial p.d.f of the form.
RooAbsReal const & x() const
Get the x variable.
int lowestOrder() const
Return the order for the first coefficient in the list.
RooArgList const & coefList() const
Get the coefficient list.
Represents the product of a given set of RooAbsReal objects.
Definition RooProduct.h:29
const RooArgList & realComponents() const
Definition RooProduct.h:50
Represents the ratio of two RooAbsReal objects.
Definition RooRatio.h:21
RooAbsReal const & numerator() const
Definition RooRatio.h:34
RooAbsReal const & denominator() const
Definition RooRatio.h:35
Performs hybrid numerical/analytical integrals of RooAbsReal objects.
const RooArgSet & numIntRealVars() const
RooArgSet intVars() const
const RooAbsReal & integrand() const
const RooArgSet & numIntCatVars() const
const char * intRange() const
const RooArgList & coefList() const
const RooArgList & funcList() const
Implements a PDF constructed from a sum of functions:
const RooArgList & funcList() const
const RooArgList & funcIntListFromCache(Int_t code, const char *rangeName=nullptr) const
Collect the list of functions to be integrated from the cache.
const RooArgList & coefList() const
Variable that can be changed from the outside.
Definition RooRealVar.h:37
A RooAbsReal implementation that calculates the plain fraction of sum of RooAddPdf components from a ...
RooArgList const & variables() const
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
RooAbsPdf * getPdf(RooStringView catName) const
Return the p.d.f associated with the given index category name.
const RooAbsCategoryLValue & indexCat() const
const std::vector< int > & interpolationCodes() const
const RooListProxy & variables() const
const std::vector< double > & high() const
const std::vector< double > & low() const
Flat p.d.f.
Definition RooUniform.h:24
double analyticalIntegral(Int_t code, const char *rangeName=nullptr) const override
Implement analytical integral.
The RooWrapperPdf is a class that can be used to convert a function into a PDF.
RooAbsReal const & function() const
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
const Element * GetMatrixArray() const override
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:226
const char * Data() const
Definition TString.h:385
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2460
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
std::string makeValidVarName(std::string const &in)
void codegenImpl(RooFit::Detail::RooFixedProdPdf &arg, CodegenContext &ctx)
void functorCodegenImpl(RooArg_t &arg, RooArgList const &variables, CodegenContext &ctx)
std::string codegenIntegralImpl(RooAbsReal &arg, int code, const char *rangeName, CodegenContext &ctx)
This function defines the analytical integral translation for the class.
@ InputArguments
TMarker m
Definition textangle.C:8
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2335