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 <cmath>
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
79 auto creator = [](const RooAbsFunc& function, const RooNumIntConfig& config) {
80 return std::make_unique<RooMCIntegrator>(function,config);
81 };
82
83 // Register prototype and default config with factory
84 std::string name = "RooMCIntegrator";
85 fact.registerPlugin(name, creator, {samplingMode,genType,verbose,alpha,nRefineIter,nRefinePerDim,nIntPerDim},
86 /*canIntegrate1D=*/true,
87 /*canIntegrate2D=*/true,
88 /*canIntegrateND=*/true,
89 /*canIntegrateOpenEnded=*/false);
90
91 // Make this method the default for all N>2-dim integrals
93}
94
95
96////////////////////////////////////////////////////////////////////////////////
97/// Construct an integrator over 'function' with given sampling mode
98/// and generator type. The sampling mode can be 'Importance'
99/// (default), 'ImportanceOnly' and 'Stratified'. The generator type
100/// can be 'QuasiRandom' (default) and 'PseudoRandom'. Consult the original
101/// VEGAS documentation on details of the mode and type parameters.
102
104 GeneratorType genType, bool verbose) :
105 RooAbsIntegrator(function), _grid(function), _verbose(verbose),
106 _alpha(1.5), _mode(mode), _genType(genType),
107 _nRefineIter(5),_nRefinePerDim(1000),_nIntegratePerDim(5000)
108{
109 // coverity[UNINIT_CTOR]
110 if(!(_valid= _grid.isValid())) return;
111 if(_verbose) _grid.print(std::cout);
112}
113
114
115
116////////////////////////////////////////////////////////////////////////////////
117/// Construct an integrator over 'function' where the configuration details
118/// are taken from 'config'
119
121 RooAbsIntegrator(function), _grid(function)
122{
123 const RooArgSet& configSet = config.getConfigSection(ClassName()) ;
124 _verbose = (bool) configSet.getCatIndex("verbose",0) ;
125 _alpha = configSet.getRealValue("alpha",1.5) ;
126 _mode = (SamplingMode) configSet.getCatIndex("samplingMode",Importance) ;
127 _genType = (GeneratorType) configSet.getCatIndex("genType",QuasiRandom) ;
128 _nRefineIter = (Int_t) configSet.getRealValue("nRefineIter",5) ;
129 _nRefinePerDim = (Int_t) configSet.getRealValue("nRefinePerDim",1000) ;
130 _nIntegratePerDim = (Int_t) configSet.getRealValue("nIntPerDim",5000) ;
131
132 // check that our grid initialized without errors
133 if(!(_valid= _grid.isValid())) return;
134 if(_verbose) _grid.print(std::cout);
135}
136
137
138////////////////////////////////////////////////////////////////////////////////
139/// Destructor
140
142{
143}
144
145
146
147////////////////////////////////////////////////////////////////////////////////
148/// Check if we can integrate over the current domain. If return value
149/// is true we cannot handle the current limits (e.g. where the domain
150/// of one or more observables is open ended.
151
153{
154 return _grid.initialize(*integrand());
155}
156
157
158
159////////////////////////////////////////////////////////////////////////////////
160/// Evaluate the integral using a fixed number of calls to evaluate the integrand
161/// equal to about 10k per dimension. Use the first 5k calls to refine the grid
162/// over 5 iterations of 1k calls each, and the remaining 5k calls for a single
163/// high statistics integration.
164
165double RooMCIntegrator::integral(const double* /*yvec*/)
166{
167 _timer.Start(true);
170 return ret ;
171}
172
173
174
175////////////////////////////////////////////////////////////////////////////////
176/// Perform one step of Monte Carlo integration using the specified number of iterations
177/// with (approximately) the specified number of integrand evaluation calls per iteration.
178/// Use the VEGAS algorithm, starting from the specified stage. Returns the best estimate
179/// of the integral. Also sets *absError to the estimated absolute error of the integral
180/// estimate if absError is non-zero.
181
182double RooMCIntegrator::vegas(Stage stage, UInt_t calls, UInt_t iterations, double *absError)
183{
184 //cout << "VEGAS stage = " << stage << " calls = " << calls << " iterations = " << iterations << endl ;
185
186 // reset the grid to its initial state if we are starting from scratch
187 if(stage == AllStages) _grid.initialize(*_function);
188
189 // reset the results of previous calculations on this grid, but reuse the grid itself.
190 if(stage <= ReuseGrid) {
191 _wtd_int_sum = 0;
192 _sum_wgts = 0;
193 _chi_sum = 0;
194 _it_num = 1;
195 _samples = 0;
196 }
197
198 // refine the results of previous calculations on the current grid.
199 if(stage <= RefineGrid) {
201 UInt_t boxes = 1;
203
204 // select the sampling mode for the next step
205 if(_mode != ImportanceOnly) {
206 // calculate the largest number of equal subdivisions ("boxes") along each
207 // axis that results in an average of no more than 2 integrand calls per cell
208 boxes = (UInt_t)floor(TMath::Power(calls/2.0,1.0/dim));
209 // use stratified sampling if we are allowed enough calls (or equivalently,
210 // if the dimension is low enough)
212 if (2*boxes >= RooGrid::maxBins) {
214 // adjust the number of bins and boxes to give an integral number >= 1 of boxes per bin
215 Int_t box_per_bin= (boxes > RooGrid::maxBins) ? boxes/RooGrid::maxBins : 1;
216 bins= boxes/box_per_bin;
217 if(bins > RooGrid::maxBins) bins= RooGrid::maxBins;
218 boxes = box_per_bin * bins;
219 oocxcoutD((TObject*)nullptr,Integration) << "RooMCIntegrator: using stratified sampling with " << bins << " bins and "
220 << box_per_bin << " boxes/bin" << endl;
221 }
222 else {
223 oocxcoutD((TObject*)nullptr,Integration) << "RooMCIntegrator: using importance sampling with " << bins << " bins and "
224 << boxes << " boxes" << endl;
225 }
226 }
227
228 // calculate the total number of n-dim boxes for this step
229 double tot_boxes = TMath::Power((double)boxes,(double)dim);
230
231 // increase the total number of calls to get at least 2 calls per box, if necessary
232 _calls_per_box = (UInt_t)(calls/tot_boxes);
234 calls= (UInt_t)(_calls_per_box*tot_boxes);
235
236 // calculate the Jacobean factor: volume/(avg # of calls/bin)
237 _jac = _grid.getVolume()*TMath::Power((double)bins,(double)dim)/calls;
238
239 // setup our grid to use the calculated number of boxes and bins
240 _grid.setNBoxes(boxes);
241 if(bins != _grid.getNBins()) _grid.resize(bins);
242 }
243
244 // allocate memory for some book-keeping arrays
245 std::vector<UInt_t> box(_grid.getDimension());
246 std::vector<UInt_t> bin(_grid.getDimension());
247 std::vector<double> x(_grid.getDimension());
248
249
250 // loop over iterations for this step
251 double cum_int(0),cum_sig(0);
253 _chisq = 0.0;
254 for (UInt_t it = 0; it < iterations; it++) {
255 double intgrl(0),intgrl_sq(0),sig(0),jacbin(_jac);
256
257 _it_num = _it_start + it;
258
259 // reset the values associated with each grid cell
261
262 // loop over grid boxes
263 _grid.firstBox(box.data());
264 do {
265 double m(0),q(0);
266 // loop over integrand evaluations within this grid box
267 for(UInt_t k = 0; k < _calls_per_box; k++) {
268 // generate a random point in this box
269 double bin_vol(0);
270 _grid.generatePoint(box.data(), x.data(), bin.data(), bin_vol, _genType == QuasiRandom ? true : false);
271 // evaluate the integrand at the generated point
272 double fval= jacbin*bin_vol*integrand(x.data());
273 // update mean and variance calculations
274 double d = fval - m;
275 m+= d / (k + 1.0);
276 q+= d * d * (k / (k + 1.0));
277 // accumulate the results of this evaluation (importance sampling only)
278 if (_mode != Stratified) _grid.accumulate(bin.data(), fval*fval);
279 }
280 intgrl += m * _calls_per_box;
281 double f_sq_sum = q * _calls_per_box ;
282 sig += f_sq_sum ;
283
284 // accumulate the results for this grid box (stratified sampling only)
285 if (_mode == Stratified) _grid.accumulate(bin.data(), f_sq_sum);
286
287 // print occasional progress messages
288 if(_timer.RealTime() > 30) {
289 std::size_t index = 0;
290 std::size_t sizeOfDim = 1;
291
292 for (unsigned int i=0; i < _grid.getDimension(); ++i) {
293 index += box[i] * sizeOfDim;
294 sizeOfDim *= _grid.getNBoxes();
295 }
296 coutP(Integration) << "RooMCIntegrator: still working ... iteration "
297 << it << '/' << iterations << " box " << index << "/"<< std::pow(_grid.getNBoxes(), _grid.getDimension()) << endl;
298 _timer.Start(true);
299 }
300 else {
301 _timer.Start(false);
302 }
303
304 } while(_grid.nextBox(box.data()));
305
306 // compute final results for this iteration
307 double wgt;
308 sig = sig / (_calls_per_box - 1.0) ;
309 if (sig > 0) {
310 wgt = 1.0 / sig;
311 }
312 else if (_sum_wgts > 0) {
313 wgt = _sum_wgts / _samples;
314 }
315 else {
316 wgt = 0.0;
317 }
318 intgrl_sq = intgrl * intgrl;
319 _result = intgrl;
320 _sigma = sqrt(sig);
321
322 if (wgt > 0.0) {
323 _samples++ ;
324 _sum_wgts += wgt;
325 _wtd_int_sum += intgrl * wgt;
326 _chi_sum += intgrl_sq * wgt;
327
328 cum_int = _wtd_int_sum / _sum_wgts;
329 cum_sig = sqrt (1 / _sum_wgts);
330
331 if (_samples > 1) {
332 _chisq = (_chi_sum - _wtd_int_sum * cum_int)/(_samples - 1.0);
333 }
334 }
335 else {
336 cum_int += (intgrl - cum_int) / (it + 1.0);
337 cum_sig = 0.0;
338 }
339 oocxcoutD((TObject*)nullptr,Integration) << "=== Iteration " << _it_num << " : I = " << intgrl << " +/- " << sqrt(sig) << endl
340 << " Cumulative : I = " << cum_int << " +/- " << cum_sig << "( chi2 = " << _chisq
341 << ")" << endl;
342 // print the grid after the final iteration
343 if (oodologD((TObject*)nullptr,Integration)) {
344 if(it + 1 == iterations) _grid.print(std::cout, true);
345 }
347 }
348
349 if(absError) *absError = cum_sig;
350 return cum_int;
351}
#define d(i)
Definition RSha256.hxx:102
#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
char name[80]
Definition TGX11.cxx:110
float * q
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
Abstract interface for integrators of real-valued functions that implement the RooAbsFunc interface.
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
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
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
@ maxBins
Definition RooGrid.h:53
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.
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(const RooAbsFunc &function, SamplingMode mode=Importance, GeneratorType genType=QuasiRandom, bool verbose=false)
Construct an integrator over 'function' with given sampling mode and generator type.
~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 registerPlugin(std::string const &name, Creator const &creator, const RooArgSet &defConfig, bool canIntegrate1D, bool canIntegrate2D, bool canIntegrateND, bool canIntegrateOpenEnded, 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:37
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:721
TMarker m
Definition textangle.C:8