Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
IntervalExamples.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_roostats
3/// \notebook
4/// Example showing confidence intervals with four techniques.
5///
6/// An example that shows confidence intervals with four techniques.
7/// The model is a Normal Gaussian G(x|mu,sigma) with 100 samples of x.
8/// The answer is known analytically, so this is a good example to validate
9/// the RooStats tools.
10///
11/// - expected interval is [-0.162917, 0.229075]
12/// - plc interval is [-0.162917, 0.229075]
13/// - fc interval is [-0.17 , 0.23] // stepsize is 0.01
14/// - bc interval is [-0.162918, 0.229076]
15/// - mcmc interval is [-0.166999, 0.230224]
16///
17/// \macro_image
18/// \macro_output
19/// \macro_code
20///
21/// \author Kyle Cranmer
22
32
34
35#include "RooRandom.h"
36#include "RooDataSet.h"
37#include "RooRealVar.h"
38#include "RooConstVar.h"
39#include "RooAddition.h"
40#include "RooDataHist.h"
41#include "RooPoisson.h"
42#include "RooPlot.h"
43
44#include "TCanvas.h"
45#include "TTree.h"
46#include "TStyle.h"
47#include "TMath.h"
48#include "Math/DistFunc.h"
49#include "TH1F.h"
50#include "TMarker.h"
51#include "TStopwatch.h"
52
53#include <iostream>
54
55// use this order for safety on library loading
56using namespace RooFit;
57using namespace RooStats;
58
60{
61
62 // Time this macro
63 TStopwatch t;
64 t.Start();
65
66 // set RooFit random seed for reproducible results
68
69 // make a simple model via the workspace factory
70 RooWorkspace *wspace = new RooWorkspace();
71 wspace->factory("Gaussian::normal(x[-10,10],mu[-1,1],sigma[1])");
72 wspace->defineSet("poi", "mu");
73 wspace->defineSet("obs", "x");
74
75 // specify components of model for statistical tools
76 ModelConfig *modelConfig = new ModelConfig("Example G(x|mu,1)");
77 modelConfig->SetWorkspace(*wspace);
78 modelConfig->SetPdf(*wspace->pdf("normal"));
79 modelConfig->SetParametersOfInterest(*wspace->set("poi"));
80 modelConfig->SetObservables(*wspace->set("obs"));
81
82 // create a toy dataset
83 std::unique_ptr<RooDataSet> data{wspace->pdf("normal")->generate(*wspace->set("obs"), 100)};
84 data->Print();
85
86 // for convenience later on
87 RooRealVar *x = wspace->var("x");
88 RooRealVar *mu = wspace->var("mu");
89
90 // set confidence level
91 double confidenceLevel = 0.95;
92
93 // example use profile likelihood calculator
94 ProfileLikelihoodCalculator plc(*data, *modelConfig);
95 plc.SetConfidenceLevel(confidenceLevel);
96 LikelihoodInterval *plInt = plc.GetInterval();
97
98 // example use of Feldman-Cousins
99 FeldmanCousins fc(*data, *modelConfig);
100 fc.SetConfidenceLevel(confidenceLevel);
101 fc.SetNBins(100); // number of points to test per parameter
102 fc.UseAdaptiveSampling(true); // make it go faster
103
104 // Here, we consider only ensembles with 100 events
105 // The PDF could be extended and this could be removed
106 fc.FluctuateNumDataEntries(false);
107
108 PointSetInterval *interval = (PointSetInterval *)fc.GetInterval();
109
110 // example use of BayesianCalculator
111 // now we also need to specify a prior in the ModelConfig
112 wspace->factory("Uniform::prior(mu)");
113 modelConfig->SetPriorPdf(*wspace->pdf("prior"));
114
115 // example usage of BayesianCalculator
116 BayesianCalculator bc(*data, *modelConfig);
117 bc.SetConfidenceLevel(confidenceLevel);
118 SimpleInterval *bcInt = bc.GetInterval();
119
120 // example use of MCMCInterval
121 MCMCCalculator mc(*data, *modelConfig);
122 mc.SetConfidenceLevel(confidenceLevel);
123 // special options
124 mc.SetNumBins(200); // bins used internally for representing posterior
125 mc.SetNumBurnInSteps(500); // first N steps to be ignored as burn-in
126 mc.SetNumIters(100000); // how long to run chain
127 mc.SetLeftSideTailFraction(0.5); // for central interval
128 MCMCInterval *mcInt = mc.GetInterval();
129
130 // for this example we know the expected intervals
131 double expectedLL =
132 data->mean(*x) + ROOT::Math::normal_quantile((1 - confidenceLevel) / 2, 1) / sqrt(data->numEntries());
133 double expectedUL =
134 data->mean(*x) + ROOT::Math::normal_quantile_c((1 - confidenceLevel) / 2, 1) / sqrt(data->numEntries());
135
136 // Use the intervals
137 std::cout << "expected interval is [" << expectedLL << ", " << expectedUL << "]" << endl;
138
139 cout << "plc interval is [" << plInt->LowerLimit(*mu) << ", " << plInt->UpperLimit(*mu) << "]" << endl;
140
141 std::cout << "fc interval is [" << interval->LowerLimit(*mu) << " , " << interval->UpperLimit(*mu) << "]" << endl;
142
143 cout << "bc interval is [" << bcInt->LowerLimit() << ", " << bcInt->UpperLimit() << "]" << endl;
144
145 cout << "mc interval is [" << mcInt->LowerLimit(*mu) << ", " << mcInt->UpperLimit(*mu) << "]" << endl;
146
147 mu->setVal(0);
148 cout << "is mu=0 in the interval? " << plInt->IsInInterval(RooArgSet(*mu)) << endl;
149
150 // make a reasonable style
160
161 // some plots
162 TCanvas *canvas = new TCanvas("canvas");
163 canvas->Divide(2, 2);
164
165 // plot the data
166 canvas->cd(1);
167 RooPlot *frame = x->frame();
168 data->plotOn(frame);
169 data->statOn(frame);
170 frame->Draw();
171
172 // plot the profile likelihood
173 canvas->cd(2);
175 plot.Draw();
176
177 // plot the MCMC interval
178 canvas->cd(3);
179 MCMCIntervalPlot *mcPlot = new MCMCIntervalPlot(*mcInt);
180 mcPlot->SetLineColor(kGreen);
181 mcPlot->SetLineWidth(2);
182 mcPlot->Draw();
183
184 canvas->cd(4);
185 RooPlot *bcPlot = bc.GetPosteriorPlot();
186 bcPlot->Draw();
187
188 canvas->Update();
189
190 t.Stop();
191 t.Print();
192}
@ kGreen
Definition Rtypes.h:66
winID h TVirtualViewer3D TVirtualGLPainter char TVirtualGLPainter plot
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
R__EXTERN TStyle * gStyle
Definition TStyle.h:436
RooFit::OwningPtr< RooDataSet > generate(const RooArgSet &whatVars, Int_t nEvents, const RooCmdArg &arg1, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={})
See RooAbsPdf::generate(const RooArgSet&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,...
Definition RooAbsPdf.h:57
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
Plot frame and a container for graphics objects within that frame.
Definition RooPlot.h:43
static RooPlot * frame(const RooAbsRealLValue &var, double xmin, double xmax, Int_t nBins)
Create a new frame for a given variable in x.
Definition RooPlot.cxx:185
void Draw(Option_t *options=nullptr) override
Draw this plot and all of the elements it contains.
Definition RooPlot.cxx:597
static TRandom * randomGenerator()
Return a pointer to a singleton random-number generator implementation.
Definition RooRandom.cxx:48
Variable that can be changed from the outside.
Definition RooRealVar.h:37
void setVal(double value) override
Set value of variable to 'value'.
BayesianCalculator is a concrete implementation of IntervalCalculator, providing the computation of a...
The FeldmanCousins class (like the Feldman-Cousins technique) is essentially a specific configuration...
This class provides simple and straightforward utilities to plot a LikelihoodInterval object.
LikelihoodInterval is a concrete implementation of the RooStats::ConfInterval interface.
double UpperLimit(const RooRealVar &param)
return the upper bound of the interval on a given parameter
double LowerLimit(const RooRealVar &param)
return the lower bound of the interval on a given parameter
bool IsInInterval(const RooArgSet &) const override
check if given point is in the interval
Bayesian Calculator estimating an interval or a credible region using the Markov-Chain Monte Carlo me...
This class provides simple and straightforward utilities to plot a MCMCInterval object.
void SetLineColor(Color_t color)
void Draw(const Option_t *options=nullptr) override
void SetLineWidth(Int_t width)
MCMCInterval is a concrete implementation of the RooStats::ConfInterval interface.
virtual double UpperLimit(RooRealVar &param)
get the highest value of param that is within the confidence interval
virtual double LowerLimit(RooRealVar &param)
get the lowest value of param that is within the confidence interval
ModelConfig is a simple class that holds configuration information specifying how a model should be u...
Definition ModelConfig.h:35
virtual void SetObservables(const RooArgSet &set)
Specify the observables.
virtual void SetPriorPdf(const RooAbsPdf &pdf)
Set the Prior Pdf, add to the workspace if not already there.
Definition ModelConfig.h:95
virtual void SetWorkspace(RooWorkspace &ws)
Definition ModelConfig.h:71
virtual void SetParametersOfInterest(const RooArgSet &set)
Specify parameters of interest.
virtual void SetPdf(const RooAbsPdf &pdf)
Set the Pdf, add to the workspace if not already there.
Definition ModelConfig.h:88
PointSetInterval is a concrete implementation of the ConfInterval interface.
double UpperLimit(RooRealVar &param)
return upper limit on a given parameter
double LowerLimit(RooRealVar &param)
return lower limit on a given parameter
The ProfileLikelihoodCalculator is a concrete implementation of CombinedCalculator (the interface cla...
SimpleInterval is a concrete implementation of the ConfInterval interface.
virtual double UpperLimit()
return the interval upper limit
virtual double LowerLimit()
return the interval lower limit
Persistable container for RooFit projects.
RooAbsPdf * pdf(RooStringView name) const
Retrieve p.d.f (RooAbsPdf) with given name. A null pointer is returned if not found.
const RooArgSet * set(RooStringView name)
Return pointer to previously defined named set with given nmame If no such set is found a null pointe...
RooFactoryWSTool & factory()
Return instance to factory tool.
RooRealVar * var(RooStringView name) const
Retrieve real-valued variable (RooRealVar) with given name. A null pointer is returned if not found.
bool defineSet(const char *name, const RooArgSet &aset, bool importMissing=false)
Define a named RooArgSet with given constituents.
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
Definition TAttFill.h:37
The Canvas class.
Definition TCanvas.h:23
TVirtualPad * cd(Int_t subpadnumber=0) override
Set current canvas & pad.
Definition TCanvas.cxx:719
void Update() override
Update canvas pad buffers.
Definition TCanvas.cxx:2489
virtual void Draw(Option_t *option="")
Default Draw method for all objects.
Definition TObject.cxx:292
void Divide(Int_t nx=1, Int_t ny=1, Float_t xmargin=0.01, Float_t ymargin=0.01, Int_t color=0) override
Automatic pad generation by division.
Definition TPad.cxx:1249
virtual void SetSeed(ULong_t seed=0)
Set the random generator seed.
Definition TRandom.cxx:615
Stopwatch class.
Definition TStopwatch.h:28
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
void Stop()
Stop the stopwatch.
void Print(Option_t *option="") const override
Print the real and cpu time passed between the start and stop events.
void SetPadBorderMode(Int_t mode=1)
Definition TStyle.h:357
void SetFrameFillColor(Color_t color=1)
Definition TStyle.h:372
void SetCanvasColor(Color_t color=19)
Definition TStyle.h:343
void SetCanvasBorderMode(Int_t mode=1)
Definition TStyle.h:345
void SetTitleFillColor(Color_t color=1)
Definition TStyle.h:404
void SetStatColor(Color_t color=19)
Definition TStyle.h:390
void SetPadColor(Color_t color=19)
Definition TStyle.h:355
double normal_quantile(double z, double sigma)
Inverse ( ) of the cumulative distribution function of the lower tail of the normal (Gaussian) distri...
double normal_quantile_c(double z, double sigma)
Inverse ( ) of the cumulative distribution function of the upper tail of the normal (Gaussian) distri...
Double_t x[n]
Definition legend1.C:17
VecExpr< UnaryOp< Sqrt< T >, VecExpr< A, T, D >, T >, T, D > sqrt(const VecExpr< A, T, D > &rhs)
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:64
Namespace for the RooStats classes.
Definition CodegenImpl.h:58