Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooSimSplitGenContext.cxx
Go to the documentation of this file.
1/*****************************************************************************
2 * Project: RooFit *
3 * Package: RooFitCore *
4 * @(#)root/roofitcore:$Id$
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
17/**
18\file RooSimSplitGenContext.cxx
19\class RooSimSplitGenContext
20\ingroup Roofitcore
21
22RooSimSplitGenContext is an efficient implementation of the generator context
23specific for RooSimultaneous PDFs when generating more than one of the
24component pdfs.
25**/
26
28#include "RooSimultaneous.h"
29#include "RooRealProxy.h"
30#include "RooDataSet.h"
31#include "Roo1DTable.h"
32#include "RooCategory.h"
33#include "RooMsgService.h"
34#include "RooRandom.h"
35#include "RooGlobalFunc.h"
36
37using namespace RooFit;
38
39#include <iostream>
40#include <string>
41
42using namespace std;
43
45
46
47////////////////////////////////////////////////////////////////////////////////
48/// Constructor of specialized generator context for RooSimultaneous p.d.f.s. This
49/// context creates a dedicated context for each component p.d.f.s and delegates
50/// generation of events to the appropriate component generator context
51
52RooSimSplitGenContext::RooSimSplitGenContext(const RooSimultaneous &model, const RooArgSet &vars, bool verbose, bool autoBinned, const char* binnedTag) :
53 RooAbsGenContext(model,vars,nullptr,nullptr,verbose), _pdf(&model)
54{
55 // Determine if we are requested to generate the index category
56 RooAbsCategoryLValue const& idxCat = model.indexCat();
57 RooArgSet pdfVars(vars) ;
58
59 RooArgSet allPdfVars(pdfVars) ;
60
61 RooArgSet catsAmongAllVars;
62 allPdfVars.selectCommon(model.flattenedCatList(), catsAmongAllVars);
63
64 if(catsAmongAllVars.size() != model.flattenedCatList().size()) {
65 oocoutE(_pdf,Generation) << "RooSimSplitGenContext::ctor(" << GetName() << ") ERROR: This context must"
66 << " generate all components of the index category" << endl ;
67 _isValid = false ;
68 _numPdf = 0 ;
69 // coverity[UNINIT_CTOR]
70 return ;
71 }
72
73 // We must extended likelihood to determine the relative fractions of the components
74 _idxCatName = idxCat.GetName() ;
75 if (!model.canBeExtended()) {
76 oocoutE(_pdf,Generation) << "RooSimSplitGenContext::RooSimSplitGenContext(" << GetName() << "): All components of the simultaneous PDF "
77 << "must be extended PDFs. Otherwise, it is impossible to calculate the number of events to be generated per component." << endl ;
78 _isValid = false ;
79 _numPdf = 0 ;
80 // coverity[UNINIT_CTOR]
81 return ;
82 }
83
84 // Initialize fraction threshold array (used only in extended mode)
85 _numPdf = model._pdfProxyList.GetSize() ;
86 _fracThresh = new double[_numPdf+1] ;
87 _fracThresh[0] = 0 ;
88
89 // Generate index category and all registered PDFS
90 _allVarsPdf.add(allPdfVars) ;
91 Int_t i(1) ;
92 for(auto * proxy : static_range_cast<RooRealProxy*>(model._pdfProxyList)) {
93 auto pdf = static_cast<RooAbsPdf*>(proxy->absArg());
94
95 // Create generator context for this PDF
96 std::unique_ptr<RooArgSet> compVars{pdf->getObservables(pdfVars)};
97 RooAbsGenContext* cx = pdf->autoGenContext(*compVars,nullptr,nullptr,verbose,autoBinned,binnedTag) ;
98
99 const auto state = idxCat.lookupIndex(proxy->name());
100
101 cx->SetName(proxy->name()) ;
102 _gcList.push_back(cx) ;
103 _gcIndex.push_back(state);
104
105 // Fill fraction threshold array
106 _fracThresh[i] = _fracThresh[i-1] + pdf->expectedEvents(&allPdfVars) ;
107 i++ ;
108 }
109
110 for(i=0 ; i<_numPdf ; i++) {
112 }
113
114 // Clone the index category
115 if(RooArgSet(model.indexCat()).snapshot(_idxCatSet, true)) {
116 oocoutE(_pdf,Generation) << "RooSimSplitGenContext::RooSimSplitGenContext(" << GetName() << ") Couldn't deep-clone index category, abort," << endl ;
117 throw std::string("RooSimSplitGenContext::RooSimSplitGenContext() Couldn't deep-clone index category, abort") ;
118 }
119 _idxCat = static_cast<RooAbsCategoryLValue*>(_idxCatSet.find(model.indexCat().GetName()));
120}
121
122
123
124////////////////////////////////////////////////////////////////////////////////
125/// Destructor. Delete all owned subgenerator contexts
126
128{
129 delete[] _fracThresh ;
130 for (vector<RooAbsGenContext*>::iterator iter = _gcList.begin() ; iter!=_gcList.end() ; ++iter) {
131 delete (*iter) ;
132 }
133}
134
135
136
137////////////////////////////////////////////////////////////////////////////////
138/// Attach the index category clone to the given event buffer
139
141{
142 if (_idxCat->isDerived()) {
144 }
145
146 // Forward initGenerator call to all components
147 for (vector<RooAbsGenContext*>::iterator iter = _gcList.begin() ; iter!=_gcList.end() ; ++iter) {
148 (*iter)->attach(args) ;
149 }
150
151}
152
153
154////////////////////////////////////////////////////////////////////////////////
155/// Perform one-time initialization of generator context
156
158{
159 // Attach the index category clone to the event
160 if (_idxCat->isDerived()) {
162 } else {
164 }
165
166 // Forward initGenerator call to all components
167 for (vector<RooAbsGenContext*>::iterator iter = _gcList.begin() ; iter!=_gcList.end() ; ++iter) {
168 (*iter)->initGenerator(theEvent) ;
169 }
170
171}
172
173
174
175////////////////////////////////////////////////////////////////////////////////
176
177RooDataSet* RooSimSplitGenContext::generate(double nEvents, bool skipInit, bool extendedMode)
178{
179 if(!isValid()) {
180 coutE(Generation) << ClassName() << "::" << GetName() << ": context is not valid" << endl;
181 return nullptr;
182 }
183
184
185 // Calculate the expected number of events if necessary
186 if(nEvents <= 0) {
187 nEvents= _expectedEvents;
188 }
189 coutI(Generation) << ClassName() << "::" << GetName() << ":generate: will generate "
190 << nEvents << " events" << endl;
191
192 if (_verbose) Print("v") ;
193
194 // Perform any subclass implementation-specific initialization
195 // Can be skipped if this is a rerun with an identical configuration
196 if (!skipInit) {
198 }
199
200 // Generate lookup table from expected event counts
201 vector<double> nGen(_numPdf) ;
202 if (extendedMode ) {
203 Int_t i(0) ;
204 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdf->_pdfProxyList)) {
205 RooAbsPdf* pdf=(RooAbsPdf*)proxy->absArg() ;
206 //nGen[i] = Int_t(pdf->expectedEvents(&_allVarsPdf)+0.5) ;
207 nGen[i] = pdf->expectedEvents(&_allVarsPdf) ;
208 i++ ;
209 }
210
211 } else {
212 Int_t i(1) ;
213 _fracThresh[0] = 0 ;
214 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdf->_pdfProxyList)) {
215 RooAbsPdf* pdf=(RooAbsPdf*)proxy->absArg() ;
217 i++ ;
218 }
219 for(i=0 ; i<_numPdf ; i++) {
221 }
222
223 // Determine from that total number of events to be generated for each component
224 double nGenSoFar(0) ;
225 while (nGenSoFar<nEvents) {
226 double rand = RooRandom::uniform() ;
227 i=0 ;
228 for (i=0 ; i<_numPdf ; i++) {
229 if (rand>_fracThresh[i] && rand<_fracThresh[i+1]) {
230 nGen[i]++ ;
231 nGenSoFar++ ;
232 break ;
233 }
234 }
235 }
236 }
237
238
239
240 // Now loop over states
241 map<string,RooAbsData*> dataMap ;
242 Int_t icomp(0) ;
243 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdf->_pdfProxyList)) {
244
245 // Calculate number of events to generate for this state
246 if (_gcList[icomp]) {
247 dataMap[proxy->GetName()] = _gcList[icomp]->generate(nGen[icomp],skipInit,extendedMode) ;
248 }
249
250 icomp++ ;
251 }
252
253 // Put all datasets together in a composite-store RooDataSet that links and owns the component datasets
254 RooDataSet* hmaster = new RooDataSet("hmaster","hmaster",_allVarsPdf,RooFit::Index((RooCategory&)*_idxCat),RooFit::Link(dataMap),RooFit::OwnLinked()) ;
255 return hmaster ;
256}
257
258
259
260////////////////////////////////////////////////////////////////////////////////
261/// Forward to components
262
264{
265 for(auto * elem : _gcList) {
266 elem->setExpectedData(flag) ;
267 }
268}
269
270
271
272////////////////////////////////////////////////////////////////////////////////
273/// this method is empty because it is not used by this context
274
275RooDataSet* RooSimSplitGenContext::createDataSet(const char* , const char* , const RooArgSet& )
276{
277 return nullptr;
278}
279
280
281
282////////////////////////////////////////////////////////////////////////////////
283/// this method is empty because it is not used in this type of context
284
286{
287 assert(0) ;
288}
289
290
291
292
293////////////////////////////////////////////////////////////////////////////////
294/// this method is empty because proto datasets are not supported by this context
295
297{
298 assert(0) ;
299}
300
301
302////////////////////////////////////////////////////////////////////////////////
303/// Detailed printing interface
304
305void RooSimSplitGenContext::printMultiline(ostream &os, Int_t content, bool verbose, TString indent) const
306{
307 RooAbsGenContext::printMultiline(os,content,verbose,indent) ;
308 os << indent << "--- RooSimSplitGenContext ---" << endl ;
309 os << indent << "Using PDF ";
311}
#define coutI(a)
#define oocoutE(o, a)
#define coutE(a)
#define ClassImp(name)
Definition Rtypes.h:377
static void indent(ostringstream &buf, int indent_level)
bool recursiveRedirectServers(const RooAbsCollection &newServerList, bool mustReplaceAll=false, bool nameChange=false, bool recurseInNewSet=true)
Recursively replace all servers with the new servers in newSet.
RooFit::OwningPtr< RooArgSet > getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
virtual bool isDerived() const
Does value or shape of this arg depend on any other arg?
Definition RooAbsArg.h:99
Abstract base class for objects that represent a discrete value that can be set from the outside,...
value_type lookupIndex(const std::string &stateName) const
Find the index number corresponding to the state name.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
Storage_t::size_type size() const
bool selectCommon(const RooAbsCollection &refColl, RooAbsCollection &outColl) const
Create a subset of the current collection, consisting only of those elements that are contained as we...
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for generator contexts of RooAbsPdf objects.
RooArgSet _theEvent
Pointer to observable event being generated.
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Interface for multi-line printing.
void Print(Option_t *options=nullptr) const override
This method must be overridden when a class wants to print itself.
UInt_t _expectedEvents
Number of expected events from extended p.d.f.
bool _verbose
Verbose messaging?
bool _isValid
Is context in valid state?
bool isValid() const
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:40
virtual double expectedEvents(const RooArgSet *nset) const
Return expected number of events to be used in calculation of extended likelihood.
bool canBeExtended() const
If true, PDF can provide extended likelihood term.
Definition RooAbsPdf.h:218
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:55
Object to represent discrete states.
Definition RooCategory.h:28
RooDataSet is a container class to hold unbinned data.
Definition RooDataSet.h:57
virtual void printStream(std::ostream &os, Int_t contents, StyleOption style, TString indent="") const
Print description of object on ostream, printing contents set by contents integer,...
static double uniform(TRandom *generator=randomGenerator())
Return a number uniformly distributed from (0,1)
Definition RooRandom.cxx:81
RooSimSplitGenContext is an efficient implementation of the generator context specific for RooSimulta...
void setExpectedData(bool) override
Forward to components.
void generateEvent(RooArgSet &theEvent, Int_t remaining) override
this method is empty because it is not used in this type of context
std::vector< RooAbsGenContext * > _gcList
List of component generator contexts.
RooArgSet _allVarsPdf
All pdf variables.
void attach(const RooArgSet &params) override
Attach the index category clone to the given event buffer.
RooSimSplitGenContext(const RooSimultaneous &model, const RooArgSet &vars, bool _verbose=false, bool autoBinned=true, const char *binnedTag="")
Constructor of specialized generator context for RooSimultaneous p.d.f.s.
void initGenerator(const RooArgSet &theEvent) override
Perform one-time initialization of generator context.
double * _fracThresh
fraction thresholds
RooDataSet * createDataSet(const char *name, const char *title, const RooArgSet &obs) override
this method is empty because it is not used by this context
Int_t _numPdf
Number of generated PDFs.
void printMultiline(std::ostream &os, Int_t content, bool verbose=false, TString indent="") const override
Detailed printing interface.
RooArgSet _idxCatSet
Owner of index category components.
const RooSimultaneous * _pdf
Original PDF.
RooDataSet * generate(double nEvents=0, bool skipInit=false, bool extendedMode=false) override
Generate the specified number of events with nEvents>0 and and return a dataset containing the genera...
std::vector< int > _gcIndex
Index value corresponding to component.
void setProtoDataOrder(Int_t *lut) override
this method is empty because proto datasets are not supported by this context
~RooSimSplitGenContext() override
Destructor. Delete all owned subgenerator contexts.
RooAbsCategoryLValue * _idxCat
Clone of index category.
TString _idxCatName
Name of index category.
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
TList _pdfProxyList
List of PDF proxies (named after applicable category state)
RooArgSet const & flattenedCatList() const
Internal utility function to get a list of all category components for this RooSimultaneous.
const RooAbsCategoryLValue & indexCat() const
virtual Int_t GetSize() const
Return the capacity of the collection, i.e.
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition TNamed.cxx:140
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:207
Basic string class.
Definition TString.h:139
RooCmdArg OwnLinked()
RooCmdArg Index(RooCategory &icat)
RooCmdArg Link(const char *state, RooAbsData &data)
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition JSONIO.h:26