Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooAbsCachedPdf.cxx
Go to the documentation of this file.
1 /*****************************************************************************
2 * Project: RooFit *
3 * *
4 * Copyright (c) 2000-2005, Regents of the University of California *
5 * and Stanford University. All rights reserved. *
6 * *
7 * Redistribution and use in source and binary forms, *
8 * with or without modification, are permitted according to the terms *
9 * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
10 *****************************************************************************/
11
12/**
13\file RooAbsCachedPdf.cxx
14\class RooAbsCachedPdf
15\ingroup Roofitcore
16
17RooAbsCachedPdf is the abstract base class for p.d.f.s that need or
18want to cache their evaluate() output in a RooHistPdf defined in
19terms of the used observables. This base class manages the creation
20and storage of all RooHistPdf cache p.d.fs and the RooDataHists
21that define their shape. Implementations of RooAbsCachedPdf must
22define member function fillCacheObject() which serves to fill an
23already created RooDataHist with the p.d.fs function values. In
24addition the member functions actualObservables() and
25actualParameters() must be define which report what the actual
26observables to be cached are for a given set of observables passed
27by the user to getVal() and on which parameters need to be tracked
28for changes to trigger a refilling of the cache histogram.
29**/
30
31#include "Riostream.h"
32using namespace std ;
33
34#include "RooFit.h"
35#include "TString.h"
36#include "RooAbsCachedPdf.h"
37#include "RooAbsReal.h"
38#include "RooMsgService.h"
39#include "RooDataHist.h"
40#include "RooHistPdf.h"
41#include "RooGlobalFunc.h"
42#include "RooRealVar.h"
43#include "RooChangeTracker.h"
45
47
48
49
50////////////////////////////////////////////////////////////////////////////////
51/// Constructor
52
53RooAbsCachedPdf::RooAbsCachedPdf(const char *name, const char *title, Int_t ipOrder) :
54 RooAbsPdf(name,title),
55 _cacheMgr(this,10),
56 _ipOrder(ipOrder),
57 _disableCache(kFALSE)
58 {
59 }
60
61
62
63////////////////////////////////////////////////////////////////////////////////
64/// Copy constructor
65
67 RooAbsPdf(other,name),
68 _cacheMgr(other._cacheMgr,this),
69 _ipOrder(other._ipOrder),
70 _disableCache(other._disableCache)
71 {
72 }
73
74
75
76////////////////////////////////////////////////////////////////////////////////
77/// Destructor
78
80{
81}
82
83
84
85////////////////////////////////////////////////////////////////////////////////
86/// Implementation of getVal() overriding default implementation
87/// of RooAbsPdf. Return normalized value stored in cache p.d.f
88/// rather than return value of evaluate() which is undefined
89/// for RooAbsCachedPdf
90
92{
93 if (_disableCache) {
94 return RooAbsPdf::getValV(nset) ;
95 }
96
97 // Calculate current unnormalized value of object
98 PdfCacheElem* cache = getCache(nset) ;
99
100 Double_t value = cache->pdf()->getVal(nset) ;
101
102 _value = value ;
103 return _value ;
104}
105
106
107
108////////////////////////////////////////////////////////////////////////////////
109/// Return pointer to RooHistPdf cache pdf for given choice of observables
110
112{
113 PdfCacheElem* cache = getCache(nset) ;
114
115 if (cache) {
116 return cache->pdf() ;
117 } else {
118 return 0 ;
119 }
120}
121
122
123////////////////////////////////////////////////////////////////////////////////
124/// Return pointer to RooDataHist cache histogram for given choice of observables
125
127{
128 PdfCacheElem* cache = getCache(nset) ;
129
130 if (cache) {
131 return cache->hist() ;
132 } else {
133 return 0 ;
134 }
135}
136
137
138////////////////////////////////////////////////////////////////////////////////
139/// Mark all bins of given cache as unitialized (value -1)
140
142{
143 cache.hist()->setAllWeights(-1) ;
144}
145
146
147
148////////////////////////////////////////////////////////////////////////////////
149/// Retrieve cache object associated with given choice of observables. If cache object
150/// does not exist, create and fill and register it on the fly. If recalculate=false
151/// recalculation of cache contents of existing caches that are marked dirty due to
152/// dependent parameter changes is suppressed.
153
155{
156 // Check if this configuration was created becfore
157 Int_t sterileIdx(-1) ;
158 PdfCacheElem* cache = (PdfCacheElem*) _cacheMgr.getObj(nset,0,&sterileIdx) ;
159
160 // Check if we have a cache histogram in the global expensive object cache
161 if (cache) {
162 if (cache->paramTracker()->hasChanged(kTRUE) && (recalculate || !cache->pdf()->haveUnitNorm()) ) {
163 cxcoutD(Eval) << "RooAbsCachedPdf::getCache(" << GetName() << ") cache " << cache << " pdf "
164 << cache->pdf()->GetName() << " requires recalculation as parameters changed" << endl ;
165 fillCacheObject(*cache) ;
166 cache->pdf()->setValueDirty() ;
167 }
168 return cache ;
169 }
170
171 // Create and fill cache
172 cache = createCache(nset) ;
173
174 // Check if we have contents registered already in global expensive object cache
175 RooDataHist* htmp = (RooDataHist*) expensiveObjectCache().retrieveObject(cache->hist()->GetName(),RooDataHist::Class(),cache->paramTracker()->parameters()) ;
176
177 if (htmp) {
178
179 cache->hist()->reset() ;
180 cache->hist()->add(*htmp) ;
181
182 } else {
183
184 fillCacheObject(*cache) ;
185
186 RooDataHist* eoclone = new RooDataHist(*cache->hist()) ;
187 eoclone->removeSelfFromDir() ;
188 expensiveObjectCache().registerObject(GetName(),cache->hist()->GetName(),*eoclone,cache->paramTracker()->parameters()) ;
189
190 }
191
192
193 // Store this cache configuration
194 Int_t code = _cacheMgr.setObj(nset,0,((RooAbsCacheElement*)cache),0) ;
195
196 coutI(Caching) << "RooAbsCachedPdf::getCache(" << GetName() << ") creating new cache " << cache << " with pdf "
197 << cache->pdf()->GetName() << " for nset " << (nset?*nset:RooArgSet()) << " with code " << code ;
198 if (htmp) {
199 ccoutI(Caching) << " from preexisting content." ;
200 }
201 ccoutI(Caching) << endl ;
202
203 return cache ;
204}
205
206
207
208
209////////////////////////////////////////////////////////////////////////////////
210/// Constructor of cache object which owns RooDataHist cache histogram,
211/// RooHistPdf pdf that represents is shape and RooChangeTracker meta
212/// object that tracks changes in listed dependent parameter of cache.
213
215 _pdf(0), _paramTracker(0), _hist(0), _norm(0)
216{
217 // Create cache object itself -- Default implementation is a RooHistPdf
218 RooArgSet* nset2 = self.actualObservables(nsetIn?*nsetIn:RooArgSet()) ;
219
220 RooArgSet orderedObs ;
221 if (nset2) {
222 self.preferredObservableScanOrder(*nset2,orderedObs) ;
223 }
224
225 // Create RooDataHist
226 TString hname = self.GetName() ;
227 hname.Append("_") ;
228 hname.Append(self.inputBaseName()) ;
229 hname.Append("_CACHEHIST") ;
230 hname.Append(self.cacheNameSuffix(orderedObs)) ;
231 hname.Append(self.histNameSuffix()) ;
232 _hist = new RooDataHist(hname,hname,orderedObs,self.binningName()) ;
234
235 //RooArgSet* observables= self.getObservables(orderedObs) ;
236 // cout << "orderedObs = " << orderedObs << " observables = " << *observables << endl ;
237
238 // Get set of p.d.f. observable corresponding to set of histogram observables
239 RooArgSet pdfObs ;
240 RooArgSet pdfFinalObs ;
241 TIterator* iter = orderedObs.createIterator() ;
242 RooAbsArg* harg ;
243 while((harg=(RooAbsArg*)iter->Next())) {
244 RooAbsArg& po = self.pdfObservable(*harg) ;
245 pdfObs.add(po) ;
246 if (po.isFundamental()) {
247 pdfFinalObs.add(po) ;
248 } else {
249 RooArgSet* tmp = po.getVariables() ;
250 pdfFinalObs.add(*tmp) ;
251 delete tmp ;
252 }
253 }
254 delete iter ;
255
256 // Create RooHistPdf
257 TString pdfname = self.inputBaseName() ;
258 pdfname.Append("_CACHE") ;
259 pdfname.Append(self.cacheNameSuffix(pdfFinalObs)) ;
260 // add a different name when cache is built in case nsetIn is not an empty list
261 if (nsetIn && nsetIn->getSize() > 0) {
262 pdfname.Append("_NORM");
263 for (auto *arg : *nsetIn)
264 pdfname.Append(TString::Format("_%s", arg->GetName()));
265 }
266 _pdf = new RooHistPdf(pdfname,pdfname,pdfObs,orderedObs,*_hist,self.getInterpolationOrder()) ;
267 if (nsetIn) {
268 _nset.addClone(*nsetIn) ;
269 }
270
271 // Create pseudo-object that tracks changes in parameter values
272
273 RooArgSet* params = self.actualParameters(pdfFinalObs) ;
274 params->remove(pdfFinalObs,kTRUE,kTRUE) ;
275
276 string name= Form("%s_CACHEPARAMS",_pdf->GetName()) ;
277 _paramTracker = new RooChangeTracker(name.c_str(),name.c_str(),*params,kTRUE) ;
278 _paramTracker->hasChanged(kTRUE) ; // clear dirty flag as cache is up-to-date upon creation
279
280 // Introduce formal dependency of RooHistPdf on parameters so that const optimization code
281 // makes the correct decisions
282 _pdf->addServerList(*params) ;
283
284 // Set initial state of cache to dirty
286
287 //delete observables ;
288 delete params ;
289 delete nset2 ;
290
291}
292
293
294
295////////////////////////////////////////////////////////////////////////////////
296/// Construct string with unique suffix for cache objects based on
297/// observable names that define cache configuration
298
300{
301 TString name ;
302 name.Append("_Obs[") ;
303 if (nset.getSize()>0) {
304 TIterator* iter = nset.createIterator() ;
305 RooAbsArg* arg ;
307 while((arg=(RooAbsArg*)iter->Next())) {
308 if (first) {
309 first=kFALSE ;
310 } else {
311 name.Append(",") ;
312 }
313 name.Append(arg->GetName()) ;
314 }
315 delete iter ;
316 }
317
318 name.Append("]") ;
319 const char* payloadUS = payloadUniqueSuffix() ;
320 if (payloadUS) {
321 name.Append(payloadUS) ;
322 }
323 return name ;
324}
325
326
327
328////////////////////////////////////////////////////////////////////////////////
329/// Change the interpolation order that is used in RooHistPdf cache
330/// representation smoothing the RooDataHist shapes.
331
333{
334 _ipOrder = order ;
335
336 Int_t i ;
337 for (i=0 ; i<_cacheMgr.cacheSize() ; i++) {
339 if (cache) {
340 cache->pdf()->setInterpolationOrder(order) ;
341 }
342 }
343}
344
345
346
347////////////////////////////////////////////////////////////////////////////////
348/// Returns all RooAbsArg objects contained in the cache element
349
351{
352 RooArgList ret(*_pdf) ;
353 ret.add(*_paramTracker) ;
354 if (_norm) ret.add(*_norm) ;
355 return ret ;
356}
357
358
359
360////////////////////////////////////////////////////////////////////////////////
361/// Cache element destructor
362
364{
365 if (_norm) {
366 delete _norm ;
367 }
368 if (_pdf) {
369 delete _pdf ;
370 }
371 if (_paramTracker) {
372 delete _paramTracker ;
373 }
374 if (_hist) {
375 delete _hist ;
376 }
377}
378
379
380
381////////////////////////////////////////////////////////////////////////////////
382/// Print contents of cache when printing self as part of object tree
383
384void RooAbsCachedPdf::PdfCacheElem::printCompactTreeHook(ostream& os, const char* indent, Int_t curElem, Int_t maxElem)
385{
386 if (curElem==0) {
387 os << indent << "--- RooAbsCachedPdf begin cache ---" << endl ;
388 }
389
390 TString indent2(indent) ;
391 os << Form("[%d] Configuration for observables ",curElem) << _nset << endl ;
392 indent2 += Form("[%d] ",curElem) ;
393 _pdf->printCompactTree(os,indent2) ;
394 if (_norm) {
395 os << Form("[%d] Norm ",curElem) ;
397 }
398
399 if (curElem==maxElem) {
400 os << indent << "--- RooAbsCachedPdf end cache --- " << endl ;
401 }
402}
403
404
405
406////////////////////////////////////////////////////////////////////////////////
407/// Force RooRealIntegral to offer all our actual observable for internal
408/// integration
409
411{
412 RooArgSet* actObs = actualObservables(dep) ;
413 Bool_t ret = (actObs->getSize()>0) ;
414 delete actObs ;
415 return ret ;
416}
417
418
419
420////////////////////////////////////////////////////////////////////////////////
421/// Advertises internal (analytical) integration capabilities. Call
422/// is forwarded to RooHistPdf cache p.d.f of cache that is used for
423/// given choice of observables
424
425Int_t RooAbsCachedPdf::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* rangeName) const
426{
427 if (allVars.getSize()==0) {
428 return 0 ;
429 }
430
431 PdfCacheElem* cache = getCache(normSet?normSet:&allVars) ;
432 Int_t code = cache->pdf()->getAnalyticalIntegralWN(allVars,analVars,normSet,rangeName) ;
433
434 if (code==0) {
435 return 0 ;
436 }
437
438 RooArgSet* all = new RooArgSet ;
439 RooArgSet* ana = new RooArgSet ;
440 RooArgSet* nrm = new RooArgSet ;
441 all->addClone(allVars) ;
442 ana->addClone(analVars) ;
443 if (normSet) {
444 nrm->addClone(*normSet) ;
445 }
446 std::vector<Int_t> codeList(2);
447 codeList[0] = code ;
448 codeList[1] = cache->pdf()->haveUnitNorm() ? 1 : 0 ;
449 Int_t masterCode = _anaReg.store(codeList,all,ana,nrm)+1 ; // takes ownership of all sets
450
451
452 // Mark all observables as internally integrated
453 if (cache->pdf()->haveUnitNorm()) {
454 analVars.add(allVars,kTRUE) ;
455 }
456
457 return masterCode ;
458}
459
460
461
462////////////////////////////////////////////////////////////////////////////////
463/// Implements internal (analytical) integration capabilities. Call
464/// is forwarded to RooHistPdf cache p.d.f of cache that is used for
465/// given choice of observables
466
467Double_t RooAbsCachedPdf::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* rangeName) const
468{
469 if (code==0) {
470 return getVal(normSet) ;
471 }
472
473 RooArgSet *allVars(0),*anaVars(0),*normSet2(0),*dummy(0) ;
474 const std::vector<Int_t> codeList = _anaReg.retrieve(code-1,allVars,anaVars,normSet2,dummy) ;
475
476 PdfCacheElem* cache = getCache(normSet2?normSet2:anaVars,kFALSE) ;
477 Double_t ret = cache->pdf()->analyticalIntegralWN(codeList[0],normSet,rangeName) ;
478
479 if (codeList[1]>0) {
480 RooArgSet factObs(*allVars) ;
481 factObs.remove(*anaVars,kTRUE,kTRUE) ;
482 TIterator* iter = factObs.createIterator() ;
483 RooAbsLValue* arg ;
484 while((arg=dynamic_cast<RooAbsLValue*>(iter->Next()))) {
485 ret *= arg->volume(rangeName) ;
486 }
487 delete iter ;
488 }
489
490 return ret ;
491}
#define coutI(a)
#define cxcoutD(a)
#define ccoutI(a)
const Bool_t kFALSE
Definition RtypesCore.h:92
const Bool_t kTRUE
Definition RtypesCore.h:91
#define ClassImp(name)
Definition Rtypes.h:364
static void indent(ostringstream &buf, int indent_level)
char name[80]
Definition TGX11.cxx:110
char * Form(const char *fmt,...)
@ kName
const std::vector< Int_t > & retrieve(Int_t masterCode) const
Retrieve the array of integer codes associated with the given master code.
Int_t store(const std::vector< Int_t > &codeList, RooArgSet *set1=0, RooArgSet *set2=0, RooArgSet *set3=0, RooArgSet *set4=0)
Store given arrays of integer codes, and up to four RooArgSets in the registry (each setX pointer may...
RooAbsArg is the common abstract base class for objects that represent a value and a "shape" in RooFi...
Definition RooAbsArg.h:72
RooExpensiveObjectCache & expensiveObjectCache() const
friend class RooArgSet
Definition RooAbsArg.h:606
virtual Bool_t isFundamental() const
Is this object a fundamental type that can be added to a dataset? Fundamental-type subclasses overrid...
Definition RooAbsArg.h:243
RooArgSet * getVariables(Bool_t stripDisconnected=kTRUE) const
Return RooArgSet with all variables (tree leaf nodes of expresssion tree)
friend class RooHistPdf
Definition RooAbsArg.h:629
void setValueDirty()
Mark the element dirty. This forces a re-evaluation when a value is requested.
Definition RooAbsArg.h:508
void addServerList(RooAbsCollection &serverList, Bool_t valueProp=kTRUE, Bool_t shapeProp=kFALSE)
Register a list of RooAbsArg as servers to us by calling addServer() for each arg in the list.
RooAbsCacheElement is the abstract base class for objects to be stored in RooAbsCache cache manager o...
virtual RooArgList containedArgs(Action)
Returns all RooAbsArg objects contained in the cache element.
RooChangeTracker * paramTracker()
PdfCacheElem(const RooAbsCachedPdf &self, const RooArgSet *nset)
Constructor of cache object which owns RooDataHist cache histogram, RooHistPdf pdf that represents is...
virtual ~PdfCacheElem()
Cache element destructor.
RooChangeTracker * _paramTracker
virtual void printCompactTreeHook(std::ostream &, const char *, Int_t, Int_t)
Print contents of cache when printing self as part of object tree.
RooAbsCachedPdf is the abstract base class for p.d.f.s that need or want to cache their evaluate() ou...
Int_t getInterpolationOrder() const
virtual Double_t analyticalIntegralWN(Int_t code, const RooArgSet *normSet, const char *rangeName=0) const
Implements internal (analytical) integration capabilities.
TString cacheNameSuffix(const RooArgSet &nset) const
Construct string with unique suffix for cache objects based on observable names that define cache con...
virtual RooAbsArg & pdfObservable(RooAbsArg &histObservable) const
virtual PdfCacheElem * createCache(const RooArgSet *nset) const
void setInterpolationOrder(Int_t order)
Change the interpolation order that is used in RooHistPdf cache representation smoothing the RooDataH...
virtual RooArgSet * actualParameters(const RooArgSet &nset) const =0
RooAICRegistry _anaReg
virtual TString histNameSuffix() const
virtual const char * binningName() const
virtual const char * inputBaseName() const =0
virtual Double_t getValV(const RooArgSet *set=0) const
Implementation of getVal() overriding default implementation of RooAbsPdf.
Bool_t _disableCache
Map for analytical integration codes.
PdfCacheElem * getCache(const RooArgSet *nset, Bool_t recalculate=kTRUE) const
Retrieve cache object associated with given choice of observables.
virtual Int_t getAnalyticalIntegralWN(RooArgSet &allVars, RooArgSet &analVars, const RooArgSet *normSet, const char *rangeName=0) const
Advertises internal (analytical) integration capabilities.
virtual ~RooAbsCachedPdf()
Destructor.
virtual Bool_t forceAnalyticalInt(const RooAbsArg &dep) const
Force RooRealIntegral to offer all our actual observable for internal integration.
RooAbsPdf * getCachePdf(const RooArgSet &nset) const
RooDataHist * getCacheHist(const RooArgSet &nset) const
virtual void fillCacheObject(PdfCacheElem &cache) const =0
void clearCacheObject(PdfCacheElem &cache) const
Mark all bins of given cache as unitialized (value -1)
RooObjCacheManager _cacheMgr
virtual const char * payloadUniqueSuffix() const
virtual RooArgSet * actualObservables(const RooArgSet &nset) const =0
Int_t getSize() const
virtual Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
virtual Bool_t remove(const RooAbsArg &var, Bool_t silent=kFALSE, Bool_t matchByNameOnly=kFALSE)
Remove the specified argument from our list.
TIterator * createIterator(Bool_t dir=kIterForward) const
TIterator-style iteration over contained elements.
Abstract base class for objects that are lvalues, i.e.
virtual Double_t volume(const char *rangeName) const =0
Double_t analyticalIntegralWN(Int_t code, const RooArgSet *normSet, const char *rangeName=0) const
Analytical integral with normalization (see RooAbsReal::analyticalIntegralWN() for further informatio...
RooAbsReal * _norm
Definition RooAbsPdf.h:321
virtual Double_t getValV(const RooArgSet *set=0) const
Return current value, normalized by integrating over the observables in nset.
virtual Int_t getAnalyticalIntegralWN(RooArgSet &allVars, RooArgSet &analVars, const RooArgSet *normSet, const char *rangeName=0) const
Variant of getAnalyticalIntegral that is also passed the normalization set that should be applied to ...
Double_t _value
Definition RooAbsReal.h:475
Double_t getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:91
virtual void preferredObservableScanOrder(const RooArgSet &obs, RooArgSet &orderedObs) const
Interface method for function objects to indicate their preferred order of observables for scanning t...
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:21
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:29
Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE) override
Add element to non-owning set.
RooAbsArg * addClone(const RooAbsArg &var, Bool_t silent=kFALSE) override
Add clone of specified element to an owning set.
Int_t cacheSize() const
T * getObj(const RooArgSet *nset, Int_t *sterileIndex=0, const TNamed *isetRangeName=0)
T * getObjByIndex(Int_t index) const
Retrieve payload object by slot index.
Int_t setObj(const RooArgSet *nset, T *obj, const TNamed *isetRangeName=0)
RooChangeTracker is a meta object that tracks value changes in a given set of RooAbsArgs by registeri...
Bool_t hasChanged(Bool_t clearState)
Returns true if state has changed since last call with clearState=kTRUE.
RooArgSet parameters() const
The RooDataHist is a container class to hold N-dimensional binned data.
Definition RooDataHist.h:37
virtual void add(const RooArgSet &row, Double_t wgt=1.0)
Add wgt to the bin content enclosed by the coordinates passed in row.
Definition RooDataHist.h:64
void removeSelfFromDir()
void setAllWeights(Double_t value)
Set all the event weight of all bins to the specified value.
void reset() override
Reset all bin weights to zero.
Bool_t registerObject(const char *ownerName, const char *objectName, TObject &cacheObject, TIterator *paramIter)
Register object associated with given name and given associated parameters with given values in cache...
const TObject * retrieveObject(const char *name, TClass *tclass, const RooArgSet &params)
Retrieve object from cache that was registered under given name with given parameters,...
Bool_t haveUnitNorm() const
Definition RooHistPdf.h:86
void setInterpolationOrder(Int_t order)
Definition RooHistPdf.h:47
virtual void printStream(std::ostream &os, Int_t contents, StyleOption style, TString indent="") const
Print description of object on ostream, printing contents set by contents integer,...
Iterator abstract base class.
Definition TIterator.h:30
virtual TObject * Next()=0
virtual const char * GetName() const
Returns name of object.
Definition TNamed.h:47
Basic string class.
Definition TString.h:136
TString & Append(const char *cs)
Definition TString.h:564
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:2331
Definition first.py:1