Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooAddHelpers.cxx
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 *
4 * Copyright (c) 2022, CERN
5 *
6 * Redistribution and use in source and binary forms,
7 * with or without modification, are permitted according to the terms
8 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
9 */
10
11#include "RooAddHelpers.h"
12
13#include <RooAbsPdf.h>
14#include <RooArgSet.h>
15#include <RooNaNPacker.h>
16#include <RooRealConstant.h>
17#include <RooRealIntegral.h>
18#include <RooRealVar.h>
19#include <RooRatio.h>
20
21////////////////////////////////////////////////////////////////////////////////
22/// Create a RooAddPdf cache element for a given normalization set and
23/// projection configuration.
24
25AddCacheElem::AddCacheElem(RooAbsPdf const &addPdf, RooArgList const &pdfList, RooArgList const &coefList,
26 const RooArgSet *nset, const RooArgSet *iset, RooArgSet const &refCoefNormSet,
27 std::string const &refCoefNormRange, int verboseEval)
28{
29 // Projection integrals are always over all pdf components. Overriding the
30 // global component selection temporarily makes all RooRealIntegrals created
31 // during that time always include all components.
33
34 // We put the normRange into a std::string to not have to deal with
35 // nullptr vs. "" ambiguities
36 const std::string normRange = addPdf.normRange() ? addPdf.normRange() : "";
37
38 _suppNormList.reserve(pdfList.size());
39
40 // *** PART 1 : Create supplemental normalization list ***
41
42 // Retrieve the combined set of dependents of this PDF ;
43 RooArgSet fullDepList;
44 addPdf.getObservables(nset, fullDepList);
45 if (iset) {
46 fullDepList.remove(*iset, true, true);
47 }
48
49 // Reduce iset/nset to actual dependents of this PDF
50 RooArgSet nset2;
51 addPdf.getObservables(nset, nset2);
52
53 if (nset2.empty() && !refCoefNormSet.empty()) {
54 // Evaluating RooAddPdf without normalization, but have reference normalization for coefficient definition
55 nset2.add(refCoefNormSet);
56 }
57
58 bool hasPdfWithCustomRange = false;
59
60 // Fill with dummy unit RRVs for now
61 for (std::size_t i = 0; i < pdfList.size(); ++i) {
62 auto pdf = static_cast<const RooAbsPdf *>(pdfList.at(i));
63 auto coef = static_cast<const RooAbsReal *>(coefList.at(i));
64
65 hasPdfWithCustomRange |= pdf->normRange() != nullptr;
66
67 // Start with full list of dependents
68 RooArgSet supNSet(fullDepList);
69
70 // Remove PDF dependents
71 if (auto pdfDeps = std::unique_ptr<RooArgSet>{pdf->getObservables(nset)}) {
72 supNSet.remove(*pdfDeps, true, true);
73 }
74
75 // Remove coef dependents
76 if (auto coefDeps = std::unique_ptr<RooArgSet>{coef ? coef->getObservables(nset) : nullptr}) {
77 supNSet.remove(*coefDeps, true, true);
78 }
79
80 std::unique_ptr<RooAbsReal> snorm;
81 auto name = std::string(addPdf.GetName()) + "_" + pdf->GetName() + "_SupNorm";
82 if (!supNSet.empty()) {
83 snorm = std::make_unique<RooRealIntegral>(name.c_str(), "Supplemental normalization integral",
84 RooRealConstant::value(1.0), supNSet);
85 oocxcoutD(&addPdf, Caching) << addPdf.ClassName() << " " << addPdf.GetName()
86 << " making supplemental normalization set " << supNSet << " for pdf component "
87 << pdf->GetName() << std::endl;
88 }
89
90 if (!normRange.empty()) {
91 auto snormTerm = std::unique_ptr<RooAbsReal>(pdf->createIntegral(nset2, nset2, normRange.c_str()));
92 if (snorm) {
93 auto oldSnorm = std::move(snorm);
94 snorm = std::make_unique<RooProduct>("snorm", "snorm", *oldSnorm.get(), *snormTerm.get());
95 snorm->addOwnedComponents(std::move(snormTerm), std::move(oldSnorm));
96 } else {
97 snorm = std::move(snormTerm);
98 }
99 }
100 _suppNormList.emplace_back(std::move(snorm));
101 }
102
103 if (verboseEval > 1) {
104 oocxcoutD(&addPdf, Caching) << addPdf.ClassName() << "::syncSuppNormList(" << addPdf.GetName()
105 << ") synching supplemental normalization list for norm"
106 << (nset ? *nset : RooArgSet()) << std::endl;
107 }
108
109 // *** PART 2 : Create projection coefficients ***
110
111 const bool projectCoefsForRangeReasons = !refCoefNormRange.empty() || !normRange.empty() || hasPdfWithCustomRange;
112
113 // If no projections required stop here
114 if (refCoefNormSet.empty() && !projectCoefsForRangeReasons) {
115 return;
116 }
117
118 if (!nset2.equals(refCoefNormSet) || projectCoefsForRangeReasons) {
119
120 // Recalculate projection integrals of PDFs
121 for (auto *pdf : static_range_cast<const RooAbsPdf *>(pdfList)) {
122
123 // Calculate projection integral
124 std::unique_ptr<RooAbsReal> pdfProj;
125 if (!refCoefNormSet.empty() && !nset2.equals(refCoefNormSet)) {
126 pdfProj = std::unique_ptr<RooAbsReal>{pdf->createIntegral(nset2, refCoefNormSet, normRange.c_str())};
127 pdfProj->setOperMode(addPdf.operMode());
128 oocxcoutD(&addPdf, Caching) << addPdf.ClassName() << "(" << addPdf.GetName() << ")::getPC nset2(" << nset2
129 << ")!=_refCoefNormSet(" << refCoefNormSet
130 << ") --> pdfProj = " << pdfProj->GetName() << std::endl;
131 oocxcoutD(&addPdf, Caching) << " " << addPdf.ClassName() << "::syncCoefProjList(" << addPdf.GetName()
132 << ") PP = " << pdfProj->GetName() << std::endl;
133 }
134
135 _projList.emplace_back(std::move(pdfProj));
136
137 // Calculation optional supplemental normalization term
138 RooArgSet supNormSet(refCoefNormSet);
139 auto deps = std::unique_ptr<RooArgSet>{pdf->getParameters(RooArgSet())};
140 supNormSet.remove(*deps, true, true);
141
142 std::unique_ptr<RooAbsReal> snorm;
143 auto name = std::string(addPdf.GetName()) + "_" + pdf->GetName() + "_ProjSupNorm";
144 if (!supNormSet.empty() && !nset2.equals(refCoefNormSet)) {
145 snorm = std::make_unique<RooRealIntegral>(name.c_str(), "Projection Supplemental normalization integral",
146 RooRealConstant::value(1.0), supNormSet);
147 oocxcoutD(&addPdf, Caching) << " " << addPdf.ClassName() << "::syncCoefProjList(" << addPdf.GetName()
148 << ") SN = " << snorm->GetName() << std::endl;
149 }
150 _suppProjList.emplace_back(std::move(snorm));
151
152 // Calculate range adjusted projection integral
153 std::unique_ptr<RooAbsReal> rangeProj2;
154 if (normRange != refCoefNormRange) {
155 RooArgSet tmp;
156 pdf->getObservables(refCoefNormSet.empty() ? nset : &refCoefNormSet, tmp);
157 auto int1 = std::unique_ptr<RooAbsReal>{pdf->createIntegral(tmp, tmp, normRange.c_str())};
158 auto int2 = std::unique_ptr<RooAbsReal>{pdf->createIntegral(tmp, tmp, refCoefNormRange.c_str())};
159 rangeProj2 = std::make_unique<RooRatio>("rangeProj", "rangeProj", *int1, *int2);
160 rangeProj2->addOwnedComponents(std::move(int1), std::move(int2));
161 }
162
163 _rangeProjList.emplace_back(std::move(rangeProj2));
164 }
165 }
166}
167
169{
170 auto printVector = [](auto const &vec, const char *name) {
171 std::cout << "+++ " << name << ":" << std::endl;
172 for (auto const &arg : vec) {
173 std::cout << " ";
174 if (arg)
175 arg->Print();
176 else
177 std::cout << "nullptr" << std::endl;
178 }
179 };
180
181 printVector(_suppNormList, "_suppNormList");
182 printVector(_projList, "_projList");
183 printVector(_suppProjList, "_suppProjList");
184 printVector(_rangeProjList, "_rangeProjList");
185}
186
187////////////////////////////////////////////////////////////////////////////////
188/// List all RooAbsArg derived contents in this cache element
189
191{
192 RooArgList allNodes;
193 // need to iterate manually because _suppProjList can contain nullptr
194 for (auto const &arg : _projList) {
195 if (arg)
196 allNodes.add(*arg);
197 }
198 for (auto const &arg : _suppProjList) {
199 if (arg)
200 allNodes.add(*arg);
201 }
202 for (auto const &arg : _rangeProjList) {
203 if (arg)
204 allNodes.add(*arg);
205 }
206
207 return allNodes;
208}
209
210////////////////////////////////////////////////////////////////////////////////
211/// Update the RooAddPdf coefficients for a given normalization set and
212/// projection configuration. The `coefCache` argument should have the same
213/// size as `pdfList`. It needs to be initialized with the raw values of the
214/// coefficients, as obtained from the `_coefList` proxy in the RooAddPdf. If
215/// the last coefficient is not given, the initial value of the last element of
216/// `_coefCache` does not matter. After this function, the `_coefCache` will be
217/// filled with the correctly scaled coefficients for each pdf.
218
219void RooAddHelpers::updateCoefficients(RooAbsPdf const &addPdf, std::vector<double> &coefCache,
220 RooArgList const &pdfList, bool haveLastCoef, AddCacheElem &cache,
221 const RooArgSet *nset, RooArgSet const &refCoefNormSet, bool allExtendable,
222 int &coefErrCount)
223{
224 // Straight coefficients
225 if (allExtendable) {
226
227 // coef[i] = expectedEvents[i] / SUM(expectedEvents)
228 double coefSum(0);
229 std::size_t i = 0;
230 for (auto arg : pdfList) {
231 auto pdf = static_cast<RooAbsPdf *>(arg);
232 coefCache[i] = pdf->expectedEvents(!refCoefNormSet.empty() ? &refCoefNormSet : nset);
233 coefSum += coefCache[i];
234 i++;
235 }
236
237 if (coefSum == 0.) {
238 oocoutW(&addPdf, Eval) << addPdf.ClassName() << "::updateCoefCache(" << addPdf.GetName()
239 << ") WARNING: total number of expected events is 0" << std::endl;
240 } else {
241 for (std::size_t j = 0; j < pdfList.size(); j++) {
242 coefCache[j] /= coefSum;
243 }
244 }
245
246 } else {
247 if (haveLastCoef) {
248
249 // coef[i] = coef[i] / SUM(coef)
250 double coefSum = std::accumulate(coefCache.begin(), coefCache.end(), 0.0);
251 if (coefSum == 0.) {
252 oocoutW(&addPdf, Eval) << addPdf.ClassName() << "::updateCoefCache(" << addPdf.GetName()
253 << ") WARNING: sum of coefficients is zero 0" << std::endl;
254 } else {
255 const double invCoefSum = 1. / coefSum;
256 for (std::size_t j = 0; j < coefCache.size(); j++) {
257 coefCache[j] *= invCoefSum;
258 }
259 }
260 } else {
261
262 // coef[i] = coef[i] ; coef[n] = 1-SUM(coef[0...n-1])
263 double lastCoef = 1.0 - std::accumulate(coefCache.begin(), coefCache.end() - 1, 0.0);
264 coefCache.back() = lastCoef;
265
266 // Treat coefficient degeneration
267 const float coefDegen = lastCoef < 0. ? -lastCoef : (lastCoef > 1. ? lastCoef - 1. : 0.);
268 if (coefDegen > 1.E-5) {
269 coefCache.back() = RooNaNPacker::packFloatIntoNaN(100.f * coefDegen);
270
271 std::stringstream msg;
272 if (coefErrCount-- > 0) {
273 msg << "RooAddPdf::updateCoefCache(" << addPdf.GetName()
274 << " WARNING: sum of PDF coefficients not in range [0-1], value=" << 1 - lastCoef;
275 if (coefErrCount == 0) {
276 msg << " (no more will be printed)";
277 }
278 oocoutW(&addPdf, Eval) << msg.str() << std::endl;
279 }
280 }
281 }
282 }
283
284 // Stop here if not projection is required or needed
285 if (!cache.doProjection()) {
286 return;
287 }
288
289 // Adjust coefficients for given projection
290 double coefSum(0);
291 for (std::size_t i = 0; i < pdfList.size(); i++) {
292 coefCache[i] *= cache.projVal(i) / cache.projSuppNormVal(i) * cache.rangeProjScaleFactor(i);
293 coefSum += coefCache[i];
294 }
295
296 if ((RooMsgService::_debugCount > 0) &&
298 for (std::size_t i = 0; i < pdfList.size(); ++i) {
299 ooccoutD(&addPdf, Caching) << " ALEX: POST-SYNC coef[" << i << "] = " << coefCache[i]
300 << " ( _coefCache[i]/coefSum = " << coefCache[i] * coefSum << "/" << coefSum
301 << " ) " << std::endl;
302 }
303 }
304
305 if (coefSum == 0.) {
306 oocoutE(&addPdf, Eval) << addPdf.ClassName() << "::updateCoefCache(" << addPdf.GetName()
307 << ") sum of coefficients is zero." << std::endl;
308 }
309
310 for (std::size_t i = 0; i < pdfList.size(); i++) {
311 coefCache[i] /= coefSum;
312 }
313}
#define oocoutW(o, a)
#define oocxcoutD(o, a)
#define oocoutE(o, a)
#define ooccoutD(o, a)
char name[80]
Definition TGX11.cxx:110
double projVal(std::size_t idx) const
OwningArgVector _projList
Projection integrals to be multiplied with coefficients.
AddCacheElem(RooAbsPdf const &addPdf, RooArgList const &pdfList, RooArgList const &coefList, const RooArgSet *nset, const RooArgSet *iset, RooArgSet const &refCoefNormSet, std::string const &refCoefNormRange, int verboseEval)
Create a RooAddPdf cache element for a given normalization set and projection configuration.
double projSuppNormVal(std::size_t idx) const
void print() const
RooArgList containedArgs(Action) override
List all RooAbsArg derived contents in this cache element.
OwningArgVector _rangeProjList
Range integrals to be multiplied with coefficients (reference to target range)
double rangeProjScaleFactor(std::size_t idx) const
OwningArgVector _suppNormList
Supplemental normalization list.
bool doProjection() const
OwningArgVector _suppProjList
Projection integrals to multiply with coefficients for supplemental normalization.
RooFit::OwningPtr< RooArgSet > getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
OperMode operMode() const
Query the operation mode of this node.
Definition RooAbsArg.h:484
bool equals(const RooAbsCollection &otherColl) const
Check if this and other collection have identically-named contents.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
const char * GetName() const override
Returns name of object.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
Storage_t::size_type size() const
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:40
virtual double expectedEvents(const RooArgSet *nset) const
Return expected number of events to be used in calculation of extended likelihood.
const char * normRange() const
Definition RooAbsPdf.h:250
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:59
static void updateCoefficients(RooAbsPdf const &addPdf, std::vector< double > &coefCache, RooArgList const &pdfList, bool haveLastCoef, AddCacheElem &cache, const RooArgSet *nset, RooArgSet const &refCoefNormSet, bool allExtendable, int &coefErrCount)
Update the RooAddPdf coefficients for a given normalization set and projection configuration.
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition RooArgList.h:110
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:55
static RooMsgService & instance()
Return reference to singleton instance.
static Int_t _debugCount
static RooConstVar & value(double value)
Return a constant value object with given value.
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:207
__roodevice__ static __roohost__ double packFloatIntoNaN(float payload)
Pack float into mantissa of a NaN.