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
44
45
46
47////////////////////////////////////////////////////////////////////////////////
48/// Constructor
49
50RooAbsCachedReal::RooAbsCachedReal(const char *name, const char *title, Int_t ipOrder) :
51 RooAbsReal(name,title),
52 _cacheMgr(this,10),
53 _ipOrder(ipOrder),
54 _disableCache(false)
55 {
56 }
57
58
59
60////////////////////////////////////////////////////////////////////////////////
61/// Copy constructor
62
64 RooAbsReal(other,name),
65 _cacheMgr(other._cacheMgr,this),
66 _ipOrder(other._ipOrder),
67 _disableCache(other._disableCache)
68 {
69 }
70
71////////////////////////////////////////////////////////////////////////////////
72/// Implementation of getVal() overriding default implementation
73/// of RooAbsReal. Return value stored in cache p.d.f
74/// rather than return value of evaluate() which is undefined
75/// for RooAbsCachedReal
76
77double RooAbsCachedReal::getValV(const RooArgSet* nset) const
78{
79 if (_disableCache) {
80 return RooAbsReal::getValV(nset) ;
81 }
82
83 // Cannot call cached p.d.f w.o nset
84 // if (!nset) return evaluate() ;
85
86 // Calculate current unnormalized value of object
87 // coverity[NULL_RETURNS]
88 FuncCacheElem* cache = getCache(nset) ;
89
90 _value = cache->func()->getVal() ;
91
92 return _value ;
93}
94
95
96////////////////////////////////////////////////////////////////////////////////
97/// Interface function to create an internal cache object that represent
98/// each cached function configuration. This interface allows to create and
99/// return a class derived from RooAbsCachedReal::FuncCacheElem so that
100/// a derived class fillCacheObject implementation can utilize extra functionality
101/// defined in such a derived cache class
102
104{
105 return new FuncCacheElem(const_cast<RooAbsCachedReal&>(*this),nset) ;
106}
107
108
109
110////////////////////////////////////////////////////////////////////////////////
111/// Retrieve cache corresponding to observables in nset
112
114{
115 // Check if this configuration was created becfore
116 Int_t sterileIdx(-1) ;
117 FuncCacheElem* cache = static_cast<FuncCacheElem*>(_cacheMgr.getObj(nset,nullptr,&sterileIdx)) ;
118 if (cache) {
119 if (cache->paramTracker()->hasChanged(true)) {
120 ccoutD(Eval) << "RooAbsCachedReal::getCache(" << GetName() << ") cached function "
121 << cache->func()->GetName() << " requires recalculation as parameters changed" << endl ;
122 fillCacheObject(*cache) ;
123 cache->func()->setValueDirty() ;
124 }
125 return cache ;
126 }
127
128 cache = createCache(nset) ;
129
130 // Set cache function data to ADirty since function will need update every time in cache update process
131 for (auto* arg : *(cache->hist()->get()) ) {
132 arg->setOperMode(ADirty);
133 }
134
135 // Check if we have contents registered already in global expensive object cache
136 auto histTmp = static_cast<RooDataHist const*>(expensiveObjectCache().retrieveObject(cache->hist()->GetName(),RooDataHist::Class(),cache->paramTracker()->parameters()));
137
138 if (histTmp) {
139
140 cache->hist()->reset() ;
141 cache->hist()->add(*histTmp) ;
142
143 } else {
144
145 fillCacheObject(*cache) ;
146
147 RooDataHist* eoclone = new RooDataHist(*cache->hist()) ;
148 eoclone->removeSelfFromDir() ;
149 expensiveObjectCache().registerObject(GetName(),cache->hist()->GetName(),*eoclone,cache->paramTracker()->parameters()) ;
150 }
151
152 // Store this cache configuration
153 Int_t code = _cacheMgr.setObj(nset,nullptr,((RooAbsCacheElement*)cache),nullptr) ;
154 ccoutD(Caching) << "RooAbsCachedReal("<<this<<")::getCache(" << GetName() << ") creating new cache " << cache->func()->GetName() << " for nset " << (nset?*nset:RooArgSet()) << " with code " << code << endl ;
155
156 return cache ;
157}
158
159
160
161////////////////////////////////////////////////////////////////////////////////
162/// Constructor of cache storage unit class
163///
164/// Create RooDataHist that will cache function values and create
165/// RooHistFunc that represent s RooDataHist shape as function, create
166/// meta object that tracks changes in declared parameters of p.d.f
167/// through actualParameters()
168
170 : _sourceClone(nullptr), _cacheSource(false)
171{
172 // Disable source caching by default
173
174 std::unique_ptr<RooArgSet> nset2{self.actualObservables(nset?*nset:RooArgSet())};
175
176 RooArgSet orderedObs ;
177 self.preferredObservableScanOrder(*nset2,orderedObs) ;
178
179 // Create RooDataHist
180 auto hname = std::string(self.inputBaseName()) + "_CACHEHIST" + self.cacheNameSuffix(*nset2).Data();
181
182 _hist = new RooDataHist(hname,hname,*nset2,self.binningName()) ;
184
185 std::unique_ptr<RooArgSet> observables{self.actualObservables(*nset2)};
186
187 // Create RooHistFunc
188 TString funcname = self.inputBaseName() ;
189 funcname.Append("_CACHE") ;
190 funcname.Append(self.cacheNameSuffix(*nset2)) ;
191 _func = new RooHistFunc(funcname,funcname,*observables,*_hist,self.getInterpolationOrder()) ;
192 if (self.operMode()==ADirty) _func->setOperMode(ADirty) ;
193
194 // Set initial state of cache to dirty
196
197 // Create pseudo-object that tracks changes in parameter values
198 std::unique_ptr<RooArgSet> params{self.actualParameters(orderedObs)};
199 string name= Form("%s_CACHEPARAMS",_func->GetName()) ;
200 _paramTracker = new RooChangeTracker(name.c_str(),name.c_str(),*params,true) ;
201 _paramTracker->hasChanged(true) ; // clear dirty flag as cache is up-to-date upon creation
202
203 // Introduce formal dependency of RooHistFunc on parameters so that const optimization code
204 // makes the correct decisions
205 _func->addServerList(*params) ;
206}
207
208
209////////////////////////////////////////////////////////////////////////////////
210
212{
213 if (_sourceClone) { delete _sourceClone ; }
214 delete _paramTracker ;
215 delete _func ;
216 delete _hist ;
217}
218
219
220
221
222////////////////////////////////////////////////////////////////////////////////
223/// Construct unique suffix name for cache p.d.f object
224
226{
227 TString name ;
228 name.Append("_Obs[") ;
229 if (!nset.empty()) {
230 bool first(true) ;
231 for (RooAbsArg * arg : nset) {
232 if (first) {
233 first=false ;
234 } else {
235 name.Append(",") ;
236 }
237 name.Append(arg->GetName()) ;
238 }
239 }
240
241 name.Append("]") ;
242 const char* payloadUS = payloadUniqueSuffix() ;
243 if (payloadUS) {
244 name.Append(payloadUS) ;
245 }
246 return name ;
247}
248
249
250
251////////////////////////////////////////////////////////////////////////////////
252/// Set interpolation order of RooHistFunct representing cache histogram
253
255{
256 _ipOrder = order ;
257
258 for (Int_t i=0 ; i<_cacheMgr.cacheSize() ; i++) {
259 FuncCacheElem* cache = static_cast<FuncCacheElem*>(_cacheMgr.getObjByIndex(i)) ;
260 if (cache) {
261 cache->func()->setInterpolationOrder(order) ;
262 }
263 }
264}
265
266
267
268////////////////////////////////////////////////////////////////////////////////
269/// Return list of contained RooAbsArg objects
270
272{
273 RooArgList ret(*func()) ;
274
275 ret.add(*_paramTracker) ;
276 if (_sourceClone) {
277 ret.add(*_sourceClone) ;
278 }
279 return ret ;
280}
281
282
283////////////////////////////////////////////////////////////////////////////////
284/// Print contents of cache when printing self as part of object tree
285
286void RooAbsCachedReal::FuncCacheElem::printCompactTreeHook(ostream& os, const char* indent, Int_t curElem, Int_t maxElem)
287{
288 if (curElem==0) {
289 os << indent << "--- RooAbsCachedReal begin cache ---" << endl ;
290 }
291
292 TString indent2(indent) ;
293 indent2 += Form("[%d] ",curElem) ;
294 func()->printCompactTree(os,indent2) ;
295
296 if (curElem==maxElem) {
297 os << indent << "--- RooAbsCachedReal end cache --- " << endl ;
298 }
299}
300
301
302
303////////////////////////////////////////////////////////////////////////////////
304/// Return analytical integration capabilities of the RooHistFunc that corresponds to the set of observables in allVars
305
306Int_t RooAbsCachedReal::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* rangeName) const
307{
308 FuncCacheElem* cache = getCache(normSet?normSet:&allVars) ;
309 Int_t code = cache->func()->getAnalyticalIntegralWN(allVars,analVars,normSet,rangeName) ;
310 _anaIntMap[code].first = &allVars ;
311 _anaIntMap[code].second = normSet ;
312 return code ;
313}
314
315
316
317////////////////////////////////////////////////////////////////////////////////
318/// Forward call to implementation in relevant RooHistFunc instance
319
320double RooAbsCachedReal::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* rangeName) const
321{
322 if (code==0) {
323 return getVal(normSet) ;
324 }
325
326 const RooArgSet* anaVars = _anaIntMap[code].first ;
327 const RooArgSet* normSet2 = _anaIntMap[code].second ;
328
329 FuncCacheElem* cache = getCache(normSet2?normSet2:anaVars) ;
330 return cache->func()->analyticalIntegralWN(code,normSet,rangeName) ;
331
332}
333
334
335
336
337
#define ccoutD(a)
#define ClassImp(name)
Definition Rtypes.h:382
static void indent(ostringstream &buf, int indent_level)
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
OperMode operMode() const
Query the operation mode of this node.
Definition RooAbsArg.h:425
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 const char * inputBaseName() const =0
virtual FuncCacheElem * createCache(const RooArgSet *nset) const
Interface function to create an internal cache object that represent each cached function configurati...
virtual RooFit::OwningPtr< RooArgSet > actualParameters(const RooArgSet &nset) const =0
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.
Int_t getInterpolationOrder() const
virtual RooFit::OwningPtr< RooArgSet > actualObservables(const RooArgSet &nset) const =0
std::map< Int_t, std::pair< const RooArgSet *, const RooArgSet * > > _anaIntMap
! Map for analytical integration codes
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.
virtual const char * binningName() const
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
RooAbsArg * first() const
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 void preferredObservableScanOrder(const RooArgSet &obs, RooArgSet &orderedObs) const
Interface method for function objects to indicate their preferred order of observables for scanning t...
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
const char * Data() const
Definition TString.h:376
TString & Append(const char *cs)
Definition TString.h:572