Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooMCIntegrator.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 RooMCIntegrator.cxx
19\class RooMCIntegrator
20\ingroup Roofitcore
21
22RooMCIntegrator implements an adaptive multi-dimensional Monte Carlo
23numerical integration, following the VEGAS algorithm originally described
24in G. P. Lepage, J. Comp. Phys. 27, 192(1978). This implementation is
25based on a C version from the 0.9 beta release of the GNU scientific library.
26**/
27
28#include "Riostream.h"
29
30#include "TMath.h"
31#include "RooMCIntegrator.h"
32#include "RooArgSet.h"
33#include "RooNumber.h"
34#include "RooNumIntFactory.h"
35#include "RooRealVar.h"
36#include "RooCategory.h"
37#include "RooMsgService.h"
38
39#include <math.h>
40
41
42
43using namespace std;
44
46;
47
48// Register this class with RooNumIntFactory
49
50
51////////////////////////////////////////////////////////////////////////////////
52/// This function registers class RooMCIntegrator, its configuration options
53/// and its capabilities with RooNumIntFactory
54
56{
57 RooCategory samplingMode("samplingMode","Sampling Mode") ;
58 samplingMode.defineType("Importance",RooMCIntegrator::Importance) ;
59 samplingMode.defineType("ImportanceOnly",RooMCIntegrator::ImportanceOnly) ;
60 samplingMode.defineType("Stratified",RooMCIntegrator::Stratified) ;
62
63 RooCategory genType("genType","Generator Type") ;
64 genType.defineType("QuasiRandom",RooMCIntegrator::QuasiRandom) ;
65 genType.defineType("PseudoRandom",RooMCIntegrator::PseudoRandom) ;
67
68 RooCategory verbose("verbose","Verbose flag") ;
69 verbose.defineType("true",1) ;
70 verbose.defineType("false",0) ;
71 verbose.setIndex(0) ;
72
73 RooRealVar alpha("alpha","Grid structure constant",1.5) ;
74 RooRealVar nRefineIter("nRefineIter","Number of refining iterations",5) ;
75 RooRealVar nRefinePerDim("nRefinePerDim","Number of refining samples (per dimension)",1000) ;
76 RooRealVar nIntPerDim("nIntPerDim","Number of integration samples (per dimension)",5000) ;
77
78 // Create prototype integrator
80
81 // Register prototype and default config with factory
82 fact.storeProtoIntegrator(proto,RooArgSet(samplingMode,genType,verbose,alpha,nRefineIter,nRefinePerDim,nIntPerDim)) ;
83
84 // Make this method the default for all N>2-dim integrals
86}
87
88
89
90////////////////////////////////////////////////////////////////////////////////
91/// Default constructor
92///
93/// coverity[UNINIT_CTOR]
94
96{
97}
98
99
100
101////////////////////////////////////////////////////////////////////////////////
102/// Construct an integrator over 'function' with given sampling mode
103/// and generator type. The sampling mode can be 'Importance'
104/// (default), 'ImportanceOnly' and 'Stratified'. The generator type
105/// can be 'QuasiRandom' (default) and 'PseudoRandom'. Consult the original
106/// VEGAS documentation on details of the mode and type parameters.
107
109 GeneratorType genType, bool verbose) :
110 RooAbsIntegrator(function), _grid(function), _verbose(verbose),
111 _alpha(1.5), _mode(mode), _genType(genType),
112 _nRefineIter(5),_nRefinePerDim(1000),_nIntegratePerDim(5000)
113{
114 // coverity[UNINIT_CTOR]
115 if(!(_valid= _grid.isValid())) return;
116 if(_verbose) _grid.print(std::cout);
117}
118
119
120
121////////////////////////////////////////////////////////////////////////////////
122/// Construct an integrator over 'function' where the configuration details
123/// are taken from 'config'
124
126 RooAbsIntegrator(function), _grid(function)
127{
128 const RooArgSet& configSet = config.getConfigSection(ClassName()) ;
129 _verbose = (bool) configSet.getCatIndex("verbose",0) ;
130 _alpha = configSet.getRealValue("alpha",1.5) ;
131 _mode = (SamplingMode) configSet.getCatIndex("samplingMode",Importance) ;
132 _genType = (GeneratorType) configSet.getCatIndex("genType",QuasiRandom) ;
133 _nRefineIter = (Int_t) configSet.getRealValue("nRefineIter",5) ;
134 _nRefinePerDim = (Int_t) configSet.getRealValue("nRefinePerDim",1000) ;
135 _nIntegratePerDim = (Int_t) configSet.getRealValue("nIntPerDim",5000) ;
136
137 // check that our grid initialized without errors
138 if(!(_valid= _grid.isValid())) return;
139 if(_verbose) _grid.print(std::cout);
140}
141
142
143
144////////////////////////////////////////////////////////////////////////////////
145/// Return clone of this generator operating on given function with given configuration
146/// Needed to support RooNumIntFactory
147
149{
150 return new RooMCIntegrator(function,config) ;
151}
152
153
154
155////////////////////////////////////////////////////////////////////////////////
156/// Destructor
157
159{
160}
161
162
163
164////////////////////////////////////////////////////////////////////////////////
165/// Check if we can integrate over the current domain. If return value
166/// is true we cannot handle the current limits (e.g. where the domain
167/// of one or more observables is open ended.
168
170{
171 return _grid.initialize(*integrand());
172}
173
174
175
176////////////////////////////////////////////////////////////////////////////////
177/// Evaluate the integral using a fixed number of calls to evaluate the integrand
178/// equal to about 10k per dimension. Use the first 5k calls to refine the grid
179/// over 5 iterations of 1k calls each, and the remaining 5k calls for a single
180/// high statistics integration.
181
182double RooMCIntegrator::integral(const double* /*yvec*/)
183{
184 _timer.Start(true);
187 return ret ;
188}
189
190
191
192////////////////////////////////////////////////////////////////////////////////
193/// Perform one step of Monte Carlo integration using the specified number of iterations
194/// with (approximately) the specified number of integrand evaluation calls per iteration.
195/// Use the VEGAS algorithm, starting from the specified stage. Returns the best estimate
196/// of the integral. Also sets *absError to the estimated absolute error of the integral
197/// estimate if absError is non-zero.
198
199double RooMCIntegrator::vegas(Stage stage, UInt_t calls, UInt_t iterations, double *absError)
200{
201 //cout << "VEGAS stage = " << stage << " calls = " << calls << " iterations = " << iterations << endl ;
202
203 // reset the grid to its initial state if we are starting from scratch
204 if(stage == AllStages) _grid.initialize(*_function);
205
206 // reset the results of previous calculations on this grid, but reuse the grid itself.
207 if(stage <= ReuseGrid) {
208 _wtd_int_sum = 0;
209 _sum_wgts = 0;
210 _chi_sum = 0;
211 _it_num = 1;
212 _samples = 0;
213 }
214
215 // refine the results of previous calculations on the current grid.
216 if(stage <= RefineGrid) {
218 UInt_t boxes = 1;
220
221 // select the sampling mode for the next step
222 if(_mode != ImportanceOnly) {
223 // calculate the largest number of equal subdivisions ("boxes") along each
224 // axis that results in an average of no more than 2 integrand calls per cell
225 boxes = (UInt_t)floor(TMath::Power(calls/2.0,1.0/dim));
226 // use stratified sampling if we are allowed enough calls (or equivalently,
227 // if the dimension is low enough)
229 if (2*boxes >= RooGrid::maxBins) {
231 // adjust the number of bins and boxes to give an integral number >= 1 of boxes per bin
232 Int_t box_per_bin= (boxes > RooGrid::maxBins) ? boxes/RooGrid::maxBins : 1;
233 bins= boxes/box_per_bin;
234 if(bins > RooGrid::maxBins) bins= RooGrid::maxBins;
235 boxes = box_per_bin * bins;
236 oocxcoutD((TObject*)0,Integration) << "RooMCIntegrator: using stratified sampling with " << bins << " bins and "
237 << box_per_bin << " boxes/bin" << endl;
238 }
239 else {
240 oocxcoutD((TObject*)0,Integration) << "RooMCIntegrator: using importance sampling with " << bins << " bins and "
241 << boxes << " boxes" << endl;
242 }
243 }
244
245 // calculate the total number of n-dim boxes for this step
246 double tot_boxes = TMath::Power((double)boxes,(double)dim);
247
248 // increase the total number of calls to get at least 2 calls per box, if necessary
249 _calls_per_box = (UInt_t)(calls/tot_boxes);
251 calls= (UInt_t)(_calls_per_box*tot_boxes);
252
253 // calculate the Jacobean factor: volume/(avg # of calls/bin)
254 _jac = _grid.getVolume()*TMath::Power((double)bins,(double)dim)/calls;
255
256 // setup our grid to use the calculated number of boxes and bins
257 _grid.setNBoxes(boxes);
258 if(bins != _grid.getNBins()) _grid.resize(bins);
259 }
260
261 // allocate memory for some book-keeping arrays
262 std::vector<UInt_t> box(_grid.getDimension());
263 std::vector<UInt_t> bin(_grid.getDimension());
264 std::vector<double> x(_grid.getDimension());
265
266
267 // loop over iterations for this step
268 double cum_int(0),cum_sig(0);
270 _chisq = 0.0;
271 for (UInt_t it = 0; it < iterations; it++) {
272 double intgrl(0),intgrl_sq(0),sig(0),jacbin(_jac);
273
274 _it_num = _it_start + it;
275
276 // reset the values associated with each grid cell
278
279 // loop over grid boxes
280 _grid.firstBox(box.data());
281 do {
282 double m(0),q(0);
283 // loop over integrand evaluations within this grid box
284 for(UInt_t k = 0; k < _calls_per_box; k++) {
285 // generate a random point in this box
286 double bin_vol(0);
287 _grid.generatePoint(box.data(), x.data(), bin.data(), bin_vol, _genType == QuasiRandom ? true : false);
288 // evaluate the integrand at the generated point
289 double fval= jacbin*bin_vol*integrand(x.data());
290 // update mean and variance calculations
291 double d = fval - m;
292 m+= d / (k + 1.0);
293 q+= d * d * (k / (k + 1.0));
294 // accumulate the results of this evaluation (importance sampling only)
295 if (_mode != Stratified) _grid.accumulate(bin.data(), fval*fval);
296 }
297 intgrl += m * _calls_per_box;
298 double f_sq_sum = q * _calls_per_box ;
299 sig += f_sq_sum ;
300
301 // accumulate the results for this grid box (stratified sampling only)
302 if (_mode == Stratified) _grid.accumulate(bin.data(), f_sq_sum);
303
304 // print occasional progress messages
305 if(_timer.RealTime() > 30) {
306 std::size_t index = 0;
307 std::size_t sizeOfDim = 1;
308
309 for (unsigned int i=0; i < _grid.getDimension(); ++i) {
310 index += box[i] * sizeOfDim;
311 sizeOfDim *= _grid.getNBoxes();
312 }
313 coutP(Integration) << "RooMCIntegrator: still working ... iteration "
314 << it << '/' << iterations << " box " << index << "/"<< std::pow(_grid.getNBoxes(), _grid.getDimension()) << endl;
315 _timer.Start(true);
316 }
317 else {
318 _timer.Start(false);
319 }
320
321 } while(_grid.nextBox(box.data()));
322
323 // compute final results for this iteration
324 double wgt;
325 sig = sig / (_calls_per_box - 1.0) ;
326 if (sig > 0) {
327 wgt = 1.0 / sig;
328 }
329 else if (_sum_wgts > 0) {
330 wgt = _sum_wgts / _samples;
331 }
332 else {
333 wgt = 0.0;
334 }
335 intgrl_sq = intgrl * intgrl;
336 _result = intgrl;
337 _sigma = sqrt(sig);
338
339 if (wgt > 0.0) {
340 _samples++ ;
341 _sum_wgts += wgt;
342 _wtd_int_sum += intgrl * wgt;
343 _chi_sum += intgrl_sq * wgt;
344
345 cum_int = _wtd_int_sum / _sum_wgts;
346 cum_sig = sqrt (1 / _sum_wgts);
347
348 if (_samples > 1) {
349 _chisq = (_chi_sum - _wtd_int_sum * cum_int)/(_samples - 1.0);
350 }
351 }
352 else {
353 cum_int += (intgrl - cum_int) / (it + 1.0);
354 cum_sig = 0.0;
355 }
356 oocxcoutD((TObject*)0,Integration) << "=== Iteration " << _it_num << " : I = " << intgrl << " +/- " << sqrt(sig) << endl
357 << " Cumulative : I = " << cum_int << " +/- " << cum_sig << "( chi2 = " << _chisq
358 << ")" << endl;
359 // print the grid after the final iteration
360 if (oodologD((TObject*)0,Integration)) {
361 if(it + 1 == iterations) _grid.print(std::cout, true);
362 }
364 }
365
366 if(absError) *absError = cum_sig;
367 return cum_int;
368}
#define d(i)
Definition RSha256.hxx:102
bool _verbose
Definition RooMinuit.h:94
#define coutP(a)
#define oocxcoutD(o, a)
#define oodologD(o, a)
int Int_t
Definition RtypesCore.h:45
unsigned int UInt_t
Definition RtypesCore.h:46
#define ClassImp(name)
Definition Rtypes.h:377
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t TPoint TPoint const char mode
float * q
const char * proto
Definition civetweb.c:17502
double getRealValue(const char *name, double defVal=0.0, bool verbose=false) const
Get value of a RooAbsReal stored in set with given name.
Int_t getCatIndex(const char *name, Int_t defVal=0, bool verbose=false) const
Get index value of a RooAbsCategory stored in set with given name.
Abstract interface for evaluating a real-valued function of one real variable and performing numerica...
Definition RooAbsFunc.h:27
RooAbsIntegrator is the abstract interface for integrators of real-valued functions that implement th...
const RooAbsFunc * _function
Pointer to function binding of integrand.
const RooAbsFunc * integrand() const
Return integrand function binding.
bool _valid
Is integrator in valid state?
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:55
RooCategory is an object to represent discrete states.
Definition RooCategory.h:28
bool setIndex(Int_t index, bool printError=true) override
Set value by specifying the index code of the desired state.
bool defineType(const std::string &label)
Define a state with given name.
bool setLabel(const char *label, bool printError=true) override
Set value by specifying the name of the desired state.
UInt_t getDimension() const
Definition RooGrid.h:36
@ maxBins
Definition RooGrid.h:53
bool initialize(const RooAbsFunc &function)
Calculate and store the grid dimensions and volume using the specified function, and initialize the g...
Definition RooGrid.cxx:72
void generatePoint(const UInt_t box[], double x[], UInt_t bin[], double &vol, bool useQuasiRandom=true) const
Generate a random vector in the specified box and store its coordinates in the x[] array provided,...
Definition RooGrid.cxx:162
double getVolume() const
Definition RooGrid.h:37
bool isValid() const
Definition RooGrid.h:35
UInt_t getNBins() const
Definition RooGrid.h:38
UInt_t getNBoxes() const
Definition RooGrid.h:39
void resetValues()
Reset the values associated with each grid cell.
Definition RooGrid.cxx:145
void accumulate(const UInt_t bin[], double amount)
Add the specified amount to bin[j] of the 1D histograms associated with each axis j.
Definition RooGrid.cxx:262
bool nextBox(UInt_t box[]) const
Update the specified array of box indices to refer to the next box in the standard traversal order an...
Definition RooGrid.cxx:222
void resize(UInt_t bins)
Adjust the subdivision of each axis to give the specified number of bins, using an algorithm that pre...
Definition RooGrid.cxx:108
void setNBoxes(UInt_t boxes)
Definition RooGrid.h:40
void refine(double alpha=1.5)
Refine the grid using the values that have been accumulated so far.
Definition RooGrid.cxx:274
void firstBox(UInt_t box[]) const
Reset the specified array of box indices to refer to the first box in the standard traversal order.
Definition RooGrid.cxx:210
void print(std::ostream &os, bool verbose=false, std::string const &indent="") const
Print info about this object to the specified stream.
Definition RooGrid.cxx:241
RooMCIntegrator implements an adaptive multi-dimensional Monte Carlo numerical integration,...
GeneratorType _genType
Generator type.
RooAbsIntegrator * clone(const RooAbsFunc &function, const RooNumIntConfig &config) const override
Return clone of this generator operating on given function with given configuration Needed to support...
RooMCIntegrator()
Default constructor.
static void registerIntegrator(RooNumIntFactory &fact)
This function registers class RooMCIntegrator, its configuration options and its capabilities with Ro...
TStopwatch _timer
Timer.
Int_t _nIntegratePerDim
Number of integration samplings (per dim)
~RooMCIntegrator() override
Destructor.
bool checkLimits() const override
Check if we can integrate over the current domain.
double _sigma
Scratch variables preserved between calls to vegas1/2/2.
double vegas(Stage stage, UInt_t calls, UInt_t iterations, double *absError=nullptr)
Perform one step of Monte Carlo integration using the specified number of iterations with (approximat...
bool _verbose
Verbosity control.
Int_t _mode
Sampling mode.
Int_t _nRefinePerDim
Number of refinement samplings (per dim)
double _alpha
Grid stiffness parameter.
UInt_t _calls_per_box
Scratch variables preserved between calls to vegas1/2/2.
Int_t _nRefineIter
Number of refinement iterations.
double integral(const double *yvec=nullptr) override
Evaluate the integral using a fixed number of calls to evaluate the integrand equal to about 10k per ...
RooNumIntConfig holds the configuration parameters of the various numeric integrators used by RooReal...
RooCategory & methodND()
const RooArgSet & getConfigSection(const char *name) const
Retrieve configuration information specific to integrator with given name.
static RooNumIntConfig & defaultConfig()
Return reference to instance of default numeric integrator configuration object.
RooNumIntFactory is a factory to instantiate numeric integrators from a given function binding and a ...
bool storeProtoIntegrator(RooAbsIntegrator *proto, const RooArgSet &defConfig, const char *depName="")
Method accepting registration of a prototype numeric integrator along with a RooArgSet of its default...
RooRealVar represents a variable that can be changed from the outside.
Definition RooRealVar.h:40
Mother of all ROOT objects.
Definition TObject.h:41
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:207
Double_t RealTime()
Stop the stopwatch (if it is running) and return the realtime (in seconds) passed between the start a...
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
void box(Int_t pat, Double_t x1, Double_t y1, Double_t x2, Double_t y2)
Definition fillpatterns.C:1
Double_t x[n]
Definition legend1.C:17
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Returns x raised to the power y.
Definition TMath.h:719
TMarker m
Definition textangle.C:8