Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooMomentMorph.cxx
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 *
4 * Copyright (c) 2023, CERN
5 *
6 * Redistribution and use in source and binary forms,
7 * with or without modification, are permitted according to the terms
8 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
9 */
10
11/** \class RooMomentMorph
12 \ingroup Roofit
13
14**/
15
16#include "Riostream.h"
17
18#include "RooMomentMorph.h"
19#include "RooAbsCategory.h"
20#include "RooRealConstant.h"
21#include "RooRealVar.h"
22#include "RooFormulaVar.h"
23#include "RooCustomizer.h"
24#include "RooAddPdf.h"
25#include "RooAddition.h"
26#include "RooMoment.h"
27#include "RooLinearVar.h"
28#include "RooChangeTracker.h"
29
30#include "TMath.h"
31#include "TH1.h"
32
34
35////////////////////////////////////////////////////////////////////////////////
36/// coverity[UNINIT_CTOR]
37
39 : _cacheMgr(this,10,true,true), _curNormSet(nullptr), _mref(nullptr), _M(nullptr), _useHorizMorph(true)
40{
41}
42
43////////////////////////////////////////////////////////////////////////////////
44/// CTOR
45
46RooMomentMorph::RooMomentMorph(const char *name, const char *title, RooAbsReal &_m, const RooArgList &varList,
47 const RooArgList &pdfList, const TVectorD &mrefpoints, Setting setting)
48 : RooAbsPdf(name, title),
49 _cacheMgr(this, 10, true, true),
50 m("m", "m", this, _m),
51 _varList("varList", "List of variables", this),
52 _pdfList("pdfList", "List of pdfs", this),
53 _mref(new TVectorD(mrefpoints)),
54 _setting(setting),
55 _useHorizMorph(true)
56{
57 // observables
59
60 // reference p.d.f.s
61 _pdfList.addTyped<RooAbsPdf>(pdfList);
62
63 // initialization
64 initialize();
65}
66
67////////////////////////////////////////////////////////////////////////////////
68/// CTOR
69
70RooMomentMorph::RooMomentMorph(const char *name, const char *title, RooAbsReal &_m, const RooArgList &varList,
71 const RooArgList &pdfList, const RooArgList &mrefList, Setting setting)
72 : RooAbsPdf(name, title),
73 _cacheMgr(this, 10, true, true),
74 m("m", "m", this, _m),
75 _varList("varList", "List of variables", this),
76 _pdfList("pdfList", "List of pdfs", this),
77 _mref(new TVectorD(mrefList.size())),
78 _setting(setting),
79 _useHorizMorph(true)
80{
81 // observables
83
84 // reference p.d.f.s
85 _pdfList.addTyped<RooAbsPdf>(pdfList);
86
87 // reference points in m
88
89 Int_t i = 0;
90 for (auto *mref : mrefList) {
91 if (!dynamic_cast<RooAbsReal*>(mref)) {
92 coutE(InputArguments) << "RooMomentMorph::ctor(" << GetName() << ") ERROR: mref " << mref->GetName() << " is not of type RooAbsReal" << std::endl ;
93 throw std::string("RooPolyMorh::ctor() ERROR mref is not of type RooAbsReal") ;
94 }
95 if (!dynamic_cast<RooConstVar*>(mref)) {
96 coutW(InputArguments) << "RooMomentMorph::ctor(" << GetName() << ") WARNING mref point " << i << " is not a constant, taking a snapshot of its value" << std::endl ;
97 }
98 (*_mref)[i] = static_cast<RooAbsReal*>(mref)->getVal() ;
99 i++;
100 }
101
102 // initialization
103 initialize();
104}
105
106////////////////////////////////////////////////////////////////////////////////
107
109 : RooAbsPdf(other, name),
110 _cacheMgr(other._cacheMgr, this),
111 _curNormSet(nullptr),
112 m("m", this, other.m),
113 _varList("varList", this, other._varList),
114 _pdfList("pdfList", this, other._pdfList),
115 _mref(new TVectorD(*other._mref)),
116 _setting(other._setting),
117 _useHorizMorph(other._useHorizMorph)
118{
119
120 // initialization
121 initialize();
122}
123
124////////////////////////////////////////////////////////////////////////////////
125
127{
128 if (_mref) delete _mref;
129 if (_M) delete _M;
130}
131
132////////////////////////////////////////////////////////////////////////////////
133
135{
136 Int_t nPdf = _pdfList.size();
137
138 // other quantities needed
139 if (nPdf!=_mref->GetNrows()) {
140 coutE(InputArguments) << "RooMomentMorph::initialize(" << GetName() << ") ERROR: nPdf != nRefPoints" << std::endl ;
141 assert(0) ;
142 }
143
144 TVectorD dm{nPdf};
145 _M = new TMatrixD(nPdf,nPdf);
146
147 // transformation matrix for non-linear extrapolation, needed in evaluate()
148 TMatrixD M(nPdf,nPdf);
149 for (Int_t i=0; i<_mref->GetNrows(); ++i) {
150 dm[i] = (*_mref)[i]-(*_mref)[0];
151 M(i,0) = 1.;
152 if (i>0) M(0,i) = 0.;
153 }
154 for (Int_t i=1; i<_mref->GetNrows(); ++i) {
155 for (Int_t j=1; j<_mref->GetNrows(); ++j) {
156 M(i,j) = TMath::Power(dm[i],(double)j);
157 }
158 }
159 (*_M) = M.Invert();
160}
161
162////////////////////////////////////////////////////////////////////////////////
163
164RooMomentMorph::CacheElem::CacheElem(std::unique_ptr<RooAbsPdf> && sumPdf,
165 std::unique_ptr<RooChangeTracker> && tracker,
166 const RooArgList& flist)
167 : _sumPdf(std::move(sumPdf)), _tracker(std::move(tracker)) {
168 _frac.add(flist);
169}
170
171////////////////////////////////////////////////////////////////////////////////
172
174{
175 if (auto* cache = static_cast<CacheElem*>(_cacheMgr.getObj(nullptr,static_cast<RooArgSet*>(nullptr)))) {
176 return cache ;
177 }
178 Int_t nVar = _varList.size();
179 Int_t nPdf = _pdfList.size();
180
181 RooAbsReal* null = nullptr;
182 std::vector<RooAbsReal*> meanrv(nPdf*nVar,null);
183 std::vector<RooAbsReal*> sigmarv(nPdf*nVar,null);
184 std::vector<RooAbsReal*> myrms(nVar,null);
185 std::vector<RooAbsReal*> mypos(nVar,null);
186 std::vector<RooAbsReal*> slope(nPdf*nVar,null);
187 std::vector<RooAbsReal*> offs(nPdf*nVar,null);
188 std::vector<RooAbsReal*> transVar(nPdf*nVar,null);
189 std::vector<RooAbsReal*> transPdf(nPdf,null);
190
191 RooArgSet ownedComps ;
192
193 RooArgList fracl ;
194
195 // fraction parameters
196 RooArgList coefList("coefList");
197 RooArgList coefList2("coefList2");
198 for (Int_t i=0; i<2*nPdf; ++i) {
199 std::string fracName = "frac_" + std::to_string(i);
200
201 RooRealVar* frac = new RooRealVar(fracName.c_str(),fracName.c_str(),1.) ;
202
203 fracl.add(*frac); // to be set later
204 if (i<nPdf) coefList.add(*frac);
205 else coefList2.add(*frac);
206 ownedComps.add(*frac);
207 }
208
209 std::unique_ptr<RooAddPdf> theSumPdf;
210 std::string sumpdfName = Form("%s_sumpdf",GetName());
211
212 if (_useHorizMorph) {
213 // mean and sigma
214 RooArgList varList(_varList) ;
215 for (Int_t i=0; i<nPdf; ++i) {
216 for (Int_t j=0; j<nVar; ++j) {
217
218 std::string meanName = Form("%s_mean_%d_%d",GetName(),i,j);
219 std::string sigmaName = Form("%s_sigma_%d_%d",GetName(),i,j);
220
221 RooAbsMoment* mom = nVar==1 ?
222 (static_cast<RooAbsPdf*>(_pdfList.at(i)))->sigma(static_cast<RooRealVar&>(*varList.at(j))) :
223 (static_cast<RooAbsPdf*>(_pdfList.at(i)))->sigma(static_cast<RooRealVar&>(*varList.at(j)),varList) ;
224
225 mom->setLocalNoDirtyInhibit(true) ;
226 mom->mean()->setLocalNoDirtyInhibit(true) ;
227
228 sigmarv[ij(i,j)] = mom ;
229 meanrv[ij(i,j)] = mom->mean() ;
230
231 ownedComps.add(*sigmarv[ij(i,j)]) ;
232 }
233 }
234
235 // slope and offset (to be set later, depend on m)
236 for (Int_t j=0; j<nVar; ++j) {
237 RooArgList meanList("meanList");
238 RooArgList rmsList("rmsList");
239 for (Int_t i=0; i<nPdf; ++i) {
240 meanList.add(*meanrv[ij(i,j)]);
241 rmsList.add(*sigmarv[ij(i,j)]);
242 }
243 std::string myrmsName = Form("%s_rms_%d",GetName(),j);
244 std::string myposName = Form("%s_pos_%d",GetName(),j);
245 myrms[j] = new RooAddition(myrmsName.c_str(),myrmsName.c_str(),rmsList,coefList2);
246 mypos[j] = new RooAddition(myposName.c_str(),myposName.c_str(),meanList,coefList2);
247 ownedComps.add(RooArgSet(*myrms[j],*mypos[j])) ;
248 }
249
250 // construction of unit pdfs
251 RooArgList transPdfList;
252
253 for (Int_t i=0; i<nPdf; ++i) {
254
255 auto& pdf = static_cast<RooAbsPdf&>(_pdfList[i]);
256 std::string pdfName = "pdf_" + std::to_string(i);
257 RooCustomizer cust(pdf,pdfName.c_str());
258
259 for (Int_t j=0; j<nVar; ++j) {
260 // slope and offset formulas
261 std::string slopeName = Form("%s_slope_%d_%d",GetName(),i,j);
262 std::string offsetName = Form("%s_offset_%d_%d",GetName(),i,j);
263 slope[ij(i,j)] = new RooFormulaVar(slopeName.c_str(),"@0/@1", {*sigmarv[ij(i,j)],*myrms[j]});
264 offs[ij(i,j)] = new RooFormulaVar(offsetName.c_str(),"@0-(@1*@2)", {*meanrv[ij(i,j)],*mypos[j],*slope[ij(i,j)]});
265 ownedComps.add(RooArgSet(*slope[ij(i,j)],*offs[ij(i,j)])) ;
266 // linear transformations, so pdf can be renormalized
267 auto* var = static_cast<RooRealVar*>(_varList[j]);
268 std::string transVarName = Form("%s_transVar_%d_%d",GetName(),i,j);
269 //transVar[ij(i,j)] = new RooFormulaVar(transVarName.c_str(),transVarName.c_str(),"@0*@1+@2",RooArgList(*var,*slope[ij(i,j)],*offs[ij(i,j)]));
270
271 transVar[ij(i,j)] = new RooLinearVar(transVarName.c_str(),transVarName.c_str(),*var,*slope[ij(i,j)],*offs[ij(i,j)]);
272
273 // *** WVE this is important *** this declares that frac effectively depends on the morphing parameters
274 // This will prevent the likelihood optimizers from erroneously declaring terms constant
275 transVar[ij(i,j)]->addServer(const_cast<RooAbsReal&>(m.arg()));
276
277 ownedComps.add(*transVar[ij(i,j)]) ;
278 cust.replaceArg(*var,*transVar[ij(i,j)]);
279 }
280 transPdf[i] = static_cast<RooAbsPdf*>(cust.build()) ;
281 transPdfList.add(*transPdf[i]);
282 ownedComps.add(*transPdf[i]) ;
283 }
284 // sum pdf
285 theSumPdf = std::make_unique<RooAddPdf>(sumpdfName.c_str(),sumpdfName.c_str(),transPdfList,coefList);
286 }
287 else {
288 theSumPdf = std::make_unique<RooAddPdf>(sumpdfName.c_str(),sumpdfName.c_str(),_pdfList,coefList);
289 }
290
291 // *** WVE this is important *** this declares that frac effectively depends on the morphing parameters
292 // This will prevent the likelihood optimizers from erroneously declaring terms constant
293 theSumPdf->addServer(const_cast<RooAbsReal&>(m.arg()));
294 theSumPdf->addOwnedComponents(ownedComps) ;
295
296 // change tracker for fraction parameters
297 std::string trackerName = Form("%s_frac_tracker",GetName()) ;
298 auto tracker = std::make_unique<RooChangeTracker>(trackerName.c_str(),trackerName.c_str(),m.arg(),true) ;
299
300 // Store it in the cache
301 auto cache = new CacheElem(std::move(theSumPdf),std::move(tracker),fracl) ;
302 _cacheMgr.setObj(nullptr,nullptr,cache,nullptr);
303
304 cache->calculateFractions(*this, false);
305 return cache ;
306}
307
308////////////////////////////////////////////////////////////////////////////////
309
311{
312 return RooArgList(*_sumPdf,*_tracker) ;
313}
314
315////////////////////////////////////////////////////////////////////////////////
316
318
319////////////////////////////////////////////////////////////////////////////////
320/// Special version of getVal() overrides RooAbsReal::getVal() to save value of current normalization set
321
322double RooMomentMorph::getVal(const RooArgSet* set) const
323{
324 _curNormSet = set ? const_cast<RooArgSet*>(set) : const_cast<RooArgSet*>(static_cast<RooArgSet const*>(&_varList));
325 return RooAbsPdf::getVal(set) ;
326}
327
328////////////////////////////////////////////////////////////////////////////////
329
331{
332 CacheElem* cache = getCache(nset ? nset : _curNormSet) ;
333
334 if (cache->_tracker->hasChanged(true)) {
335 cache->calculateFractions(*this,false); // verbose turned off
336 }
337
338 return cache->_sumPdf.get();
339}
340
341////////////////////////////////////////////////////////////////////////////////
342
344{
345 CacheElem* cache = getCache(_curNormSet) ;
346
347 if (cache->_tracker->hasChanged(true)) {
348 cache->calculateFractions(*this,false); // verbose turned off
349 }
350
351 return cache->_sumPdf->getVal(_pdfList.nset());
352}
353
354////////////////////////////////////////////////////////////////////////////////
355
357{
358 return static_cast<RooRealVar*>(_frac.at(i)) ;
359}
360
361////////////////////////////////////////////////////////////////////////////////
362
364{
365 return static_cast<RooRealVar*>(_frac.at(i)) ;
366}
367
368////////////////////////////////////////////////////////////////////////////////
369
371{
372 Int_t nPdf = self._pdfList.size();
373
374 double dm = self.m - (*self._mref)[0];
375
376 // fully non-linear
377 double sumposfrac=0.;
378 for (Int_t i=0; i<nPdf; ++i) {
379 double ffrac=0.;
380 for (Int_t j=0; j<nPdf; ++j) { ffrac += (*self._M)(j,i) * (j==0?1.:TMath::Power(dm,(double)j)); }
381 if (ffrac>=0) sumposfrac+=ffrac;
382 // fractions for pdf
383 const_cast<RooRealVar*>(frac(i))->setVal(ffrac);
384 // fractions for rms and mean
385 const_cast<RooRealVar*>(frac(nPdf+i))->setVal(ffrac);
386 if (verbose) { std::cout << ffrac << std::endl; }
387 }
388
389 // various mode settings
390 int imin = self.idxmin(self.m);
391 int imax = self.idxmax(self.m);
392 double mfrac = (self.m-(*self._mref)[imin])/((*self._mref)[imax]-(*self._mref)[imin]);
393 switch (self._setting) {
394 case NonLinear:
395 // default already set above
396 break;
397
398 case SineLinear:
399 mfrac = TMath::Sin( TMath::PiOver2()*mfrac ); // this gives a continuous differentiable transition between grid points.
400
401 // now fall through to Linear case
402
403 case Linear:
404 for (Int_t i=0; i<2*nPdf; ++i)
405 const_cast<RooRealVar*>(frac(i))->setVal(0.);
406 if (imax>imin) { // m in between mmin and mmax
407 const_cast<RooRealVar*>(frac(imin))->setVal(1.-mfrac);
408 const_cast<RooRealVar*>(frac(nPdf+imin))->setVal(1.-mfrac);
409 const_cast<RooRealVar*>(frac(imax))->setVal(mfrac);
410 const_cast<RooRealVar*>(frac(nPdf+imax))->setVal(mfrac);
411 } else if (imax==imin) { // m outside mmin and mmax
412 const_cast<RooRealVar*>(frac(imin))->setVal(1.);
413 const_cast<RooRealVar*>(frac(nPdf+imin))->setVal(1.);
414 }
415 break;
417 for (Int_t i=0; i<nPdf; ++i)
418 const_cast<RooRealVar*>(frac(i))->setVal(0.);
419 if (imax>imin) { // m in between mmin and mmax
420 const_cast<RooRealVar*>(frac(imin))->setVal(1.-mfrac);
421 const_cast<RooRealVar*>(frac(imax))->setVal(mfrac);
422 } else if (imax==imin) { // m outside mmin and mmax
423 const_cast<RooRealVar*>(frac(imin))->setVal(1.);
424 }
425 break;
427 for (Int_t i = 0; i < nPdf; ++i) {
428 if (frac(i)->getVal() < 0)
429 const_cast<RooRealVar *>(frac(i))->setVal(0.);
430 const_cast<RooRealVar *>(frac(i))->setVal(frac(i)->getVal() / sumposfrac);
431 }
432 break;
433 }
434
435}
436
437////////////////////////////////////////////////////////////////////////////////
438
439int RooMomentMorph::idxmin(const double& mval) const
440{
441 int imin(0);
442 Int_t nPdf = _pdfList.size();
443 double mmin=-DBL_MAX;
444 for (Int_t i=0; i<nPdf; ++i)
445 if ( (*_mref)[i]>mmin && (*_mref)[i]<=mval ) { mmin=(*_mref)[i]; imin=i; }
446 return imin;
447}
448
449
450////////////////////////////////////////////////////////////////////////////////
451
452int RooMomentMorph::idxmax(const double& mval) const
453{
454 int imax(0);
455 Int_t nPdf = _pdfList.size();
456 double mmax=DBL_MAX;
457 for (Int_t i=0; i<nPdf; ++i)
458 if ( (*_mref)[i]<mmax && (*_mref)[i]>=mval ) { mmax=(*_mref)[i]; imax=i; }
459 return imax;
460}
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
#define coutW(a)
#define coutE(a)
#define ClassImp(name)
Definition Rtypes.h:377
char name[80]
Definition TGX11.cxx:110
TMatrixT< Double_t > TMatrixD
Definition TMatrixDfwd.h:23
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2489
void setLocalNoDirtyInhibit(bool flag) const
Definition RooAbsArg.h:700
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
Storage_t::size_type size() const
bool addTyped(const RooAbsCollection &list, bool silent=false)
Adds elements of a given RooAbsCollection to the container if they match the specified type.
RooAbsReal * mean()
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:40
const RooArgSet * nset() const
Definition RooAbsProxy.h:52
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
RooAbsMoment * sigma(RooRealVar &obs)
Definition RooAbsReal.h:368
Calculates the sum of a set of RooAbsReal terms, or when constructed with two sets,...
Definition RooAddition.h:27
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition RooArgList.h:110
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:55
Int_t setObj(const RooArgSet *nset, T *obj, const TNamed *isetRangeName=nullptr)
Setter function without integration set.
T * getObj(const RooArgSet *nset, Int_t *sterileIndex=nullptr, const TNamed *isetRangeName=nullptr)
Getter function without integration set.
Represents a constant real-valued object.
Definition RooConstVar.h:23
RooCustomizer is a factory class to produce clones of a prototype composite PDF object with the same ...
void replaceArg(const RooAbsArg &orig, const RooAbsArg &subst)
Replace any occurrence of arg 'orig' with arg 'subst'.
RooAbsArg * build(const char *masterCatState, bool verbose=false)
Build a clone of the prototype executing all registered 'replace' rules and 'split' rules for the mas...
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
RooLinearVar is the most general form of a derived real-valued object that can be used by RooRealInte...
RooArgList containedArgs(Action) override
CacheElem(std::unique_ptr< RooAbsPdf > &&sumPdf, std::unique_ptr< RooChangeTracker > &&tracker, const RooArgList &flist)
RooRealVar * frac(Int_t i)
void calculateFractions(const RooMomentMorph &self, bool verbose=true) const
std::unique_ptr< RooAbsPdf > _sumPdf
std::unique_ptr< RooChangeTracker > _tracker
RooObjCacheManager _cacheMgr
virtual double getVal(const RooArgSet *set=nullptr) const
Special version of getVal() overrides RooAbsReal::getVal() to save value of current normalization set...
~RooMomentMorph() override
RooSetProxy _varList
double evaluate() const override
Evaluate this PDF / function / constant. Needs to be overridden by all derived classes.
RooMomentMorph()
coverity[UNINIT_CTOR]
RooRealProxy m
RooAbsPdf * sumPdf(const RooArgSet *nset)
Int_t ij(const Int_t &i, const Int_t &j) const
RooArgSet * _curNormSet
The cache manager.
RooListProxy _pdfList
int idxmin(const double &m) const
int idxmax(const double &m) const
CacheElem * getCache(const RooArgSet *nset) const
TVectorD * _mref
Variable that can be changed from the outside.
Definition RooRealVar.h:37
void setVal(double value) override
Set value of variable to 'value'.
const T & arg() const
Return reference to object held in proxy.
TMatrixT< Element > & Invert(Double_t *det=nullptr)
Invert the matrix and calculate its determinant.
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
Int_t GetNrows() const
Definition TVectorT.h:75
constexpr Double_t PiOver2()
Definition TMath.h:51
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Returns x raised to the power y.
Definition TMath.h:721
Double_t Sin(Double_t)
Returns the sine of an angle of x radians.
Definition TMath.h:588
TMarker m
Definition textangle.C:8