Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooAbsGenContext.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 RooAbsGenContext.cxx
19\class RooAbsGenContext
20\ingroup Roofitcore
21
22Abstract base class for generator contexts of
23RooAbsPdf objects. A generator context is an object that controls
24the generation of events from a given p.d.f in one or more sessions.
25This class defines the common interface for all such contexts and organizes
26storage of common components, such as the observables definition, the
27prototype data etc..
28**/
29
30#include "RooAbsGenContext.h"
31#include "RooRandom.h"
32#include "RooAbsPdf.h"
33#include "RooDataSet.h"
34#include "RooMsgService.h"
35#include "RooGlobalFunc.h"
36
37#include "Riostream.h"
38
39
40using namespace std;
41
43;
44
45
46////////////////////////////////////////////////////////////////////////////////
47/// Constructor
48
50 const RooDataSet *prototype, const RooArgSet* auxProto, bool verbose) :
51 TNamed(model),
52 _prototype(prototype),
53 _isValid(true),
54 _verbose(verbose)
55{
56 // Check PDF dependents
57 if (model.recursiveCheckObservables(&vars)) {
58 coutE(Generation) << "RooAbsGenContext::ctor: Error in PDF dependents" << endl ;
59 _isValid = false ;
60 return ;
61 }
62
63 // Make a snapshot of the generated variables that we can overwrite.
64 vars.snapshot(_theEvent, false);
65
66 // Analyze the prototype dataset, if one is specified
68 if(nullptr != _prototype) {
69 for (RooAbsArg const* proto : *_prototype->get()) {
70 // is this variable being generated or taken from the prototype?
71 if(!_theEvent.contains(*proto)) {
74 }
75 }
76 }
77
78 // Add auxiliary protovars to _protoVars, if provided
79 if (auxProto) {
80 _protoVars.add(*auxProto) ;
81 _theEvent.addClone(*auxProto);
82 }
83
84 // Remember the default number of events to generate when no prototype dataset is provided.
85 _extendMode = model.extendMode() ;
86 if (model.canBeExtended()) {
88 } else {
90 }
91
92 // Save normalization range
93 if (model.normRange()) {
94 _normRange = model.normRange() ;
95 }
96}
97
98
99
100////////////////////////////////////////////////////////////////////////////////
101/// Interface to attach given parameters to object in this context
102
103void RooAbsGenContext::attach(const RooArgSet& /*params*/)
104{
105}
106
107
108
109////////////////////////////////////////////////////////////////////////////////
110/// Create an empty dataset to hold the events that will be generated
111
112RooDataSet* RooAbsGenContext::createDataSet(const char* name, const char* title, const RooArgSet& obs)
113{
114 RooDataSet* ret = new RooDataSet(name, title, obs);
115 ret->setDirtyProp(false) ;
116 return ret ;
117}
118
119
120////////////////////////////////////////////////////////////////////////////////
121/// Generate the specified number of events with nEvents>0 and
122/// and return a dataset containing the generated events. With nEvents<=0,
123/// generate the number of events in the prototype dataset, if available,
124/// or else the expected number of events, if non-zero.
125/// If extendedMode = true generate according to a Poisson(nEvents)
126/// The returned dataset belongs to the caller. Return zero in case of an error.
127/// Generation of individual events is delegated to a virtual generateEvent()
128/// method. A virtual initGenerator() method is also called just before the
129/// first call to generateEvent().
130
131RooDataSet *RooAbsGenContext::generate(double nEvents, bool skipInit, bool extendedMode)
132{
133 if(!isValid()) {
134 coutE(Generation) << ClassName() << "::" << GetName() << ": context is not valid" << endl;
135 return nullptr;
136 }
137
138 // Calculate the expected number of events if necessary
139 if(nEvents <= 0) {
140 if(_prototype) {
141 nEvents= (Int_t)_prototype->numEntries();
142 }
143 else {
145 coutE(Generation) << ClassName() << "::" << GetName()
146 << ":generate: PDF not extendable: cannot calculate expected number of events" << endl;
147 return nullptr;
148 }
149 nEvents= _expectedEvents;
150 }
151 if(nEvents <= 0) {
152 coutE(Generation) << ClassName() << "::" << GetName()
153 << ":generate: cannot calculate expected number of events" << endl;
154 return nullptr;
155 }
156 coutI(Generation) << ClassName() << "::" << GetName() << ":generate: will generate "
157 << nEvents << " events" << endl;
158
159 }
160
161 if (extendedMode) {
162 double nExpEvents = nEvents;
163 nEvents = RooRandom::randomGenerator()->Poisson(nEvents) ;
164 cxcoutI(Generation) << " Extended mode active, number of events generated (" << nEvents << ") is Poisson fluctuation on "
165 << GetName() << "::expectedEvents() = " << nExpEvents << endl ;
166 }
167
168 // check that any prototype dataset still defines the variables we need
169 // (this is necessary since we never make a private clone, for efficiency)
170 if(_prototype) {
171 const RooArgSet *vars= _prototype->get();
172 bool ok(true);
173 for (RooAbsArg * arg : _protoVars) {
174 if(vars->contains(*arg)) continue;
175 coutE(InputArguments) << ClassName() << "::" << GetName() << ":generate: prototype dataset is missing \""
176 << arg->GetName() << "\"" << endl;
177
178 // WVE disable this for the moment
179 // ok= false;
180 }
181 // coverity[DEADCODE]
182 if(!ok) return nullptr;
183 }
184
185 if (_verbose) Print("v") ;
186
187 // create a new dataset
188 TString name(GetName()),title(GetTitle());
189 name.Append("Data");
190 title.Prepend("Generated From ");
191
192 // WVE need specialization here for simultaneous pdfs
193 _genData = createDataSet(name.Data(), title.Data(), _theEvent);
194
195 // Perform any subclass implementation-specific initialization
196 // Can be skipped if this is a rerun with an identical configuration
197 if (!skipInit) {
199 }
200
201 // Loop over the events to generate
202 while(_genData->numEntries()<nEvents) {
203
204 // first, load values from the prototype dataset, if one was provided
205 if(nullptr != _prototype) {
207
208 Int_t actualProtoIdx = !_protoOrder.empty() ? _protoOrder[_nextProtoIndex] : _nextProtoIndex ;
209
210 const RooArgSet *subEvent= _prototype->get(actualProtoIdx);
212 if(nullptr != subEvent) {
213 _theEvent.assign(*subEvent);
214 }
215 else {
216 coutE(Generation) << ClassName() << "::" << GetName() << ":generate: cannot load event "
217 << actualProtoIdx << " from prototype dataset" << endl;
218 return nullptr;
219 }
220 }
221
222 // delegate the generation of the rest of this event to our subclass implementation
224
225
226 // WVE add check that event is in normRange
228 continue ;
229 }
230
232 }
233
235 _genData = nullptr ;
236 output->setDirtyProp(true) ;
237
238 return output;
239}
240
241
242
243////////////////////////////////////////////////////////////////////////////////
244/// Interface function to initialize context for generation for given
245/// set of observables
246
248{
249}
250
251
252
253////////////////////////////////////////////////////////////////////////////////
254/// Print name of context
255
256void RooAbsGenContext::printName(ostream& os) const
257{
258 os << GetName() ;
259}
260
261
262
263////////////////////////////////////////////////////////////////////////////////
264/// Print title of context
265
266void RooAbsGenContext::printTitle(ostream& os) const
267{
268 os << GetTitle() ;
269}
270
271
272
273////////////////////////////////////////////////////////////////////////////////
274/// Print class name of context
275
276void RooAbsGenContext::printClassName(ostream& os) const
277{
278 os << ClassName() ;
279}
280
281
282
283////////////////////////////////////////////////////////////////////////////////
284/// Print arguments of context, i.e. the observables being generated in this context
285
286void RooAbsGenContext::printArgs(ostream& os) const
287{
288 os << "[ " ;
289 bool first(true) ;
290 for (RooAbsArg * arg : _theEvent) {
291 if (first) {
292 first=false ;
293 } else {
294 os << "," ;
295 }
296 os << arg->GetName() ;
297 }
298 os << "]" ;
299}
300
301
302
303////////////////////////////////////////////////////////////////////////////////
304/// Interface for multi-line printing
305
306void RooAbsGenContext::printMultiline(ostream &/*os*/, Int_t /*contents*/, bool /*verbose*/, TString /*indent*/) const
307{
308}
309
310
311
312
313////////////////////////////////////////////////////////////////////////////////
314/// Set the traversal order of prototype data to that in the lookup tables
315/// passed as argument. The LUT must be an array of integers with the same
316/// size as the number of entries in the prototype dataset and must contain
317/// integer values in the range [0,Nevt-1]
318
320{
321 // Copy new lookup table if provided and needed
322 if (lut && _prototype) {
324 _protoOrder.resize(n);
325 Int_t i ;
326 for (i=0 ; i<n ; i++) {
327 _protoOrder[i] = lut[i] ;
328 }
329 }
330}
331
332
333
334
335////////////////////////////////////////////////////////////////////////////////
336/// Rescale existing output buffer with given ratio
337
339{
340
341 Int_t nOrig = _genData->numEntries() ;
342 Int_t nTarg = Int_t(nOrig*ratio+0.5) ;
343 std::unique_ptr<RooAbsData> trimmedData{_genData->reduce(RooFit::EventRange(0,nTarg))};
344
345 cxcoutD(Generation) << "RooGenContext::resampleData*( existing production trimmed from " << nOrig << " to " << trimmedData->numEntries() << " events" << endl ;
346
347 delete _genData ;
348 _genData = static_cast<RooDataSet*>(trimmedData.release());
349
350 if (_prototype) {
351 // Push back proto index by trimmed amount to force recycling of the
352 // proto entries that were trimmed away
353 _nextProtoIndex -= (nOrig-nTarg) ;
354 while (_nextProtoIndex<0) {
356 }
357 }
358
359}
360
361
362
363
364////////////////////////////////////////////////////////////////////////////////
365/// Define default contents when printing
366
368{
369 return kName|kClassName|kValue ;
370}
371
372
373
374////////////////////////////////////////////////////////////////////////////////
375/// Define default print style
376
378{
379 if (opt && TString(opt).Contains("v")) {
380 return kVerbose ;
381 }
382 return kStandard ;
383}
#define coutI(a)
#define cxcoutI(a)
#define cxcoutD(a)
#define coutE(a)
int Int_t
Definition RtypesCore.h:45
const char Option_t
Definition RtypesCore.h:66
#define ClassImp(name)
Definition Rtypes.h:377
char name[80]
Definition TGX11.cxx:110
const char * proto
Definition civetweb.c:17536
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:79
bool recursiveCheckObservables(const RooArgSet *nset) const
Recursively call checkObservables on all nodes in the expression tree.
bool contains(const RooAbsArg &var) const
Check if collection contains an argument with the same name as var.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
void assign(const RooAbsCollection &other) const
Sets the value, cache and constant attribute of any argument in our set that also appears in the othe...
virtual RooAbsArg * addClone(const RooAbsArg &var, bool silent=false)
Add a clone of the specified argument to list.
void setDirtyProp(bool flag)
Control propagation of dirty flags from observables in dataset.
RooFit::OwningPtr< RooAbsData > reduce(const RooCmdArg &arg1, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={})
Create a reduced copy of this dataset.
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Abstract base class for generator contexts of RooAbsPdf objects.
virtual RooDataSet * createDataSet(const char *name, const char *title, const RooArgSet &obs)
Create an empty dataset to hold the events that will be generated.
std::vector< Int_t > _protoOrder
LUT with traversal order of prototype data.
RooAbsPdf::ExtendMode _extendMode
Extended mode capabilities of p.d.f.
StyleOption defaultPrintStyle(Option_t *opt) const override
Define default print style.
Int_t defaultPrintContents(Option_t *opt) const override
Define default contents when printing.
virtual void attach(const RooArgSet &params)
Interface to attach given parameters to object in this context.
RooDataSet * _genData
! Data being generated
virtual RooDataSet * generate(double nEvents=0, bool skipInit=false, bool extendedMode=false)
Generate the specified number of events with nEvents>0 and and return a dataset containing the genera...
void printClassName(std::ostream &os) const override
Print class name of context.
void printName(std::ostream &os) const override
Print name of context.
virtual void initGenerator(const RooArgSet &theEvent)
Interface function to initialize context for generation for given set of observables.
RooArgSet _theEvent
Pointer to observable event being generated.
RooAbsGenContext(const RooAbsPdf &model, const RooArgSet &vars, const RooDataSet *prototype=nullptr, const RooArgSet *auxProto=nullptr, bool _verbose=false)
Constructor.
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Interface for multi-line printing.
const RooDataSet * _prototype
Pointer to prototype dataset.
void Print(Option_t *options=nullptr) const override
This method must be overridden when a class wants to print itself.
TString _normRange
Normalization range of pdf.
void printArgs(std::ostream &os) const override
Print arguments of context, i.e. the observables being generated in this context.
UInt_t _expectedEvents
Number of expected events from extended p.d.f.
Int_t _nextProtoIndex
Next prototype event to load according to LUT.
RooArgSet _protoVars
Prototype observables.
void printTitle(std::ostream &os) const override
Print title of context.
virtual void generateEvent(RooArgSet &theEvent, Int_t remaining)=0
bool _verbose
Verbose messaging?
bool _isValid
Is context in valid state?
bool isValid() const
virtual void setProtoDataOrder(Int_t *lut)
Set the traversal order of prototype data to that in the lookup tables passed as argument.
void resampleData(double &ratio)
Rescale existing output buffer with given ratio.
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
@ CanNotBeExtended
Definition RooAbsPdf.h:212
const char * normRange() const
Definition RooAbsPdf.h:250
virtual ExtendMode extendMode() const
Returns ability of PDF to provide extended likelihood terms.
Definition RooAbsPdf.h:216
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:55
bool isInRange(const char *rangeSpec)
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Definition RooArgSet.h:178
RooDataSet is a container class to hold unbinned data.
Definition RooDataSet.h:57
const RooArgSet * get(Int_t index) const override
Return RooArgSet with coordinates of event 'index'.
virtual void addFast(const RooArgSet &row, double weight=1.0, double weightError=0.0)
Add a data point, with its coordinates specified in the 'data' argset, to the data set.
static TRandom * randomGenerator()
Return a pointer to a singleton random-number generator implementation.
Definition RooRandom.cxx:51
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:48
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:207
virtual Int_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition TRandom.cxx:402
Basic string class.
Definition TString.h:139
Ssiz_t Length() const
Definition TString.h:421
const char * Data() const
Definition TString.h:380
TString & Prepend(const char *cs)
Definition TString.h:673
RooCmdArg EventRange(Int_t nStart, Int_t nStop)
const Int_t n
Definition legend1.C:16
Definition first.py:1
static void output()