Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooTemplateProxy.h
Go to the documentation of this file.
1/*****************************************************************************
2 * Project: RooFit *
3 * Package: RooFitCore *
4 * File: $Id: RooRealProxy.h,v 1.23 2007/07/12 20:30:28 wouter Exp $
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#ifndef ROO_TEMPLATE_PROXY
17#define ROO_TEMPLATE_PROXY
18
19#include "RooAbsReal.h"
20#include "RooArgProxy.h"
21#include "RooAbsRealLValue.h"
22#include "RooAbsCategory.h"
23#include "RooMsgService.h"
24
25#include <string>
26
27/**
28\class RooTemplateProxy
29\ingroup Roofitcore
30
31## Introduction
32A RooTemplateProxy is used to hold references to other RooFit objects in an expression tree.
33A `RooGaussian(..., x, mean, sigma)` can e.g. store references to `x, mean, sigma` as
34```
35RooTemplateProxy<RooAbsReal> _x;
36RooTemplateProxy<RooAbsReal> _mean;
37RooTemplateProxy<RooAbsReal> _sigma;
38```
39Now, the values of these three can be accessed, and the template argument ensures that only objects that evaluate
40to real numbers (RooAbsReal) can be stored in such a proxy. These can e.g. be variables, PDFs and functions.
41To store an object that's a `RooCategory`, one would, for example, use
42```
43RooTemplateProxy<RooCategory> _category;
44```
45
46Since %ROOT 6.22, the proxy can be used like a pointer to an instance of the template argument.
47For this, it provides `operator*` and `operator->`, e.g.
48```
49double oldValue = _x->getVal(normalisationSet);
50*_x = 17.;
51```
52
53RooTemplateProxy's base class RooArgProxy registers the proxied objects as "servers" of the object
54that holds the proxy. When the value of the proxied object is changed, the owner is
55notified, and can recalculate its own value. Renaming or exchanging objects that
56serve values to the owner of the proxy is handled automatically.
57
58## Modernisation of proxies in ROOT 6.22
59In ROOT 6.22, the classes RooRealProxy and RooCategoryProxy were replaced by RooTemplateProxy<class T>.
60
61Two typedefs have been defined for backward compatibility:
62- `RooRealProxy = RooTemplateProxy<RooAbsReal>`. Any generic object that converts to a real value.
63- `RooCategoryProxy = RooTemplateProxy<RooAbsCategory>`. Any category object.
64
65To modernise a class, one can change the template argument of the proxy to the most appropriate type,
66and increment the class version of the owner.
67
68<table>
69<tr><th> %RooFit before %ROOT 6.22 <th> %RooFit starting with %ROOT 6.22
70<tr><td>
71~~~{.cpp}
72// In .h: Declare member
73RooRealProxy pdfProxy;
74
75ClassDefOverride(MyPdf, 1)
76};
77
78// In .cxx: Initialise proxy in constructor
79// The proxy will accept any RooAbsArg, so the type of
80// "thePdf" has to be checked manually.
81MyPdf::MyPdf(name, title, ...) :
82 pdfProxy("pdfProxy", "Proxy holding a PDF", this, thePdf) {
83 [ Extra checking here ... ]
84}
85
86
87// In .cxx: Accessing the proxy
88RooAbsArg* absArg = pdfProxy.absArg();
89RooAbsPdf* pdf = dynamic_cast<RooAbsPdf*>(absArg);
90assert(pdf); // Manual type checking ...
91pdf->fitTo(...);
92~~~
93<td>
94~~~{.cpp}
95// In .h: Declare member
96RooTemplateProxy<RooAbsPdf> pdfProxy;
97
98ClassDefOverride(MyPdf, 2)
99};
100
101// In .cxx: Initialise proxy in constructor
102// The program will not compile if "thePdf" is not a
103// type deriving from RooAbsPdf
104MyPdf::MyPdf(name, title, ...) :
105 pdfProxy("pdfProxy", "Proxy holding a PDF", this, thePdf) {
106
107}
108
109
110// In .cxx: Accessing the proxy
111
112
113
114pdfProxy->fitTo(...);
115~~~
116</table>
117
118
119### How to modernise old code
120
1211. Choose the proper template argument for the proxy.
122 - If a PDF is stored: `RooTemplateProxy<RooAbsPdf>`.
123 - If a real-valued object is stored: `RooTemplateProxy<RooAbsReal>`.
124 - If a category is stored: `RooTemplateProxy<RooCategory>`.
125 - If a variable is stored (i.e. one wants to be able to assign values to it): `RooTemplateProxy<RooRealVar>`
126 Other template arguments are possible, as long as they derive from RooAbsArg.
1272. Increment the class version of the owning class.
1283. Make sure that the right type is passed in the constructor of the proxy.
1294. Always use `proxy->` and `*proxy` to work with the stored object. No need to cast.
1305. **Only if necessary** If errors about missing symbols connected to RooTemplateProxy appear at link time,
131 a specific template instantiation for RooTemplateProxy is not yet in ROOT's dictionaries.
132 These two lines should be added to the LinkDef.h of the project:
133 ~~~{.cpp}
134 #pragma link C++ class RooTemplateProxy<RooMultiCategory>+;
135 #pragma read sourceClass="RooCategoryProxy" targetClass="RooTemplateProxy<RooMultiCategory>"
136 ~~~
137 Replace `RooMultiCategory` by the proper type. If the proxy was holding a real-valued object, use `sourceClass="RooRealProxy"`.
138
139 The first line adds the proxy class to the dictionary, the second line enables reading a legacy
140 `RooCategoryProxy` from a file, and converting it to the new type-safe proxy. If no old proxies
141 have to be read from files, this line can be omitted.
142
143 If the template instantiation that triggered the missing symbols seems to be a very common instantiation,
144 request for it to be added to RooFit by creating a pull request for ROOT. If it is rather uncommon,
145 it is sufficient to add it to the LinkDef.h of the local project only.
146
147**/
148
149template<class T>
151public:
152
154
155 ////////////////////////////////////////////////////////////////////////////////
156 /// Constructor with owner.
157 /// \param[in] theName Name of this proxy (for printing).
158 /// \param[in] desc Description what this proxy should act as.
159 /// \param[in] owner The object that owns the proxy. This is important for tracking
160 /// of client-server dependencies.
161 /// \param[in] valueServer Notify the owner if value changes.
162 /// \param[in] shapeServer Notify the owner if shape (e.g. binning) changes.
163 template<typename Bool = bool, typename = std::enable_if_t<std::is_same<Bool,bool>::value>>
164 RooTemplateProxy(const char* theName, const char* desc, RooAbsArg* owner,
165 Bool valueServer=true, bool shapeServer=false)
166 : RooArgProxy(theName, desc, owner, valueServer, shapeServer, false) {
167 // Note for developers: the type of the first bool parameter is templated
168 // such that implicit conversion from int or pointers to bool is disabled.
169 // This is because there is another constructor with the signature
170 // `RooTemplateProxy(name, title, owner, T& ref)`. It happened already more
171 // than once that other developers accidentally used a `T*` pointer instead
172 // of a reference, in which case it resolved to this constructor via
173 // implicit conversion to bool. This is completely meaningless and should
174 // not happen.
175 }
176
177 ////////////////////////////////////////////////////////////////////////////////
178 /// Constructor with owner and proxied object.
179 /// \param[in] theName Name of this proxy (for printing).
180 /// \param[in] desc Description what this proxy should act as.
181 /// \param[in] owner The object that owns the proxy. This is important for tracking
182 /// of client-server dependencies.
183 /// \param[in] ref Reference to the object that the proxy should hold.
184 /// \param[in] valueServer Notify the owner if value changes.
185 /// \param[in] shapeServer Notify the owner if shape (e.g. binning) changes.
186 RooTemplateProxy(const char* theName, const char* desc, RooAbsArg* owner, T& ref,
187 bool valueServer=true, bool shapeServer=false) :
188 RooArgProxy(theName, desc, owner, const_cast<typename std::remove_const<T>::type&>(ref), valueServer, shapeServer, false) { }
189
190 ////////////////////////////////////////////////////////////////////////////////
191 /// Constructor with owner and proxied object, taking ownership of the proxied object.
192 ///
193 /// \param[in] theName Name of this proxy (for printing).
194 /// \param[in] desc Description what this proxy should act as.
195 /// \param[in] owner The object that owns the proxy. This is important for tracking
196 /// of client-server dependencies.
197 /// \param[in] ptr Owning smart pointer to the object that the proxy should hold. Ownership will be transferred to the proxy.
198 /// \param[in] valueServer Notify the owner if value changes.
199 /// \param[in] shapeServer Notify the owner if shape (e.g. binning) changes.
200 RooTemplateProxy(const char *theName, const char *desc, RooAbsArg *owner, std::unique_ptr<T> ptr,
201 bool valueServer = true, bool shapeServer = false)
202 : RooArgProxy(theName, desc, owner, *ptr, valueServer, shapeServer, true)
203 {
204 ptr.release();
205 }
206
207
208 ////////////////////////////////////////////////////////////////////////////////
209 /// Copy from an existing proxy.
210 /// It will accept any RooTemplateProxy instance, and attempt a dynamic_cast on its payload.
211 /// \param[in] theName Name of this proxy.
212 /// \param[in] owner Pointer to the owner this proxy should be registered to.
213 /// \param[in] other Instance of a different proxy whose payload should be copied.
214 /// \param[in] allowWrongTypes Instead of throwing a std::invalid_argument, only issue an
215 /// error message when payload with wrong type is found. This is unsafe, but may be necessary
216 /// when reading back legacy types. Defaults to false.
217 /// \throw std::invalid_argument if the types of the payloads are incompatible.
218 template<typename U>
219 RooTemplateProxy(const char* theName, RooAbsArg* owner, const RooTemplateProxy<U>& other, bool allowWrongTypes = false) :
220 RooArgProxy(theName, owner, other) {
221 if (_arg && !dynamic_cast<const T*>(_arg)) {
222 if (allowWrongTypes) {
223 coutE(InputArguments) << "Error trying to copy an argument from a proxy with an incompatible payload." << std::endl;
224 } else {
225 throw std::invalid_argument("Tried to construct a RooTemplateProxy with incompatible payload.");
226 }
227 }
228 }
229
230 TObject* Clone(const char* newName=nullptr) const override { return new RooTemplateProxy<T>(newName,_owner,*this); }
231
232
233 /// Return reference to the proxied object.
234 T& operator*() const {
235 return static_cast<T&>(*_arg);
236 }
237
238 /// Member access operator to proxied object.
239 T* operator->() const {
240 return static_cast<T*>(_arg);
241 }
242
243
244 /// Convert the proxy into a number.
245 /// \return A category proxy will return the index state, real proxies the result of RooAbsReal::getVal(normSet).
246 operator typename T::value_type() const {
247 return retrieveValue(arg());
248 }
249
250
251 ////////////////////////////////////////////////////////////////////////////////
252 /// Change object held in proxy into newRef
253 bool setArg(T& newRef) {
254 if (_arg) {
255 if (std::string(arg().GetName()) != newRef.GetName()) {
256 newRef.setAttribute(("ORIGNAME:" + std::string(arg().GetName())).c_str()) ;
257 }
258 return changePointer(RooArgSet(newRef), true);
259 } else {
260 return changePointer(RooArgSet(newRef), false, true);
261 }
262 }
263
264
265 ////////////////////////////////////////////////////////////////////////////////
266 /// Create a new object held and owned by proxy.
267 /// Can only be done if the proxy was non-owning before.
268 template<class U, class... ConstructorArgs>
269 U& emplaceOwnedArg(ConstructorArgs&&... constructorArgs) {
270 if(_ownArg) {
271 // let's maybe not support overwriting owned args unless it becomes necessary
272 throw std::runtime_error("Error in RooTemplateProxy: emplaceOwnedArg<>() called on a proxy already owning an arg.");
273 }
274 auto ownedArg = new U{std::forward<ConstructorArgs>(constructorArgs)...};
275 setArg(*ownedArg);
276 _ownArg = true;
277 return *ownedArg;
278 }
279
280
281 ////////////////////////////////////////////////////////////////////////////////
282 /// Move a new object held and owned by proxy.
283 /// Can only be done if the proxy was non-owning before.
284 template<class U>
285 U& putOwnedArg(std::unique_ptr<U> ownedArg) {
286 if(_ownArg) {
287 // let's maybe not support overwriting owned args unless it becomes necessary
288 throw std::runtime_error("Error in RooTemplateProxy: putOwnedArg<>() called on a proxy already owning an arg.");
289 }
290 auto argPtr = ownedArg.get();
291 setArg(*ownedArg.release());
292 _ownArg = true;
293 return *argPtr;
294 }
295
296 /// \name Legacy interface
297 /// In ROOT versions before 6.22, RooFit didn't have this typed proxy. Therefore, a number of functions
298 /// for forwarding calls to the proxied objects were necessary. The functions in this group can all be
299 /// replaced by directly accessing the proxied objects using e.g. the member access operator like
300 /// `proxy->function()` or by dereferencing like `*proxy = value`.
301 /// For this to work, choose the template argument appropriately. That is, if the
302 /// proxy stores a PDF, use `RooTemplateProxy<RooAbsPdf>`, *etc.*.
303 /// @{
304
305 /// Get the label of the current category state. This function only makes sense for category proxies.
306 const char* label() const {
307 return arg().getCurrentLabel();
308 }
309
310 /// Check if the stored object has a range with the given name.
311 bool hasRange(const char* rangeName) const {
312 return arg().hasRange(rangeName);
313 }
314
315 /// Return reference to object held in proxy.
316 const T& arg() const { return static_cast<const T&>(*_arg); }
317
318 /// Assign a new value to the object pointed to by the proxy.
319 /// This requires the payload to be assignable (RooAbsRealLValue or derived, RooAbsCategoryLValue).
320 RooTemplateProxy<T>& operator=(typename T::value_type value) {
321 lvptr(static_cast<T*>(nullptr))->operator=(value);
322 return *this;
323 }
324 /// Set a category state using its state name. This function can only work for category-type proxies.
325 RooTemplateProxy<T>& operator=(const std::string& newState) {
326 static_assert(std::is_base_of<RooAbsCategory, T>::value, "Strings can only be assigned to category proxies.");
327 lvptr(static_cast<RooAbsCategoryLValue*>(nullptr))->operator=(newState.c_str());
328 return *this;
329 }
330
331 /// Query lower limit of range. This requires the payload to be RooAbsRealLValue or derived.
332 double min(const char* rname=nullptr) const { return lvptr(static_cast<const T*>(nullptr))->getMin(rname) ; }
333 /// Query upper limit of range. This requires the payload to be RooAbsRealLValue or derived.
334 double max(const char* rname=nullptr) const { return lvptr(static_cast<const T*>(nullptr))->getMax(rname) ; }
335 /// Check if the range has a lower bound. This requires the payload to be RooAbsRealLValue or derived.
336 bool hasMin(const char* rname=nullptr) const { return lvptr(static_cast<const T*>(nullptr))->hasMin(rname) ; }
337 /// Check if the range has a upper bound. This requires the payload to be RooAbsRealLValue or derived.
338 bool hasMax(const char* rname=nullptr) const { return lvptr(static_cast<const T*>(nullptr))->hasMax(rname) ; }
339
340 /// @}
341
342
343private:
344 /// Are we a real-valued proxy or a category proxy?
345 using LValue_t = typename std::conditional<std::is_base_of<RooAbsReal, T>::value,
347
348 ////////////////////////////////////////////////////////////////////////////////
349 /// Return l-value pointer to contents. If the contents derive from RooAbsLValue or RooAbsCategoryLValue,
350 /// the conversion is safe, and the function directly returns the pointer using a static_cast.
351 /// If the template parameter of this proxy is not an LValue type, then
352 /// - in a debug build, a dynamic_cast with an assertion is used.
353 /// - in a release build, a static_cast is forced, irrespective of what the type of the object actually is. This
354 /// is dangerous, but equivalent to the behaviour before refactoring the RooFit proxies.
355 /// \deprecated This function is unnecessary if the template parameter is RooAbsRealLValue (+ derived types) or
356 /// RooAbsCategoryLValue (+derived types), as arg() will always return the correct type.
357 const LValue_t* lvptr(const LValue_t*) const {
358 return static_cast<const LValue_t*>(_arg);
359 }
360 /// \copydoc lvptr(const LValue_t*) const
362 return static_cast<LValue_t*>(_arg);
363 }
364 /// \copydoc lvptr(const LValue_t*) const
365 const LValue_t* lvptr(const RooAbsArg*) const
366 R__SUGGEST_ALTERNATIVE("The template argument of RooTemplateProxy needs to derive from RooAbsRealLValue or RooAbsCategoryLValue to safely call this function.") {
367#ifdef NDEBUG
368 return static_cast<const LValue_t*>(_arg);
369#else
370 auto theArg = dynamic_cast<const LValue_t*>(_arg);
371 assert(theArg);
372 return theArg;
373#endif
374 }
375 /// \copydoc lvptr(const LValue_t*) const
377 R__SUGGEST_ALTERNATIVE("The template argument of RooTemplateProxy needs to derive from RooAbsRealLValue or RooAbsCategoryLValue to safely call this function.") {
378#ifdef NDEBUG
379 return static_cast<LValue_t*>(_arg);
380#else
381 auto theArg = dynamic_cast<LValue_t*>(_arg);
382 assert(theArg);
383 return theArg;
384#endif
385 }
386
387
388 /// Retrieve index state from a category.
389 typename T::value_type retrieveValue(const RooAbsCategory& cat) const {
390 return cat.getCurrentIndex();
391 }
392
393 /// Retrieve value from a real-valued object.
394 typename T::value_type retrieveValue(const RooAbsReal& real) const {
395 return real.getVal(_nset);
396 }
397
398 ClassDefOverride(RooTemplateProxy,1) // Proxy for a RooAbsReal object
399};
400
401#endif
#define R__SUGGEST_ALTERNATIVE(ALTERNATIVE)
Definition RConfig.hxx:520
#define coutE(a)
#define ClassDefOverride(name, id)
Definition Rtypes.h:346
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
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 Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
Abstract base class for objects that represent a discrete value that can be set from the outside,...
A space to attach TBranches.
virtual value_type getCurrentIndex() const
Return index number of current state.
RooArgSet * _nset
! Normalization set to be used for evaluation of RooAbsPdf contents
Definition RooAbsProxy.h:60
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
Abstract interface for RooAbsArg proxy classes.
Definition RooArgProxy.h:24
RooAbsArg * _owner
Pointer to owner of proxy.
Definition RooArgProxy.h:77
bool _ownArg
If true proxy owns contents.
Definition RooArgProxy.h:83
RooAbsArg * owner() const
Returns the owner of this proxy.
Definition RooArgProxy.h:57
RooAbsArg * _arg
Pointer to content of proxy.
Definition RooArgProxy.h:78
bool changePointer(const RooAbsCollection &newServerSet, bool nameChange=false, bool factoryInitMode=false) override
Change proxied object to object of same name in given list.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
TObject * Clone(const char *newName=nullptr) const override
Make a clone of an object using the Streamer facility.
LValue_t * lvptr(RooAbsArg *)
Return l-value pointer to contents.
bool hasRange(const char *rangeName) const
Check if the stored object has a range with the given name.
T & operator*() const
Return reference to the proxied object.
T::value_type retrieveValue(const RooAbsCategory &cat) const
Retrieve index state from a category.
RooTemplateProxy(const char *theName, RooAbsArg *owner, const RooTemplateProxy< U > &other, bool allowWrongTypes=false)
Copy from an existing proxy.
RooTemplateProxy< T > & operator=(typename T::value_type value)
Assign a new value to the object pointed to by the proxy.
RooTemplateProxy(const char *theName, const char *desc, RooAbsArg *owner, T &ref, bool valueServer=true, bool shapeServer=false)
Constructor with owner and proxied object.
bool hasMin(const char *rname=nullptr) const
Check if the range has a lower bound. This requires the payload to be RooAbsRealLValue or derived.
RooTemplateProxy(const char *theName, const char *desc, RooAbsArg *owner, Bool valueServer=true, bool shapeServer=false)
Constructor with owner.
U & putOwnedArg(std::unique_ptr< U > ownedArg)
Move a new object held and owned by proxy.
RooTemplateProxy< T > & operator=(const std::string &newState)
Set a category state using its state name. This function can only work for category-type proxies.
const LValue_t * lvptr(const RooAbsArg *) const
Return l-value pointer to contents.
RooTemplateProxy(const char *theName, const char *desc, RooAbsArg *owner, std::unique_ptr< T > ptr, bool valueServer=true, bool shapeServer=false)
Constructor with owner and proxied object, taking ownership of the proxied object.
const LValue_t * lvptr(const LValue_t *) const
Return l-value pointer to contents.
const char * label() const
Get the label of the current category state. This function only makes sense for category proxies.
bool hasMax(const char *rname=nullptr) const
Check if the range has a upper bound. This requires the payload to be RooAbsRealLValue or derived.
double max(const char *rname=nullptr) const
Query upper limit of range. This requires the payload to be RooAbsRealLValue or derived.
T * operator->() const
Member access operator to proxied object.
LValue_t * lvptr(LValue_t *)
Return l-value pointer to contents.
T::value_type retrieveValue(const RooAbsReal &real) const
Retrieve value from a real-valued object.
bool setArg(T &newRef)
Change object held in proxy into newRef.
U & emplaceOwnedArg(ConstructorArgs &&... constructorArgs)
Create a new object held and owned by proxy.
const T & arg() const
Return reference to object held in proxy.
double min(const char *rname=nullptr) const
Query lower limit of range. This requires the payload to be RooAbsRealLValue or derived.
typename std::conditional< std::is_base_of< RooAbsReal, T >::value, RooAbsRealLValue, RooAbsCategoryLValue >::type LValue_t
Are we a real-valued proxy or a category proxy?
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
Mother of all ROOT objects.
Definition TObject.h:41