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