Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooAbsCachedReal.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 RooAbsCachedReal.cxx
14\class RooAbsCachedReal
15\ingroup Roofitcore
16
17Abstract base class for functions that need or
18want to cache their evaluate() output in a RooHistFunc defined in
19terms of the used observables. This base class manages the creation
20and storage of all RooHistFunc cache p.d.fs and the RooDataHists
21that define their shape. Implementations of RooAbsCachedReal must
22define member function fillCacheObject() which serves to fill an
23already created RooDataHist with the functions 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 std::string, std::endl, std::ostream;
33
34#include "TString.h"
35#include "RooAbsCachedReal.h"
36#include "RooAbsReal.h"
37#include "RooMsgService.h"
38#include "RooDataHist.h"
39#include "RooHistFunc.h"
40#include "RooChangeTracker.h"
42
43
44
45
46////////////////////////////////////////////////////////////////////////////////
47/// Constructor
48
49RooAbsCachedReal::RooAbsCachedReal(const char *name, const char *title, Int_t ipOrder) :
50 RooAbsReal(name,title),
51 _cacheMgr(this,10),
52 _ipOrder(ipOrder),
53 _disableCache(false)
54 {
55 }
56
57
58
59////////////////////////////////////////////////////////////////////////////////
60/// Copy constructor
61
64 _cacheMgr(other._cacheMgr,this),
65 _ipOrder(other._ipOrder),
66 _disableCache(other._disableCache)
67 {
68 }
69
70////////////////////////////////////////////////////////////////////////////////
71/// Implementation of getVal() overriding default implementation
72/// of RooAbsReal. Return value stored in cache p.d.f
73/// rather than return value of evaluate() which is undefined
74/// for RooAbsCachedReal
75
76double RooAbsCachedReal::getValV(const RooArgSet* nset) const
77{
78 if (_disableCache) {
79 return RooAbsReal::getValV(nset) ;
80 }
81
82 // Cannot call cached p.d.f w.o nset
83 // if (!nset) return evaluate() ;
84
85 // Calculate current unnormalized value of object
86 // coverity[NULL_RETURNS]
87 FuncCacheElem* cache = getCache(nset) ;
88
89 _value = cache->func()->getVal() ;
90
91 return _value ;
92}
93
94
95////////////////////////////////////////////////////////////////////////////////
96/// Interface function to create an internal cache object that represent
97/// each cached function configuration. This interface allows to create and
98/// return a class derived from RooAbsCachedReal::FuncCacheElem so that
99/// a derived class fillCacheObject implementation can utilize extra functionality
100/// defined in such a derived cache class
101
103{
104 return new FuncCacheElem(const_cast<RooAbsCachedReal&>(*this),nset) ;
105}
106
107
108
109////////////////////////////////////////////////////////////////////////////////
110/// Retrieve cache corresponding to observables in nset
111
113{
114 // Check if this configuration was created becfore
115 Int_t sterileIdx(-1) ;
116 FuncCacheElem* cache = static_cast<FuncCacheElem*>(_cacheMgr.getObj(nset,nullptr,&sterileIdx)) ;
117 if (cache) {
118 if (cache->paramTracker()->hasChanged(true)) {
119 ccoutD(Eval) << "RooAbsCachedReal::getCache(" << GetName() << ") cached function "
120 << cache->func()->GetName() << " requires recalculation as parameters changed" << std::endl ;
121 fillCacheObject(*cache) ;
122 cache->func()->setValueDirty() ;
123 }
124 return cache ;
125 }
126
127 cache = createCache(nset) ;
128
129 // Set cache function data to ADirty since function will need update every time in cache update process
130 for (auto* arg : *(cache->hist()->get()) ) {
131 arg->setOperMode(ADirty);
132 }
133
134 // Check if we have contents registered already in global expensive object cache
136
137 if (histTmp) {
138
139 cache->hist()->reset() ;
140 cache->hist()->add(*histTmp) ;
141
142 } else {
143
144 fillCacheObject(*cache) ;
145
146 RooDataHist* eoclone = new RooDataHist(*cache->hist()) ;
147 eoclone->removeSelfFromDir() ;
149 }
150
151 // Store this cache configuration
152 Int_t code = _cacheMgr.setObj(nset,nullptr,((RooAbsCacheElement*)cache),nullptr) ;
153 ccoutD(Caching) << "RooAbsCachedReal("<<this<<")::getCache(" << GetName() << ") creating new cache " << cache->func()->GetName() << " for nset " << (nset?*nset:RooArgSet()) << " with code " << code << std::endl ;
154
155 return cache ;
156}
157
158
159
160////////////////////////////////////////////////////////////////////////////////
161/// Constructor of cache storage unit class
162///
163/// Create RooDataHist that will cache function values and create
164/// RooHistFunc that represent s RooDataHist shape as function, create
165/// meta object that tracks changes in declared parameters of p.d.f
166/// through actualParameters()
167
169 : _sourceClone(nullptr), _cacheSource(false)
170{
171 // Disable source caching by default
172
173 std::unique_ptr<RooArgSet> nset2{self.actualObservables(nset?*nset:RooArgSet())};
174
176 self.preferredObservableScanOrder(*nset2,orderedObs) ;
177
178 // Create RooDataHist
179 auto hname = std::string(self.inputBaseName()) + "_CACHEHIST" + self.cacheNameSuffix(*nset2).Data();
180
181 _hist = new RooDataHist(hname,hname,*nset2,self.binningName()) ;
183
184 std::unique_ptr<RooArgSet> observables{self.actualObservables(*nset2)};
185
186 // Create RooHistFunc
187 TString funcname = self.inputBaseName() ;
188 funcname.Append("_CACHE") ;
189 funcname.Append(self.cacheNameSuffix(*nset2)) ;
190 _func = new RooHistFunc(funcname,funcname,*observables,*_hist,self.getInterpolationOrder()) ;
191 if (self.operMode()==ADirty) _func->setOperMode(ADirty) ;
192
193 // Set initial state of cache to dirty
195
196 // Create pseudo-object that tracks changes in parameter values
197 std::unique_ptr<RooArgSet> params{self.actualParameters(orderedObs)};
198 string name= Form("%s_CACHEPARAMS",_func->GetName()) ;
199 _paramTracker = new RooChangeTracker(name.c_str(),name.c_str(),*params,true) ;
200 _paramTracker->hasChanged(true) ; // clear dirty flag as cache is up-to-date upon creation
201
202 // Introduce formal dependency of RooHistFunc on parameters so that const optimization code
203 // makes the correct decisions
204 _func->addServerList(*params) ;
205}
206
207
208////////////////////////////////////////////////////////////////////////////////
209
211{
212 if (_sourceClone) { delete _sourceClone ; }
213 delete _paramTracker ;
214 delete _func ;
215 delete _hist ;
216}
217
218
219
220
221////////////////////////////////////////////////////////////////////////////////
222/// Construct unique suffix name for cache p.d.f object
223
225{
226 TString name ;
227 name.Append("_Obs[") ;
228 if (!nset.empty()) {
229 bool first(true) ;
230 for (RooAbsArg * arg : nset) {
231 if (first) {
232 first=false ;
233 } else {
234 name.Append(",") ;
235 }
236 name.Append(arg->GetName()) ;
237 }
238 }
239
240 name.Append("]") ;
241 const char* payloadUS = payloadUniqueSuffix() ;
242 if (payloadUS) {
243 name.Append(payloadUS) ;
244 }
245 return name ;
246}
247
248
249
250////////////////////////////////////////////////////////////////////////////////
251/// Set interpolation order of RooHistFunct representing cache histogram
252
254{
255 _ipOrder = order ;
256
257 for (Int_t i=0 ; i<_cacheMgr.cacheSize() ; i++) {
258 FuncCacheElem* cache = static_cast<FuncCacheElem*>(_cacheMgr.getObjByIndex(i)) ;
259 if (cache) {
260 cache->func()->setInterpolationOrder(order) ;
261 }
262 }
263}
264
265
266
267////////////////////////////////////////////////////////////////////////////////
268/// Return list of contained RooAbsArg objects
269
271{
272 RooArgList ret(*func()) ;
273
274 ret.add(*_paramTracker) ;
275 if (_sourceClone) {
276 ret.add(*_sourceClone) ;
277 }
278 return ret ;
279}
280
281
282////////////////////////////////////////////////////////////////////////////////
283/// Print contents of cache when printing self as part of object tree
284
286{
287 if (curElem==0) {
288 os << indent << "--- RooAbsCachedReal begin cache ---" << std::endl ;
289 }
290
292 indent2 += Form("[%d] ",curElem) ;
293 func()->printCompactTree(os,indent2) ;
294
295 if (curElem==maxElem) {
296 os << indent << "--- RooAbsCachedReal end cache --- " << std::endl ;
297 }
298}
299
300
301
302////////////////////////////////////////////////////////////////////////////////
303/// Return analytical integration capabilities of the RooHistFunc that corresponds to the set of observables in allVars
304
306{
307 FuncCacheElem* cache = getCache(normSet?normSet:&allVars) ;
308 Int_t code = cache->func()->getAnalyticalIntegralWN(allVars,analVars,normSet,rangeName) ;
309 _anaIntMap[code].first = &allVars ;
310 _anaIntMap[code].second = normSet ;
311 return code ;
312}
313
314
315
316////////////////////////////////////////////////////////////////////////////////
317/// Forward call to implementation in relevant RooHistFunc instance
318
319double RooAbsCachedReal::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* rangeName) const
320{
321 if (code==0) {
322 return getVal(normSet) ;
323 }
324
325 const RooArgSet* anaVars = _anaIntMap[code].first ;
326 const RooArgSet* normSet2 = _anaIntMap[code].second ;
327
329 return cache->func()->analyticalIntegralWN(code,normSet,rangeName) ;
330
331}
332
333
334
335
336
#define ccoutD(a)
static void indent(ostringstream &buf, int indent_level)
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
char name[80]
Definition TGX11.cxx:110
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2489
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
RooExpensiveObjectCache & expensiveObjectCache() const
void setOperMode(OperMode mode, bool recurseADirty=true)
Set the operation mode of this node.
friend class RooHistFunc
Definition RooAbsArg.h:588
void addServerList(RooAbsCollection &serverList, bool valueProp=true, bool shapeProp=false)
Register a list of RooAbsArg as servers to us by calling addServer() for each arg in the list.
void setValueDirty()
Mark the element dirty. This forces a re-evaluation when a value is requested.
Definition RooAbsArg.h:431
Abstract base class for objects to be stored in RooAbsCache cache manager objects.
void printCompactTreeHook(std::ostream &, const char *, Int_t, Int_t) override
Print contents of cache when printing self as part of object tree.
RooChangeTracker * paramTracker()
RooArgList containedArgs(Action) override
Return list of contained RooAbsArg objects.
FuncCacheElem(const RooAbsCachedReal &self, const RooArgSet *nset)
Constructor of cache storage unit class.
Abstract base class for functions that need or want to cache their evaluate() output in a RooHistFunc...
void setInterpolationOrder(Int_t order)
Set interpolation order of RooHistFunct representing cache histogram.
virtual void fillCacheObject(FuncCacheElem &cache) const =0
virtual FuncCacheElem * createCache(const RooArgSet *nset) const
Interface function to create an internal cache object that represent each cached function configurati...
TString cacheNameSuffix(const RooArgSet &nset) const
Construct unique suffix name for cache p.d.f object.
FuncCacheElem * getCache(const RooArgSet *nset) const
Retrieve cache corresponding to observables in nset.
double analyticalIntegralWN(Int_t code, const RooArgSet *normSet, const char *rangeName=nullptr) const override
Forward call to implementation in relevant RooHistFunc instance.
RooObjCacheManager _cacheMgr
! The cache manager
Int_t _ipOrder
Interpolation order for cache histograms.
std::map< Int_t, std::pair< const RooArgSet *, const RooArgSet * > > _anaIntMap
! Map for analytical integration codes
friend class FuncCacheElem
Int_t getAnalyticalIntegralWN(RooArgSet &allVars, RooArgSet &analVars, const RooArgSet *normSet, const char *rangeName=nullptr) const override
Return analytical integration capabilities of the RooHistFunc that corresponds to the set of observab...
virtual const char * payloadUniqueSuffix() const
double getValV(const RooArgSet *set=nullptr) const override
Implementation of getVal() overriding default implementation of RooAbsReal.
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 getValV(const RooArgSet *normalisationSet=nullptr) const
Return value of object.
virtual Int_t getAnalyticalIntegralWN(RooArgSet &allVars, RooArgSet &analVars, const RooArgSet *normSet, const char *rangeName=nullptr) const
Variant of getAnalyticalIntegral that is also passed the normalization set that should be applied to ...
double _value
Cache for current value of object.
Definition RooAbsReal.h:535
virtual double analyticalIntegralWN(Int_t code, const RooArgSet *normSet, const char *rangeName=nullptr) const
Implements the actual analytical integral(s) advertised by getAnalyticalIntegral.
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
Int_t setObj(const RooArgSet *nset, T *obj, const TNamed *isetRangeName=nullptr)
Setter function without integration set.
Int_t cacheSize() const
Return size of cache.
T * getObjByIndex(Int_t index) const
Retrieve payload object by slot index.
T * getObj(const RooArgSet *nset, Int_t *sterileIndex=nullptr, const TNamed *isetRangeName=nullptr)
Getter function without integration set.
Meta object that tracks value changes in a given set of RooAbsArgs by registering itself as value cli...
bool hasChanged(bool clearState)
Returns true if state has changed since last call with clearState=true.
RooArgSet parameters() const
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
static TClass * Class()
void add(const RooArgSet &row, double wgt=1.0) override
Add wgt to the bin content enclosed by the coordinates passed in row.
Definition RooDataHist.h:72
void removeSelfFromDir()
void reset() override
Reset all bin weights to zero.
const RooArgSet * get() const override
Get bin centre of current bin.
Definition RooDataHist.h:82
bool registerObject(const char *ownerName, const char *objectName, TObject &cacheObject, const RooArgSet &params)
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,...
void setInterpolationOrder(Int_t order)
Set histogram interpolation order.
Definition RooHistFunc.h:63
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
Basic string class.
Definition TString.h:139