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