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
115realSumPdfTranslateImpl(CodegenContext &ctx, RooArgList const &funcList, RooArgList const &coefList, bool normalize)
116{
117 bool noLastCoeff = funcList.size() != coefList.size();
118
119 // Decide the scope from the inputs rather than from the RooRealSumPdf
120 // itself: this function is also used for the integral of the sum, whose
121 // inputs are the integrals of the components. Those usually don't depend
122 // on the data even though the sum does, and then the code must not end up
123 // inside the event loop, because the integral is also the expected number
124 // of events that the extended likelihood uses after the loop.
125 bool scopeIndependent = true;
126 for (RooAbsArg const *func : funcList) {
127 scopeIndependent = scopeIndependent && ctx.isScopeIndependent(func);
128 }
129 for (RooAbsArg const *coef : coefList) {
130 scopeIndependent = scopeIndependent && ctx.isScopeIndependent(coef);
131 }
132 auto addCode = [&](std::string const &code) { ctx.addToCodeBody(code, scopeIndependent); };
133
134 std::string const &funcName = ctx.buildArg(funcList);
135 std::string const &coeffName = ctx.buildArg(coefList);
136 std::string const &coeffSize = std::to_string(coefList.size());
137
138 std::string sum = ctx.getTmpVarName();
139 std::string coeffSum = ctx.getTmpVarName();
140 addCode("double " + sum + " = 0;\ndouble " + coeffSum + "= 0;\n");
141
142 std::string iterator = "i_" + ctx.getTmpVarName();
143 std::string subscriptExpr = "[" + iterator + "]";
144
145 std::string code = "for(int " + iterator + " = 0; " + iterator + " < " + coeffSize + "; " + iterator + "++) {\n" +
146 sum + " += " + funcName + subscriptExpr + " * " + coeffName + subscriptExpr + ";\n";
147 code += coeffSum + " += " + coeffName + subscriptExpr + ";\n";
148 code += "}\n";
149
150 if (noLastCoeff) {
151 code += sum + " += " + funcName + "[" + coeffSize + "]" + " * (1 - " + coeffSum + ");\n";
152 } else if (normalize) {
153 code += sum + " /= " + coeffSum + ";\n";
154 }
155 addCode(code);
156
157 return sum;
158}
159
160} // namespace
161
163{
164 if (arg.isRearranged()) {
165 ctx.addResult(&arg, ctx.buildCall(mathFunc("ratio"), *arg.rearrangedNum(), *arg.rearrangedDen()));
166 } else {
167 ctx.addResult(&arg, ctx.buildCall(mathFunc("product"), *arg.partList(), arg.partList()->size()));
168 }
169}
170
172{
173 std::string const &idx = arg.dataHist().calculateTreeIndexForCodeSquash(ctx, arg.dataVars(), true);
174 std::string const &paramNames = ctx.buildArg(arg.paramList());
175
176 ctx.addResult(&arg, paramNames + "[" + idx + "]");
177}
178
180{
181 auto const &interpCodes = arg.interpolationCodes();
182
183 std::size_t n = interpCodes.size();
184
185 std::string resName = "total_" + ctx.getTmpVarName();
186 for (std::size_t i = 0; i < n; ++i) {
187 if (interpCodes[i] != interpCodes[0]) {
189 << "FlexibleInterpVar::evaluate ERROR: Code Squashing AD does not yet support having "
190 "different interpolation codes for the same class object "
191 << std::endl;
192 }
193 }
194
195 // The PiecewiseInterpolation class is used in the context of HistFactory
196 // models, where is is always used the same way: all RooAbsReals in _lowSet,
197 // _histSet, and also nominal are 1D RooHistFuncs with with same structure.
198 //
199 // Therefore, we can make a big optimization: we get the bin index only once
200 // here in the generated code for PiecewiseInterpolation. Then, we also
201 // rearrange the histogram data in such a way that we can always pass the
202 // same arrays to the free function that implements the interpolation, just
203 // with a dynamic offset calculated from the bin index.
204 RooDataHist const &nomHist = dynamic_cast<RooHistFunc const &>(*arg.nominalHist()).dataHist();
205 int nBins = nomHist.numEntries();
206 std::vector<double> valsNominal;
207 std::vector<double> valsLow;
208 std::vector<double> valsHigh;
209 valsNominal.reserve(nBins);
210 for (int i = 0; i < nBins; ++i) {
211 valsNominal.push_back(nomHist.weight(i));
212 }
213 for (int i = 0; i < nBins; ++i) {
214 for (std::size_t iParam = 0; iParam < n; ++iParam) {
215 valsLow.push_back(dynamic_cast<RooHistFunc const &>(arg.lowList()[iParam]).dataHist().weight(i));
216 valsHigh.push_back(dynamic_cast<RooHistFunc const &>(arg.highList()[iParam]).dataHist().weight(i));
217 }
218 }
219 std::string idxName = ctx.getTmpVarName();
220 std::string valsNominalStr = ctx.buildArg(valsNominal);
221 std::string valsLowStr = ctx.buildArg(valsLow);
222 std::string valsHighStr = ctx.buildArg(valsHigh);
223 std::string nStr = std::to_string(n);
224 std::string code;
225
226 std::string lowName = ctx.getTmpVarName();
227 std::string highName = ctx.getTmpVarName();
228 std::string nominalName = ctx.getTmpVarName();
229 code +=
230 "unsigned int " + idxName + " = " +
231 nomHist.calculateTreeIndexForCodeSquash(ctx, dynamic_cast<RooHistFunc const &>(*arg.nominalHist()).variables()) +
232 ";\n";
233 code += "double const* " + lowName + " = " + valsLowStr + " + " + nStr + " * " + idxName + ";\n";
234 code += "double const* " + highName + " = " + valsHighStr + " + " + nStr + " * " + idxName + ";\n";
235 code += "double " + nominalName + " = *(" + valsNominalStr + " + " + idxName + ");\n";
236
237 std::string funcCall = ctx.buildCall(mathFunc("flexibleInterp"), interpCodes[0], arg.paramList(), n, lowName,
238 highName, 1.0, nominalName, 0.0);
239 code += "double " + resName + " = " + funcCall + ";\n";
240
241 if (arg.positiveDefinite()) {
242 code += resName + " = " + resName + " < 0 ? 0 : " + resName + ";\n";
243 }
244
245 ctx.addToCodeBody(&arg, code);
246 ctx.addResult(&arg, resName);
247}
248
249////////////////////////////////////////////////////////////////////////////////
250/// This function defines a translation for each RooAbsReal based object that can be used
251/// to express the class as simple C++ code. The function adds the code represented by
252/// each class as an std::string (that is later concatenated with code strings from translate calls)
253/// to form the C++ code that AD tools can understand. Any class that wants to support AD, has to
254/// implement this function.
255///
256/// \param[in] ctx An object to manage auxiliary information for code-squashing. Also takes the
257/// code string that this class outputs into the squashed code through the 'addToCodeBody' function.
259{
260 std::stringstream errorMsg;
261 errorMsg << "Translate function for class \"" << arg.ClassName() << "\" has not yet been implemented.";
262 oocoutE(&arg, Minimization) << errorMsg.str() << std::endl;
263 return ctx.addResult(&arg, "1.0");
264}
265
267{
268 ctx.addResult(&arg, realSumPdfTranslateImpl(ctx, arg.pdfList(), arg.coefList(), true));
269}
270
272{
273 auto const &covI = arg.covarianceMatrixInverse();
274 std::span<const double> covISpan{covI.GetMatrixArray(), static_cast<size_t>(covI.GetNoElements())};
275 ctx.addResult(&arg,
276 ctx.buildCall(mathFunc("multiVarGaussian"), arg.xVec().size(), arg.xVec(), arg.muVec(), covISpan));
277}
278
280{
281 int numPdfs = arg.getNumPdfs();
282
283 // MathFunc call
284
285 // The value of this number should be discussed. Beyound a certain number of
286 // indices MathFunc call becomes more efficient.
287 if (numPdfs > 2) {
288 ctx.addResult(&arg, ctx.buildCall(mathFunc("multipdf"), arg.indexCategory(), arg.getPdfList()));
289
290 std::cout << "MathFunc call used\n";
291
292 } else {
293
294 // Ternary nested expression
295 std::string indexExpr = ctx.getResult(arg.indexCategory());
296
297 // int numPdfs = arg.getNumPdfs();
298 std::string expr;
299
300 for (int i = 0; i < numPdfs; ++i) {
301 RooAbsPdf *pdf = arg.getPdf(i);
302 std::string pdfExpr = ctx.getResult(*pdf);
303
304 expr += "(" + indexExpr + " == " + std::to_string(i) + " ? (" + pdfExpr + ") : ";
305 }
306
307 expr += "0.0";
308 expr += std::string(numPdfs, ')'); // Close all ternary operators
309
310 ctx.addResult(&arg, expr);
311 std::cout << "Ternary expression call used \n";
312 }
313}
314
316{
317 // A RooSimultaneous appears as a node in the compute graph only when its
318 // index category is not an observable (see the "switch mode" in
319 // RooSimultaneous::compileForNormSet()): its value is then the one of the
320 // component selected by the current category state, like for RooMultiPdf.
321 // With an observable index category, the likelihood is decomposed into
322 // per-channel terms and the RooSimultaneous itself is never translated.
323 if (!arg.indexCat().isFundamental()) {
324 std::stringstream errorMsg;
325 errorMsg << "RooSimultaneous \"" << arg.GetName()
326 << "\" with a derived, non-observable index category can't be translated.";
327 oocoutE(&arg, Minimization) << errorMsg.str() << std::endl;
328 throw std::runtime_error(errorMsg.str());
329 }
330
331 std::string const &indexExpr = ctx.getResult(arg.indexCat());
332
333 // Nested ternary expression that selects the pdf matching the category
334 // state, keyed on the state index numbers.
335 std::string expr;
336 std::size_t numStates = 0;
337 for (auto const &nameIdx : arg.indexCat()) {
338 RooAbsPdf *pdf = arg.getPdf(nameIdx.first.c_str());
339 if (!pdf) {
340 continue;
341 }
342 expr += "(" + indexExpr + " == " + std::to_string(nameIdx.second) + " ? (" + ctx.getResult(*pdf) + ") : ";
343 ++numStates;
344 }
345 expr += "0.0" + std::string(numStates, ')');
346
347 ctx.addResult(&arg, expr);
348}
349
350// RooCategory index added.
352{
353 int idx = ctx.observableIndexOf(arg);
354 if (idx < 0) {
355
356 idx = 1;
357 ctx.addVecObs(arg.GetName(), idx);
358 }
359
360 std::string result = std::to_string(arg.getCurrentIndex());
361 ctx.addResult(&arg, result);
362}
363
365{
366 if (arg.list().empty()) {
367 ctx.addResult(&arg, "0.0");
368 }
369 std::string result;
370 if (arg.list().size() > 1)
371 result += "(";
372
373 std::size_t i = 0;
374 for (auto *component : static_range_cast<RooAbsReal *>(arg.list())) {
375
376 if (!dynamic_cast<RooFit::Detail::RooNLLVarNew *>(component) || arg.list().size() == 1) {
377 result += ctx.getResult(*component);
378 ++i;
379 if (i < arg.list().size())
380 result += '+';
381 continue;
382 }
383 result += ctx.buildFunction(*component, ctx.dependsOnData()) + "(params, obs, xlArr)";
384 ++i;
385 if (i < arg.list().size())
386 result += '+';
387 }
388 if (arg.list().size() > 1)
389 result += ')';
390 ctx.addResult(&arg, result);
391}
392
394{
395 arg.fillBuffer();
396 ctx.addResult(&arg, ctx.buildCall(mathFunc("bernstein"), arg.x(), arg.xmin(), arg.xmax(), arg.coefList(),
397 arg.coefList().size()));
398}
399
401{
402 ctx.addResult(&arg,
403 ctx.buildCall(mathFunc("bifurGauss"), arg.getX(), arg.getMean(), arg.getSigmaL(), arg.getSigmaR()));
404}
405
407{
408 ctx.addResult(
409 &arg, ctx.buildCall(mathFunc("cbShape"), arg.getM(), arg.getM0(), arg.getSigma(), arg.getAlpha(), arg.getN()));
410}
411
413{
414 // first bring the range of the variable _x to the normalised range [-1, 1]
415 // calculate sum_k c_k T_k(x) where x is given in the normalised range,
416 // c_0 = 1, and the higher coefficients are given in _coefList
417 double xmax = static_cast<RooAbsRealLValue const &>(arg.x()).getMax(arg.refRangeName());
418 double xmin = static_cast<RooAbsRealLValue const &>(arg.x()).getMin(arg.refRangeName());
419
420 ctx.addResult(&arg,
421 ctx.buildCall(mathFunc("chebychev"), arg.coefList(), arg.coefList().size(), arg.x(), xmin, xmax));
422}
423
425{
426 ctx.addResult(&arg, doubleToString(arg.getVal()));
427}
428
430{
431 ctx.addResult(&arg, ctx.buildCall(mathFunc("constraintSum"), arg.list(), arg.list().size()));
432}
433
434// Generate RooFit codegen wrappers for RooFunctorBinding and similar objects,
435// emitting both the primal function call and its gradient pullback for
436// Clad-based AD.
437template <class RooArg_t>
438void functorCodegenImpl(RooArg_t &arg, RooArgList const &variables, CodegenContext &ctx)
439{
440 if (!arg.function()->HasGradient()) {
441 std::stringstream errorMsg;
442 errorMsg << "Functor wrapped by \"" << arg.GetName() << "\" doesn't provide a gradient function."
443 << " RooFit codegen is therefore not supported.";
444 oocoutE(&arg, InputArguments) << errorMsg.str() << std::endl;
445 throw std::runtime_error(errorMsg.str());
446 }
447
448 std::string funcAddrStr = TString::Format("0x%zx", reinterpret_cast<std::size_t>(arg.function())).Data();
449 std::string wrapperName = "roo_functor_" + funcAddrStr;
450
451 static std::unordered_set<std::string> wrapperNames;
452
453 if (wrapperNames.find(wrapperName) == wrapperNames.end()) {
454
455 wrapperNames.insert(wrapperName);
456
457 std::string pullbackName = wrapperName + "_pullback";
458 std::string nStr = std::to_string(std::size(variables));
459
460 std::string type;
461 if constexpr (std::is_same_v<RooArg_t, RooFunctor1DBinding> || std::is_same_v<RooArg_t, RooFunctor1DPdfBinding>) {
462 type = "::ROOT::Math::IGradientFunctionOneDim";
463 } else {
464 type = "::ROOT::Math::IGradientFunctionMultiDim";
465 }
466
467 std::string funcAddrCasted = "reinterpret_cast<" + type + " const *>(" + funcAddrStr + ")";
468
469 std::string code;
470
471 code += "double " + wrapperName +
472 "(double const *x) {\n"
473 " return " +
474 funcAddrCasted +
475 "->operator()(x);\n"
476 "}\n\n"
477 "namespace clad::custom_derivatives {\n\n"
478 "void " +
479 pullbackName +
480 "(double const* x, double d_y, double *d_x) {\n"
481 " double output[" +
482 nStr +
483 "]{};\n"
484 " " +
485 funcAddrCasted +
486 "->Gradient(x, output);\n"
487 " for (int i = 0; i < " +
488 nStr +
489 "; ++i) {\n"
490 " d_x[i] += output[i] * d_y;\n"
491 " }\n"
492 "}\n"
493 "} // namespace clad::custom_derivatives\n";
494
495 gInterpreter->Declare(code.c_str());
496 }
497
498 ctx.addResult(&arg, ctx.buildCall(wrapperName, variables));
499}
500
502{
503 functorCodegenImpl(arg, arg.variable(), ctx);
504}
505
507{
508 functorCodegenImpl(arg, arg.variable(), ctx);
509}
510
512{
513 functorCodegenImpl(arg, arg.variables(), ctx);
514}
515
517{
518 functorCodegenImpl(arg, arg.variables(), ctx);
519}
520
522{
523 ctx.addResult(&arg, ctx.buildCall("TMath::GammaDist", arg.getX(), arg.getGamma(), arg.getMu(), arg.getBeta()));
524}
525
527{
528 arg.getVal(); // to trigger the creation of the TFormula
529 std::string funcName = arg.getUniqueFuncName();
530 ctx.collectFunction(funcName);
531 // We have to force the array type to be "double" because that's what the
532 // declared function wrapped by the TFormula expects.
533 auto inputVar = ctx.buildArg(arg.dependents(), /*arrayType=*/"double");
534 ctx.addResult(&arg, funcName + "(" + inputVar + ")");
535}
536
538{
539 ctx.addResult(&arg, ctx.buildCall(mathFunc("effProd"), arg.eff(), arg.pdf()));
540}
541
543{
544 RooAbsCategory const &cat = arg.cat();
545 int sigCatIndex = cat.lookupIndex(arg.sigCatName());
546 ctx.addResult(&arg, ctx.buildCall(mathFunc("efficiency"), arg.effFunc(), cat, sigCatIndex));
547}
548
550{
551 // Build a call to the stateless exponential defined later.
552 std::string coef;
553 if (arg.negateCoefficient()) {
554 coef += "-";
555 }
556 coef += ctx.getResult(arg.coefficient());
557 ctx.addResult(&arg, "std::exp(" + coef + " * " + ctx.getResult(arg.variable()) + ")");
558}
559
561{
562 // Use the result of the underlying pdf.
563 ctx.addResult(&arg, ctx.getResult(arg.pdf()));
564}
565
567{
568 // Build a call to the stateless gaussian defined later.
569 ctx.addResult(&arg, ctx.buildCall(mathFunc("gaussian"), arg.getX(), arg.getMean(), arg.getSigma()));
570}
571
573{
574 arg.getVal(); // to trigger the creation of the TFormula
575 std::string funcName = arg.getUniqueFuncName();
576 ctx.collectFunction(funcName);
577 // We have to force the array type to be "double" because that's what the
578 // declared function wrapped by the TFormula expects.
579 auto inputVar = ctx.buildArg(arg.dependents(), /*arrayType=*/"double");
580 ctx.addResult(&arg, funcName + "(" + inputVar + ")");
581}
582
584{
585 rooHistTranslateImpl(arg, ctx, arg.getInterpolationOrder(), arg.dataHist(), arg.variables(), false,
586 arg.getCdfBoundaries());
587}
588
590{
591 rooHistTranslateImpl(arg, ctx, arg.getInterpolationOrder(), arg.dataHist(), arg.variables(), !arg.haveUnitNorm(),
592 arg.getCdfBoundaries());
593}
594
596{
597 ctx.addResult(&arg, ctx.buildCall(mathFunc("landau"), arg.getX(), arg.getMean(), arg.getSigma()));
598}
599
601{
602 std::string funcName = arg.useStandardParametrization() ? "logNormalStandard" : "logNormal";
603 ctx.addResult(&arg, ctx.buildCall(mathFunc(funcName), arg.getX(), arg.getShapeK(), arg.getMedian()));
604}
605
606namespace {
607
608void codegenChi2(RooFit::Detail::RooNLLVarNew &arg, CodegenContext &ctx)
609{
610 using FuncMode = RooFit::Detail::RooNLLVarNew::FuncMode;
611
612 std::string resName = RooFit::Detail::makeValidVarName(arg.GetName()) + "Result";
613 ctx.addResult(&arg, resName);
614 ctx.addToGlobalScope("double " + resName + " = 0.0;\n");
615
616 // DataError::None means "no errors": every bin contributes zero.
617 if (arg.chi2ErrorType() == RooDataHist::None) {
618 return;
619 }
620
621 // Compute the per-bin normalization factor (constant with respect to the
622 // loop).
623 std::string normFactor;
624 if (arg.funcMode() == FuncMode::Function) {
625 normFactor = "1.0";
626 } else if (arg.funcMode() == FuncMode::ExtendedPdf) {
627 normFactor = ctx.getResult(*arg.expectedEvents());
628 } else { // Pdf
629 std::string weightSumName = RooFit::Detail::makeValidVarName(arg.GetName()) + "WeightSum";
630 ctx.addToGlobalScope("double " + weightSumName + " = 0.0;\n");
631 {
632 auto scope = ctx.beginLoop(&arg);
633 ctx.addToCodeBody(weightSumName + " += " + ctx.getResult(arg.weightVar()) + ";\n");
634 }
635 normFactor = weightSumName;
636 }
637
638 auto scope = ctx.beginLoop(&arg);
639 const std::string mu =
640 "(" + ctx.getResult(arg.func()) + " * " + ctx.getResult(*arg.binVolumes()) + " * " + normFactor + ")";
641
642 std::string term;
643 switch (arg.chi2ErrorType()) {
644 case RooDataHist::Expected: term = ctx.buildCall(mathFunc("chi2Expected"), mu, arg.weightVar()); break;
646 term = ctx.buildCall(mathFunc("chi2Symmetric"), mu, arg.weightVar(), arg.weightSquaredVar());
647 break;
649 term = ctx.buildCall(mathFunc("chi2Asymmetric"), mu, arg.weightVar(), *arg.weightErrLo(), *arg.weightErrHi());
650 break;
651 default: break;
652 }
653 ctx.addToCodeBody(&arg, resName + " += " + term + ";");
654}
655
656} // namespace
657
658void codegenImpl(RooFit::Detail::RooNLLVarNew &arg, CodegenContext &ctx)
659{
660 if (arg.statistic() == RooFit::Detail::RooNLLVarNew::Statistic::Chi2) {
661 return codegenChi2(arg, ctx);
662 }
663
664 if (arg.binnedL() && !arg.func().getAttribute("BinnedLikelihoodActiveYields")) {
665 std::stringstream errorMsg;
666 errorMsg << "codegen: binned likelihood optimization is only supported when raw pdf "
667 "values can be interpreted as yields."
668 << " This is not the case for HistFactory models written with ROOT versions before 6.26.00";
669 oocoutE(&arg, InputArguments) << errorMsg.str() << std::endl;
670 throw std::runtime_error(errorMsg.str());
671 }
672
673 std::string weightSumName = RooFit::Detail::makeValidVarName(arg.GetName()) + "WeightSum";
674 std::string resName = RooFit::Detail::makeValidVarName(arg.GetName()) + "Result";
675 ctx.addResult(&arg, resName);
676 ctx.addToGlobalScope("double " + weightSumName + " = 0.0;\n");
677 ctx.addToGlobalScope("double " + resName + " = 0.0;\n");
678
679 const bool needWeightSum = arg.expectedEvents() || arg.simCount() > 1;
680
681 if (needWeightSum) {
682 auto scope = ctx.beginLoop(&arg);
683 ctx.addToCodeBody(weightSumName + " += " + ctx.getResult(arg.weightVar()) + ";\n");
684 }
685 if (arg.simCount() > 1) {
686 std::string simCountStr = std::to_string(static_cast<double>(arg.simCount()));
687 ctx.addToCodeBody(resName + " += " + weightSumName + " * std::log(" + simCountStr + ");\n");
688 }
689
690 // Begin loop scope for the observables and weight variable. If the weight
691 // is a scalar, the context will ignore it for the loop scope. The closing
692 // brackets of the loop is written at the end of the scopes lifetime.
693 {
694 auto scope = ctx.beginLoop(&arg);
695 std::string term = ctx.buildCall(mathFunc("nll"), arg.func(), arg.weightVar(), arg.binnedL(), 0);
696 ctx.addToCodeBody(&arg, resName + " += " + term + ";");
697 }
698 if (arg.expectedEvents()) {
699 std::string expected = ctx.getResult(*arg.expectedEvents());
700 ctx.addToCodeBody(resName + " += " + expected + " - " + weightSumName + " * std::log(" + expected + ");\n");
701 }
702}
703
705{
706 // For now just return function/normalization integral.
707 ctx.addResult(&arg, ctx.getResult(arg.pdf()) + "/" + ctx.getResult(arg.normIntegral()));
708}
709
711{
712 std::string const &idx = arg.dataHist().calculateTreeIndexForCodeSquash(ctx, arg.xList());
713 std::string arrName = ctx.buildArg(arg.paramList());
714 std::stringstream result;
715 result << arrName << "[" << idx << "]";
716 if (arg.relParam()) {
717 // get weight[idx] * binv[idx]. Here we get the bin volume for the first element as we assume the distribution to
718 // be binned uniformly.
719 double binV = arg.dataHist().binVolume(0);
720 std::string weightArr = arg.dataHist().declWeightArrayForCodeSquash(ctx, false);
721 result << " * *(" << weightArr << " + " << idx + ") * " << doubleToString(binV);
722 }
723 ctx.addResult(&arg, result.str());
724}
725
727{
728 std::string xName = ctx.getResult(arg.getX());
729 if (!arg.getNoRounding())
730 xName = "std::floor(" + xName + ")";
731
732 ctx.addResult(&arg, ctx.buildCall(mathFunc("poisson"), xName, arg.getMean()));
733}
734
736{
737 const unsigned sz = arg.coefList().size();
738 if (!sz) {
739 ctx.addResult(&arg, std::to_string(arg.lowestOrder() ? 1. : 0.));
740 return;
741 }
742
743 ctx.addResult(&arg, ctx.buildCall(mathFunc("polynomial"), arg.coefList(), sz, arg.lowestOrder(), arg.x()));
744}
745
747{
748 const unsigned sz = arg.coefList().size();
749 if (!sz) {
750 ctx.addResult(&arg, std::to_string(arg.lowestOrder() ? 1. : 0.));
751 return;
752 }
753
754 ctx.addResult(&arg, ctx.buildCall(mathFunc("polynomial<true>"), arg.coefList(), sz, arg.lowestOrder(), arg.x()));
755}
756
758{
759 ctx.addResult(&arg, ctx.buildCall(mathFunc("product"), arg.realComponents(), arg.realComponents().size()));
760}
761
763{
764 ctx.addResult(&arg, ctx.buildCall(mathFunc("ratio"), arg.numerator(), arg.denominator()));
765}
766
767namespace {
768
769std::string codegenIntegral(RooAbsReal &arg, int code, const char *rangeName, CodegenContext &ctx)
770{
771 using Func = std::string (*)(RooAbsReal &, int, const char *, CodegenContext &);
772
773 Func func;
774
775 TClass *tclass = arg.IsA();
776
777 // Cache the overload resolutions
778 static std::unordered_map<TClass *, Func> dispatchMap;
779
780 auto found = dispatchMap.find(tclass);
781
782 if (found != dispatchMap.end()) {
783 func = found->second;
784 } else {
785 // Can probably done with CppInterop in the future to avoid string manipulation.
786 std::stringstream cmd;
787 cmd << "&RooFit::Experimental::CodegenIntegralImplCaller<" << tclass->GetName() << ">::call;";
788 func = reinterpret_cast<Func>(gInterpreter->ProcessLine(cmd.str().c_str()));
789 dispatchMap[tclass] = func;
790 }
791
792 return func(arg, code, rangeName, ctx);
793}
794
795} // namespace
796
798{
799 if (arg.numIntCatVars().empty() && arg.numIntRealVars().empty()) {
800 ctx.addResult(&arg, codegenIntegral(const_cast<RooAbsReal &>(arg.integrand()), arg.mode(), arg.intRange(), ctx));
801 return;
802 }
803
804 if (arg.intVars().size() != 1 || arg.numIntRealVars().size() != 1) {
805 std::stringstream errorMsg;
806 errorMsg << "Only analytical integrals and 1D numeric integrals are supported for AD for class"
807 << arg.integrand().GetName();
808 oocoutE(&arg, Minimization) << errorMsg.str() << std::endl;
809 throw std::runtime_error(errorMsg.str().c_str());
810 }
811
812 auto &intVar = static_cast<RooAbsRealLValue &>(*arg.numIntRealVars()[0]);
813
814 std::string obsName = ctx.getTmpVarName();
815 std::string oldIntVarResult = ctx.getResult(intVar);
816 ctx.addResult(&intVar, "obs[0]");
817
818 std::string funcName = ctx.buildFunction(arg.integrand(), {});
819
820 std::stringstream ss;
821
822 ss << "double " << obsName << "[1];\n";
823
824 std::string resName = RooFit::Detail::makeValidVarName(arg.GetName()) + "Result";
825 ctx.addResult(&arg, resName);
826 ctx.addToGlobalScope("double " + resName + " = 0.0;\n");
827
828 // TODO: once Clad has support for higher-order functions (follow also the
829 // Clad issue #637), we could refactor this code into an actual function
830 // instead of hardcoding it here as a string.
831 ss << "{\n"
832 << " const int n = 1000; // number of sampling points\n"
833 << " double d = " << intVar.getMax(arg.intRange()) << " - " << intVar.getMin(arg.intRange()) << ";\n"
834 << " double eps = d / n;\n"
835 << " #pragma clad checkpoint loop\n"
836 << " for (int i = 0; i < n; ++i) {\n"
837 << " " << obsName << "[0] = " << intVar.getMin(arg.intRange()) << " + eps * i;\n"
838 << " double tmpA = " << funcName << "(params, " << obsName << ", xlArr);\n"
839 << " " << obsName << "[0] = " << intVar.getMin(arg.intRange()) << " + eps * (i + 1);\n"
840 << " double tmpB = " << funcName << "(params, " << obsName << ", xlArr);\n"
841 << " " << resName << " += (tmpA + tmpB) * 0.5 * eps;\n"
842 << " }\n"
843 << "}\n";
844
845 ctx.addToGlobalScope(ss.str());
846
847 ctx.addResult(&intVar, oldIntVarResult);
848}
849
851{
852 ctx.addResult(&arg, realSumPdfTranslateImpl(ctx, arg.funcList(), arg.coefList(), false));
853}
854
856{
857 ctx.addResult(&arg, realSumPdfTranslateImpl(ctx, arg.funcList(), arg.coefList(), false));
858}
859
861{
862 if (!arg.isConstant()) {
863 ctx.addResult(&arg, arg.GetName());
864 }
865 ctx.addResult(&arg, doubleToString(arg.getVal()));
866}
867
869{
870 ctx.addResult(&arg, ctx.buildCall(mathFunc("recursiveFraction"), arg.variables(), arg.variables().size()));
871}
872
874{
875 auto const &interpCodes = arg.interpolationCodes();
876
877 unsigned int n = interpCodes.size();
878
879 int interpCode = interpCodes[0];
880 // To get consistent codes with the PiecewiseInterpolation
881 if (interpCode == 4) {
882 interpCode = 5;
883 }
884
885 for (unsigned int i = 1; i < n; i++) {
886 if (interpCodes[i] != interpCodes[0]) {
888 << "FlexibleInterpVar::evaluate ERROR: Code Squashing AD does not yet support having "
889 "different interpolation codes for the same class object "
890 << std::endl;
891 }
892 }
893
894 std::string const &resName = ctx.buildCall(mathFunc("flexibleInterp"), interpCode, arg.variables(), n, arg.low(),
895 arg.high(), arg.globalBoundary(), arg.nominal(), 1.0);
896 ctx.addResult(&arg, resName);
897}
898
900{
901 ctx.addResult(&arg, "1.0");
902}
903
905{
906 ctx.addResult(&arg, ctx.getResult(arg.function()));
907}
908
909////////////////////////////////////////////////////////////////////////////////
910/// This function defines the analytical integral translation for the class.
911///
912/// \param[in] code The code that decides the integrands.
913/// \param[in] rangeName Name of the normalization range.
914/// \param[in] ctx An object to manage auxiliary information for code-squashing.
915///
916/// \returns The representative code string of the integral for the given object.
917std::string codegenIntegralImpl(RooAbsReal &arg, int, const char *, CodegenContext &)
918{
919 std::stringstream errorMsg;
920 errorMsg << "An analytical integral function for class \"" << arg.ClassName() << "\" has not yet been implemented.";
921 oocoutE(&arg, Minimization) << errorMsg.str() << std::endl;
922 throw std::runtime_error(errorMsg.str().c_str());
923}
924
925std::string codegenIntegralImpl(RooBernstein &arg, int, const char *rangeName, CodegenContext &ctx)
926{
927 arg.fillBuffer(); // to get the right xmin() and xmax()
928 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.x());
929 return ctx.buildCall(mathFunc("bernsteinIntegral"), x.getMin(rangeName), x.getMax(rangeName), arg.xmin(), arg.xmax(),
930 arg.coefList(), arg.coefList().size());
931}
932
933std::string codegenIntegralImpl(RooBifurGauss &arg, int code, const char *rangeName, CodegenContext &ctx)
934{
935 auto &constant = code == 1 ? arg.getMean() : arg.getX();
936 auto &integrand = dynamic_cast<RooAbsRealLValue const &>(code == 1 ? arg.getX() : arg.getMean());
937
938 return ctx.buildCall(mathFunc("bifurGaussIntegral"), integrand.getMin(rangeName), integrand.getMax(rangeName),
939 constant, arg.getSigmaL(), arg.getSigmaR());
940}
941
942std::string codegenIntegralImpl(RooCBShape &arg, int /*code*/, const char *rangeName, CodegenContext &ctx)
943{
944 auto &m = dynamic_cast<RooAbsRealLValue const &>(arg.getM());
945 return ctx.buildCall(mathFunc("cbShapeIntegral"), m.getMin(rangeName), m.getMax(rangeName), arg.getM0(),
946 arg.getSigma(), arg.getAlpha(), arg.getN());
947}
948
949std::string codegenIntegralImpl(RooChebychev &arg, int, const char *rangeName, CodegenContext &ctx)
950{
951 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.x());
952 double xmax = x.getMax(arg.refRangeName());
953 double xmin = x.getMin(arg.refRangeName());
954 unsigned int sz = arg.coefList().size();
955
956 return ctx.buildCall(mathFunc("chebychevIntegral"), arg.coefList(), sz, xmin, xmax, x.getMin(rangeName),
957 x.getMax(rangeName));
958}
959
960std::string codegenIntegralImpl(RooEfficiency &, int, const char *, CodegenContext &)
961{
962 return "1.0";
963}
964
965std::string codegenIntegralImpl(RooExponential &arg, int code, const char *rangeName, CodegenContext &ctx)
966{
967 bool isOverX = code == 1;
968
969 std::string constant;
970 if (arg.negateCoefficient() && isOverX) {
971 constant += "-";
972 }
973 constant += ctx.getResult(isOverX ? arg.coefficient() : arg.variable());
974
975 auto &integrand = dynamic_cast<RooAbsRealLValue const &>(isOverX ? arg.variable() : arg.coefficient());
976
977 double min = integrand.getMin(rangeName);
978 double max = integrand.getMax(rangeName);
979
980 if (!isOverX && arg.negateCoefficient()) {
981 std::swap(min, max);
982 min = -min;
983 max = -max;
984 }
985
986 return ctx.buildCall(mathFunc("exponentialIntegral"), min, max, constant);
987}
988
989std::string codegenIntegralImpl(RooGamma &arg, int, const char *rangeName, CodegenContext &ctx)
990{
991 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.getX());
992 const std::string a =
993 ctx.buildCall("ROOT::Math::gamma_cdf", x.getMax(rangeName), arg.getGamma(), arg.getBeta(), arg.getMu());
994 const std::string b =
995 ctx.buildCall("ROOT::Math::gamma_cdf", x.getMin(rangeName), arg.getGamma(), arg.getBeta(), arg.getMu());
996 return a + " - " + b;
997}
998
999std::string codegenIntegralImpl(RooGaussian &arg, int code, const char *rangeName, CodegenContext &ctx)
1000{
1001 auto &constant = code == 1 ? arg.getMean() : arg.getX();
1002 auto &integrand = dynamic_cast<RooAbsRealLValue const &>(code == 1 ? arg.getX() : arg.getMean());
1003
1004 return ctx.buildCall(mathFunc("gaussianIntegral"), integrand.getMin(rangeName), integrand.getMax(rangeName),
1005 constant, arg.getSigma());
1006}
1007
1008namespace {
1009
1010std::string rooHistIntegralTranslateImpl(int code, RooAbsArg const &arg, RooDataHist const &dataHist,
1011 const RooArgSet &obs, bool histFuncMode)
1012{
1013 if (((2 << obs.size()) - 1) != code) {
1014 oocoutE(&arg, InputArguments) << "RooHistPdf::integral(" << arg.GetName()
1015 << ") ERROR: AD currently only supports integrating over all histogram observables."
1016 << std::endl;
1017 return "";
1018 }
1019 return doubleToString(dataHist.sum(histFuncMode));
1020}
1021
1022} // namespace
1023
1024std::string codegenIntegralImpl(RooHistFunc &arg, int code, const char *, CodegenContext &)
1025{
1026 return rooHistIntegralTranslateImpl(code, arg, arg.dataHist(), arg.variables(), true);
1027}
1028
1029std::string codegenIntegralImpl(RooHistPdf &arg, int code, const char *, CodegenContext &)
1030{
1031 return rooHistIntegralTranslateImpl(code, arg, arg.dataHist(), arg.variables(), false);
1032}
1033
1034std::string codegenIntegralImpl(RooLandau &arg, int, const char *rangeName, CodegenContext &ctx)
1035{
1036 // Don't do anything with "code". It can only be "1" anyway (see
1037 // implementation of getAnalyticalIntegral).
1038 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.getX());
1039 const std::string a = ctx.buildCall("ROOT::Math::landau_cdf", x.getMax(rangeName), arg.getSigma(), arg.getMean());
1040 const std::string b = ctx.buildCall("ROOT::Math::landau_cdf", x.getMin(rangeName), arg.getSigma(), arg.getMean());
1041 return ctx.getResult(arg.getSigma()) + " * " + "(" + a + " - " + b + ")";
1042}
1043
1044std::string codegenIntegralImpl(RooLognormal &arg, int, const char *rangeName, CodegenContext &ctx)
1045{
1046 std::string funcName = arg.useStandardParametrization() ? "logNormalIntegralStandard" : "logNormalIntegral";
1047 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.getX());
1048 return ctx.buildCall(mathFunc(funcName), x.getMin(rangeName), x.getMax(rangeName), arg.getMedian(), arg.getShapeK());
1049}
1050
1051std::string codegenIntegralImpl(RooMultiVarGaussian &arg, int code, const char *rangeName, CodegenContext &)
1052{
1053 if (code != -1) {
1054 std::stringstream errorMsg;
1055 errorMsg << "Partial integrals over RooMultiVarGaussian are not supported.";
1056 oocoutE(&arg, Minimization) << errorMsg.str() << std::endl;
1057 throw std::runtime_error(errorMsg.str().c_str());
1058 }
1059
1060 return doubleToString(arg.analyticalIntegral(code, rangeName));
1061}
1062
1064{
1065 std::stringstream ss;
1066 ss << arg.outerWrapperName() << "(";
1067 for (std::size_t i = 0; i < arg.nInputTensors(); ++i) {
1068 ss << ctx.buildArg(arg.inputTensorList(i)) << std::endl;
1069 if (i != arg.nInputTensors() - 1) {
1070 ss << ", ";
1071 }
1072 }
1073 ss << ")";
1074
1075 ctx.addResult(&arg, ss.str());
1076}
1077
1078std::string codegenIntegralImpl(RooPoisson &arg, int code, const char *rangeName, CodegenContext &ctx)
1079{
1080 assert(code == 1 || code == 2);
1081 std::string xName = ctx.getResult(arg.getX());
1082 if (!arg.getNoRounding())
1083 xName = "std::floor(" + xName + ")";
1084
1085 auto &integrand = dynamic_cast<RooAbsRealLValue const &>(code == 1 ? arg.getX() : arg.getMean());
1086 // Since the integral function is the same for both codes, we need to make sure the indexed observables do not appear
1087 // in the function if they are not required.
1088 xName = code == 1 ? "0" : xName;
1089 return ctx.buildCall(mathFunc("poissonIntegral"), code, arg.getMean(), xName, integrand.getMin(rangeName),
1090 integrand.getMax(rangeName), arg.getProtectNegativeMean());
1091}
1092
1093std::string codegenIntegralImpl(RooPolyVar &arg, int, const char *rangeName, CodegenContext &ctx)
1094{
1095 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.x());
1096 const double xmin = x.getMin(rangeName);
1097 const double xmax = x.getMax(rangeName);
1098 const unsigned sz = arg.coefList().size();
1099 if (!sz)
1100 return std::to_string(arg.lowestOrder() ? xmax - xmin : 0.0);
1101
1102 return ctx.buildCall(mathFunc("polynomialIntegral"), arg.coefList(), sz, arg.lowestOrder(), xmin, xmax);
1103}
1104
1105std::string codegenIntegralImpl(RooPolynomial &arg, int, const char *rangeName, CodegenContext &ctx)
1106{
1107 auto &x = dynamic_cast<RooAbsRealLValue const &>(arg.x());
1108 const double xmin = x.getMin(rangeName);
1109 const double xmax = x.getMax(rangeName);
1110 const unsigned sz = arg.coefList().size();
1111 if (!sz)
1112 return std::to_string(arg.lowestOrder() ? xmax - xmin : 0.0);
1113
1114 return ctx.buildCall(mathFunc("polynomialIntegral<true>"), arg.coefList(), sz, arg.lowestOrder(), xmin, xmax);
1115}
1116
1117std::string codegenIntegralImpl(RooRealSumPdf &arg, int code, const char *rangeName, CodegenContext &ctx)
1118{
1119 // Re-use translate, since integration is linear.
1120 return realSumPdfTranslateImpl(ctx, arg.funcIntListFromCache(code, rangeName), arg.coefList(), false);
1121}
1122
1123std::string codegenIntegralImpl(RooUniform &arg, int code, const char *rangeName, CodegenContext &)
1124{
1125 // The integral of a uniform distribution is static, so we can just hardcode
1126 // the result in a string.
1127 return doubleToString(arg.analyticalIntegral(code, rangeName));
1128}
1129
1130} // 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:77
bool isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:284
virtual bool isFundamental() const
Is this object a fundamental type that can be added to a dataset? Fundamental-type subclasses overrid...
Definition RooAbsArg.h:176
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:265
RooAbsReal const * rearrangedDen() const
Definition RooProdPdf.h:260
RooAbsReal const * rearrangedNum() const
Definition RooProdPdf.h:256
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:30
Int_t getInterpolationOrder() const
Definition RooHistPdf.h:59
RooDataHist & dataHist()
Definition RooHistPdf.h:42
bool haveUnitNorm() const
Definition RooHistPdf.h:82
bool getCdfBoundaries() const
Definition RooHistPdf.h:73
RooArgSet const & variables() const
Definition RooHistPdf.h:100
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