Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooAddition.cxx
Go to the documentation of this file.
1/*****************************************************************************
2 * Project: RooFit *
3 * Package: RooFitCore *
4 * @(#)root/roofitcore:$Id$
5 * Authors: *
6 * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
7 * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
8 * *
9 * Copyright (c) 2000-2005, Regents of the University of California *
10 * and Stanford University. All rights reserved. *
11 * *
12 * Redistribution and use in source and binary forms, *
13 * with or without modification, are permitted according to the terms *
14 * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
15 *****************************************************************************/
16
17/**
18\file RooAddition.cxx
19\class RooAddition
20\ingroup Roofitcore
21
22Calculates the sum of a set of RooAbsReal terms, or
23when constructed with two sets, it sums the product of the terms
24in the two sets.
25**/
26
27
28#include "Riostream.h"
29#include "RooAddition.h"
30#include "RooRealSumFunc.h"
31#include "RooRealSumPdf.h"
32#include "RooProduct.h"
33#include "RooErrorHandler.h"
34#include "RooArgSet.h"
35#include "RooNameReg.h"
36#include "RooNLLVarNew.h"
37#include "RooMsgService.h"
38#include "RooBatchCompute.h"
39#include "RooFuncWrapper.h"
40
41#ifdef ROOFIT_LEGACY_EVAL_BACKEND
42#include "RooNLLVar.h"
43#include "RooChi2Var.h"
44#endif
45
46#include <algorithm>
47#include <cmath>
48
50
51
52////////////////////////////////////////////////////////////////////////////////
53/// Constructor with a single set consisting of RooAbsReal.
54/// \param[in] name Name of the PDF
55/// \param[in] title Title
56/// \param[in] sumSet The value of the function will be the sum of the values in this set
57
58RooAddition::RooAddition(const char *name, const char *title, const RooArgList &sumSet)
59 : RooAbsReal(name, title), _set("!set", "set of components", this), _cacheMgr(this, 10)
60{
61 _set.addTyped<RooAbsReal>(sumSet);
62}
63
64
65
66////////////////////////////////////////////////////////////////////////////////
67/// Constructor with two sets of RooAbsReals.
68///
69/// The sum of pair-wise products of elements in the sets will be computed:
70/// \f[
71/// A = \sum_i \mathrm{Set1}[i] * \mathrm{Set2}[i]
72/// \f]
73///
74/// \param[in] name Name of the PDF
75/// \param[in] title Title
76/// \param[in] sumSet1 Left-hand element of the pair-wise products
77/// \param[in] sumSet2 Right-hand element of the pair-wise products
78///
79RooAddition::RooAddition(const char *name, const char *title, const RooArgList &sumSet1, const RooArgList &sumSet2)
80 : RooAbsReal(name, title), _set("!set", "set of components", this), _cacheMgr(this, 10)
81{
82 if (sumSet1.size() != sumSet2.size()) {
83 coutE(InputArguments) << "RooAddition::ctor(" << GetName() << ") ERROR: input lists should be of equal length" << std::endl;
85 }
86
87 for (unsigned int i = 0; i < sumSet1.size(); ++i) {
88 const auto comp1 = &sumSet1[i];
89 const auto comp2 = &sumSet2[i];
90
91 if (!dynamic_cast<RooAbsReal*>(comp1)) {
92 coutE(InputArguments) << "RooAddition::ctor(" << GetName() << ") ERROR: component " << comp1->GetName()
93 << " in first list is not of type RooAbsReal" << std::endl;
95 }
96
97 if (!dynamic_cast<RooAbsReal*>(comp2)) {
98 coutE(InputArguments) << "RooAddition::ctor(" << GetName() << ") ERROR: component " << comp2->GetName()
99 << " in first list is not of type RooAbsReal" << std::endl;
101 }
102 TString _name(name);
103 _name.Append( "_[");
104 _name.Append(comp1->GetName());
105 _name.Append( "_x_");
106 _name.Append(comp2->GetName());
107 _name.Append( "]");
108 auto prod = std::make_unique<RooProduct>( _name, _name , RooArgSet(*comp1, *comp2));
109 _set.add(*prod);
110 _ownedList.addOwned(std::move(prod));
111 }
112}
113
114
115
116////////////////////////////////////////////////////////////////////////////////
117/// Copy constructor
118
119RooAddition::RooAddition(const RooAddition& other, const char* name)
120 : RooAbsReal(other, name)
121 , _set("!set",this,other._set)
122 , _cacheMgr(other._cacheMgr,this)
123{
124 // Member _ownedList is intentionally not copy-constructed -- ownership is not transferred
125}
126
127////////////////////////////////////////////////////////////////////////////////
128/// Calculate and return current value of self
129
131{
132 double sum(0);
133 const RooArgSet* nset = _set.nset() ;
134
135 for (auto* comp : static_range_cast<RooAbsReal*>(_set)) {
136 const double tmp = comp->getVal(nset);
137 sum += tmp ;
138 }
139 return sum ;
140}
141
142
143////////////////////////////////////////////////////////////////////////////////
144/// Compute addition of PDFs in batches.
146{
147 std::vector<std::span<const double>> pdfs;
148 std::vector<double> coefs;
149 pdfs.reserve(_set.size());
150 coefs.reserve(_set.size());
151 for (const auto arg : _set) {
152 pdfs.push_back(ctx.at(arg));
153 coefs.push_back(1.0);
154 }
155 RooBatchCompute::compute(ctx.config(this), RooBatchCompute::AddPdf, ctx.output(), pdfs, coefs);
156}
157
158////////////////////////////////////////////////////////////////////////////////
159
161{
162 if (_set.empty()) {
163 ctx.addResult(this, "0.0");
164 }
165 std::string result;
166 if (_set.size() > 1)
167 result += "(";
168
169 std::size_t i = 0;
170 for (auto *component : static_range_cast<RooAbsReal *>(_set)) {
171
172 // if (dynamic_cast<RooNLLVarNew *>(component)) {
173 // result += ctx.getResultFrom
174 // } else {
175 if (!dynamic_cast<RooNLLVarNew *>(component) || _set.size() == 1) {
176 result += ctx.getResult(*component);
177 ++i;
178 if (i < _set.size()) result += '+';
179 continue;
180 }
181 auto &wrp = *ctx._wrapper;
182 auto funcName = wrp.declareFunction(wrp.buildCode(*component));
183 result += funcName + "(params, obs, xlArr)";
184 ++i;
185 if (i < _set.size()) result += '+';
186 }
187 if (_set.size() > 1)
188 result += ')';
189 ctx.addResult(this, result);
190}
191
192////////////////////////////////////////////////////////////////////////////////
193/// Return the default error level for MINUIT error analysis
194/// If the addition contains one or more RooNLLVars and
195/// no RooChi2Vars, return the defaultErrorLevel() of
196/// RooNLLVar. If the addition contains one ore more RooChi2Vars
197/// and no RooNLLVars, return the defaultErrorLevel() of
198/// RooChi2Var. If the addition contains neither or both
199/// issue a warning message and return a value of 1
200
202{
203 RooAbsReal* nllArg(nullptr) ;
204 RooAbsReal* chi2Arg(nullptr) ;
205
206 std::unique_ptr<RooArgSet> comps{getComponents()};
207 for(RooAbsArg * arg : *comps) {
208 if (dynamic_cast<RooNLLVarNew*>(arg)) {
209 nllArg = static_cast<RooAbsReal*>(arg) ;
210 }
211#ifdef ROOFIT_LEGACY_EVAL_BACKEND
212 if (dynamic_cast<RooNLLVar*>(arg)) {
213 nllArg = static_cast<RooAbsReal*>(arg) ;
214 }
215 if (dynamic_cast<RooChi2Var*>(arg)) {
216 chi2Arg = static_cast<RooAbsReal*>(arg) ;
217 }
218#endif
219 }
220
221 if (nllArg && !chi2Arg) {
222 coutI(Fitting) << "RooAddition::defaultErrorLevel(" << GetName()
223 << ") Summation contains a RooNLLVar, using its error level" << std::endl;
224 return nllArg->defaultErrorLevel() ;
225 } else if (chi2Arg && !nllArg) {
226 coutI(Fitting) << "RooAddition::defaultErrorLevel(" << GetName()
227 << ") Summation contains a RooChi2Var, using its error level" << std::endl;
228 return chi2Arg->defaultErrorLevel() ;
229 } else if (!nllArg && !chi2Arg) {
230 coutI(Fitting) << "RooAddition::defaultErrorLevel(" << GetName() << ") WARNING: "
231 << "Summation contains neither RooNLLVar nor RooChi2Var server, using default level of 1.0" << std::endl;
232 } else {
233 coutI(Fitting) << "RooAddition::defaultErrorLevel(" << GetName() << ") WARNING: "
234 << "Summation contains BOTH RooNLLVar and RooChi2Var server, using default level of 1.0" << std::endl;
235 }
236
237 return 1.0 ;
238}
239
240
241
242////////////////////////////////////////////////////////////////////////////////
243
245{
246 for (const auto arg : _set) {
247 static_cast<RooAbsReal*>(arg)->setData(data,cloneData) ;
248 }
249 return true ;
250}
251
252
253
254////////////////////////////////////////////////////////////////////////////////
255
256void RooAddition::printMetaArgs(std::ostream& os) const
257{
258 // We can use the implementation of RooRealSumPdf with an empty coefficient list.
259 static const RooArgList coefs{};
261}
262
263////////////////////////////////////////////////////////////////////////////////
264
265Int_t RooAddition::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* rangeName) const
266{
267 // we always do things ourselves -- actually, always delegate further down the line ;-)
268 analVars.add(allVars);
269
270 // check if we already have integrals for this combination of factors
271 Int_t sterileIndex(-1);
272 CacheElem* cache = static_cast<CacheElem*>(_cacheMgr.getObj(&analVars,&analVars,&sterileIndex,RooNameReg::ptr(rangeName)));
273 if (cache!=nullptr) {
274 Int_t code = _cacheMgr.lastIndex();
275 return code+1;
276 }
277
278 // we don't, so we make it right here....
279 cache = new CacheElem;
280 for (auto *arg : static_range_cast<RooAbsReal const*>(_set)) {// checked in c'tor that this will work...
281 cache->_I.addOwned(std::unique_ptr<RooAbsReal>{arg->createIntegral(analVars,rangeName)});
282 }
283
284 Int_t code = _cacheMgr.setObj(&analVars,&analVars,(RooAbsCacheElement*)cache,RooNameReg::ptr(rangeName));
285 return 1+code;
286}
287
288////////////////////////////////////////////////////////////////////////////////
289/// Calculate integral internally from appropriate integral cache
290
291double RooAddition::analyticalIntegral(Int_t code, const char* rangeName) const
292{
293 // note: rangeName implicit encoded in code: see _cacheMgr.setObj in getPartIntList...
294 CacheElem *cache = static_cast<CacheElem*>(_cacheMgr.getObjByIndex(code-1));
295 if (cache==nullptr) {
296 // cache got sterilized, trigger repopulation of this slot, then try again...
297 std::unique_ptr<RooArgSet> vars( getParameters(RooArgSet()) );
298 RooArgSet iset = _cacheMgr.selectFromSet2(*vars, code-1);
299 RooArgSet dummy;
300 Int_t code2 = getAnalyticalIntegral(iset,dummy,rangeName);
301 assert(code==code2); // must have revived the right (sterilized) slot...
302 return analyticalIntegral(code2,rangeName);
303 }
304 assert(cache!=nullptr);
305
306 // loop over cache, and sum...
307 double result(0);
308 for (auto I : cache->_I) {
309 result += static_cast<const RooAbsReal*>(I)->getVal();
310 }
311 return result;
312
313}
314
315
316////////////////////////////////////////////////////////////////////////////////
317
318std::list<double>* RooAddition::binBoundaries(RooAbsRealLValue& obs, double xlo, double xhi) const
319{
320 return RooRealSumPdf::binBoundaries(_set, obs, xlo, xhi);
321}
322
323
325{
327}
328
329
330////////////////////////////////////////////////////////////////////////////////
331
332std::list<double>* RooAddition::plotSamplingHint(RooAbsRealLValue& obs, double xlo, double xhi) const
333{
334 return RooRealSumPdf::plotSamplingHint(_set, obs, xlo, xhi);
335}
#define coutI(a)
#define coutE(a)
#define ClassImp(name)
Definition Rtypes.h:377
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
char name[80]
Definition TGX11.cxx:110
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
RooFit::OwningPtr< RooArgSet > getParameters(const RooAbsData *data, bool stripDisconnected=true) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
RooFit::OwningPtr< RooArgSet > getComponents() const
Create a RooArgSet with all components (branch nodes) of the expression tree headed by this object.
Abstract base class for objects to be stored in RooAbsCache cache manager objects.
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
bool addTyped(const RooAbsCollection &list, bool silent=false)
Adds elements of a given RooAbsCollection to the container if they match the specified type.
virtual bool addOwned(RooAbsArg &var, bool silent=false)
Add an argument and transfer the ownership to the collection.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:57
const RooArgSet * nset() const
Definition RooAbsProxy.h:52
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:59
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:103
virtual double defaultErrorLevel() const
Definition RooAbsReal.h:248
Calculates the sum of a set of RooAbsReal terms, or when constructed with two sets,...
Definition RooAddition.h:27
RooArgList _ownedList
List of owned components.
Definition RooAddition.h:63
void doEval(RooFit::EvalContext &) const override
Compute addition of PDFs in batches.
Int_t getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &numVars, const char *rangeName=nullptr) const override
Interface function getAnalyticalIntergral advertises the analytical integrals that are supported.
std::list< double > * binBoundaries(RooAbsRealLValue &, double, double) const override
Retrieve bin boundaries if this distribution is binned in obs.
RooListProxy _set
set of terms to be summed
Definition RooAddition.h:64
void printMetaArgs(std::ostream &os) const override
bool setData(RooAbsData &data, bool cloneData=true) override
double analyticalIntegral(Int_t code, const char *rangeName=nullptr) const override
Calculate integral internally from appropriate integral cache.
RooObjCacheManager _cacheMgr
! The cache manager
Definition RooAddition.h:72
double defaultErrorLevel() const override
Return the default error level for MINUIT error analysis If the addition contains one or more RooNLLV...
double evaluate() const override
Calculate and return current value of self.
std::list< double > * plotSamplingHint(RooAbsRealLValue &, double, double) const override
Interface for returning an optional hint for initial sampling points when constructing a curve projec...
bool isBinnedDistribution(const RooArgSet &obs) const override
Tests if the distribution is binned. Unless overridden by derived classes, this always returns false.
void translate(RooFit::Detail::CodeSquashContext &ctx) const override
This function defines a translation for each RooAbsReal based object that can be used to express the ...
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:55
Int_t setObj(const RooArgSet *nset, T *obj, const TNamed *isetRangeName=nullptr)
Setter function without integration set.
T * getObjByIndex(Int_t index) const
Retrieve payload object by slot index.
RooArgSet selectFromSet2(RooArgSet const &argSet, int index) const
Create RooArgSet containing the objects that are both in the cached set 2 with a given index and an i...
Int_t lastIndex() const
Return index of slot used in last get or set operation.
T * getObj(const RooArgSet *nset, Int_t *sterileIndex=nullptr, const TNamed *isetRangeName=nullptr)
Getter function without integration set.
Simple calculation from a binned dataset and a PDF.
Definition RooChi2Var.h:50
bool add(const RooAbsArg &var, bool valueServer, bool shapeServer, bool silent)
Overloaded RooCollection_t::add() method insert object into set and registers object as server to own...
static void softAbort()
Soft abort function that interrupts macro execution but doesn't kill ROOT.
A class to maintain the context for squashing of RooFit models into code.
void addResult(RooAbsArg const *key, std::string const &value)
A function to save an expression that includes/depends on the result of the input node.
std::string const & getResult(RooAbsArg const &arg)
Gets the result for the given node using the node name.
Experimental::RooFuncWrapper * _wrapper
std::span< const double > at(RooAbsArg const *arg, RooAbsArg const *caller=nullptr)
std::span< double > output()
RooBatchCompute::Config config(RooAbsArg const *arg) const
std::string declareFunction(std::string const &funcBody)
Implements a -log(likelihood) calculation from a dataset and a PDF.
Definition RooNLLVar.h:50
static const TNamed * ptr(const char *stringPtr)
Return a unique TNamed pointer for given C++ string.
std::list< double > * plotSamplingHint(RooAbsRealLValue &, double, double) const override
Interface for returning an optional hint for initial sampling points when constructing a curve projec...
std::list< double > * binBoundaries(RooAbsRealLValue &, double, double) const override
Retrieve bin boundaries if this distribution is binned in obs.
void printMetaArgs(std::ostream &os) const override
Customized printing of arguments of a RooRealSumPdf to more intuitively reflect the contents of the p...
bool isBinnedDistribution(const RooArgSet &obs) const override
Check if all components that depend on obs are binned.
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
Basic string class.
Definition TString.h:139
TString & Append(const char *cs)
Definition TString.h:572
#define I(x, y, z)
void compute(Config cfg, Computer comp, std::span< double > output, VarSpan vars, ArgSpan extraArgs={})
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2345