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
22Efficient 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
37#include <iostream>
38#include <string>
39
41
42
43////////////////////////////////////////////////////////////////////////////////
44/// Constructor of specialized generator context for RooSimultaneous p.d.f.s. This
45/// context creates a dedicated context for each component p.d.f.s and delegates
46/// generation of events to the appropriate component generator context
47
48RooSimSplitGenContext::RooSimSplitGenContext(const RooSimultaneous &model, const RooArgSet &vars, bool verbose, bool autoBinned, const char* binnedTag) :
49 RooAbsGenContext(model,vars,nullptr,nullptr,verbose), _pdf(&model)
50{
51 // Determine if we are requested to generate the index category
52 RooAbsCategoryLValue const& idxCat = model.indexCat();
53 RooArgSet pdfVars(vars) ;
54
55 RooArgSet allPdfVars(pdfVars) ;
56
57 RooArgSet catsAmongAllVars;
58 allPdfVars.selectCommon(model.flattenedCatList(), catsAmongAllVars);
59
60 if(catsAmongAllVars.size() != model.flattenedCatList().size()) {
61 oocoutE(_pdf,Generation) << "RooSimSplitGenContext::ctor(" << GetName() << ") ERROR: This context must"
62 << " generate all components of the index category" << std::endl ;
63 _isValid = false ;
64 _numPdf = 0 ;
65 // coverity[UNINIT_CTOR]
66 return ;
67 }
68
69 // We must extended likelihood to determine the relative fractions of the components
70 _idxCatName = idxCat.GetName() ;
71 if (!model.canBeExtended()) {
72 oocoutE(_pdf,Generation) << "RooSimSplitGenContext::RooSimSplitGenContext(" << GetName() << "): All components of the simultaneous PDF "
73 << "must be extended PDFs. Otherwise, it is impossible to calculate the number of events to be generated per component." << std::endl ;
74 _isValid = false ;
75 _numPdf = 0 ;
76 // coverity[UNINIT_CTOR]
77 return ;
78 }
79
80 // Initialize fraction threshold array (used only in extended mode)
81 _numPdf = model._pdfProxyList.GetSize() ;
82 _fracThresh = new double[_numPdf+1] ;
83 _fracThresh[0] = 0 ;
84
85 // Generate index category and all registered PDFS
86 _allVarsPdf.add(allPdfVars) ;
87 Int_t i(1) ;
88 for(auto * proxy : static_range_cast<RooRealProxy*>(model._pdfProxyList)) {
89 auto pdf = static_cast<RooAbsPdf*>(proxy->absArg());
90
91 // Create generator context for this PDF
92 std::unique_ptr<RooArgSet> compVars{pdf->getObservables(pdfVars)};
93 RooAbsGenContext* cx = pdf->autoGenContext(*compVars,nullptr,nullptr,verbose,autoBinned,binnedTag) ;
94
95 const auto state = idxCat.lookupIndex(proxy->name());
96
97 cx->SetName(proxy->name()) ;
98 _gcList.push_back(cx) ;
99 _gcIndex.push_back(state);
100
101 // Fill fraction threshold array
102 _fracThresh[i] = _fracThresh[i-1] + pdf->expectedEvents(&allPdfVars) ;
103 i++ ;
104 }
105
106 for(i=0 ; i<_numPdf ; i++) {
108 }
109
110 // Clone the index category
111 if(RooArgSet(model.indexCat()).snapshot(_idxCatSet, true)) {
112 oocoutE(_pdf,Generation) << "RooSimSplitGenContext::RooSimSplitGenContext(" << GetName() << ") Couldn't deep-clone index category, abort," << std::endl ;
113 throw std::string("RooSimSplitGenContext::RooSimSplitGenContext() Couldn't deep-clone index category, abort") ;
114 }
115 _idxCat = static_cast<RooAbsCategoryLValue*>(_idxCatSet.find(model.indexCat().GetName()));
116}
117
118
119
120////////////////////////////////////////////////////////////////////////////////
121/// Destructor. Delete all owned subgenerator contexts
122
124{
125 delete[] _fracThresh ;
126 for (RooAbsGenContext *item : _gcList) {
127 delete item;
128 }
129}
130
131
132
133////////////////////////////////////////////////////////////////////////////////
134/// Attach the index category clone to the given event buffer
135
137{
138 if (_idxCat->isDerived()) {
140 }
141
142 // Forward initGenerator call to all components
143 for (RooAbsGenContext *item : _gcList) {
144 item->attach(args) ;
145 }
146
147}
148
149
150////////////////////////////////////////////////////////////////////////////////
151/// Perform one-time initialization of generator context
152
154{
155 // Attach the index category clone to the event
156 if (_idxCat->isDerived()) {
158 } else {
159 _idxCat = static_cast<RooAbsCategoryLValue*>(theEvent.find(_idxCat->GetName())) ;
160 }
161
162 // Forward initGenerator call to all components
163 for (RooAbsGenContext *item : _gcList) {
164 item->initGenerator(theEvent) ;
165 }
166
167}
168
169
170
171////////////////////////////////////////////////////////////////////////////////
172
173RooDataSet* RooSimSplitGenContext::generate(double nEvents, bool skipInit, bool extendedMode)
174{
175 if(!isValid()) {
176 coutE(Generation) << ClassName() << "::" << GetName() << ": context is not valid" << std::endl;
177 return nullptr;
178 }
179
180
181 // Calculate the expected number of events if necessary
182 if(nEvents <= 0) {
183 nEvents= _expectedEvents;
184 }
185 coutI(Generation) << ClassName() << "::" << GetName() << ":generate: will generate "
186 << nEvents << " events" << std::endl;
187
188 if (_verbose) Print("v") ;
189
190 // Perform any subclass implementation-specific initialization
191 // Can be skipped if this is a rerun with an identical configuration
192 if (!skipInit) {
194 }
195
196 // Generate lookup table from expected event counts
197 std::vector<double> nGen(_numPdf) ;
198 if (extendedMode ) {
199 Int_t i(0) ;
200 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdf->_pdfProxyList)) {
201 RooAbsPdf* pdf=static_cast<RooAbsPdf*>(proxy->absArg()) ;
202 //nGen[i] = Int_t(pdf->expectedEvents(&_allVarsPdf)+0.5) ;
203 nGen[i] = pdf->expectedEvents(&_allVarsPdf) ;
204 i++ ;
205 }
206
207 } else {
208 Int_t i(1) ;
209 _fracThresh[0] = 0 ;
210 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdf->_pdfProxyList)) {
211 RooAbsPdf* pdf=static_cast<RooAbsPdf*>(proxy->absArg()) ;
213 i++ ;
214 }
215 for(i=0 ; i<_numPdf ; i++) {
217 }
218
219 // Determine from that total number of events to be generated for each component
220 double nGenSoFar(0) ;
221 while (nGenSoFar<nEvents) {
222 double rand = RooRandom::uniform() ;
223 i=0 ;
224 for (i=0 ; i<_numPdf ; i++) {
225 if (rand>_fracThresh[i] && rand<_fracThresh[i+1]) {
226 nGen[i]++ ;
227 nGenSoFar++ ;
228 break ;
229 }
230 }
231 }
232 }
233
234
235
236 // Now loop over states
237 std::map<std::string,RooAbsData*> dataMap ;
238 Int_t icomp(0) ;
239 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdf->_pdfProxyList)) {
240
241 // Calculate number of events to generate for this state
242 if (_gcList[icomp]) {
243 dataMap[proxy->GetName()] = _gcList[icomp]->generate(nGen[icomp],skipInit,extendedMode) ;
244 }
245
246 icomp++ ;
247 }
248
249 // Put all datasets together in a composite-store RooDataSet that links and owns the component datasets
250 RooDataSet* hmaster = new RooDataSet("hmaster","hmaster",_allVarsPdf,RooFit::Index(static_cast<RooCategory&>(*_idxCat)),RooFit::Link(dataMap),RooFit::OwnLinked()) ;
251 return hmaster ;
252}
253
254
255
256////////////////////////////////////////////////////////////////////////////////
257/// Forward to components
258
260{
261 for(RooAbsGenContext *elem : _gcList) {
262 elem->setExpectedData(flag) ;
263 }
264}
265
266
267
268////////////////////////////////////////////////////////////////////////////////
269/// this method is empty because it is not used by this context
270
271RooDataSet* RooSimSplitGenContext::createDataSet(const char* , const char* , const RooArgSet& )
272{
273 return nullptr;
274}
275
276
277
278////////////////////////////////////////////////////////////////////////////////
279/// this method is empty because it is not used in this type of context
280
282{
283 assert(0) ;
284}
285
286
287
288
289////////////////////////////////////////////////////////////////////////////////
290/// this method is empty because proto datasets are not supported by this context
291
293{
294 assert(0) ;
295}
296
297
298////////////////////////////////////////////////////////////////////////////////
299/// Detailed printing interface
300
301void RooSimSplitGenContext::printMultiline(std::ostream &os, Int_t content, bool verbose, TString indent) const
302{
303 RooAbsGenContext::printMultiline(os,content,verbose,indent) ;
304 os << indent << "--- RooSimSplitGenContext ---" << std::endl ;
305 os << indent << "Using PDF ";
307}
#define coutI(a)
#define oocoutE(o, a)
#define coutE(a)
#define ClassImp(name)
Definition Rtypes.h:382
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
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:24
RooArgSet * selectCommon(const RooAbsCollection &refColl) const
Use RooAbsCollection::selecCommon(), but return as RooArgSet.
Definition RooArgSet.h:149
Object to represent discrete states.
Definition RooCategory.h:28
Container class to hold unbinned data.
Definition RooDataSet.h:33
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:78
Efficient implementation of the generator context specific for RooSimultaneous PDFs when generating m...
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:213
Basic string class.
Definition TString.h:139
RooCmdArg OwnLinked()
RooCmdArg Index(RooCategory &icat)
RooCmdArg Link(const char *state, RooAbsData &data)