Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
rs401d_FeldmanCousins.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_roostats
3/// \notebook
4/// Neutrino Oscillation Example from Feldman & Cousins
5///
6/// This tutorial shows a more complex example using the FeldmanCousins utility
7/// to create a confidence interval for a toy neutrino oscillation experiment.
8/// The example attempts to faithfully reproduce the toy example described in Feldman & Cousins'
9/// original paper, Phys.Rev.D57:3873-3889,1998.
10///
11/// \macro_image
12/// \macro_output
13/// \macro_code
14///
15/// \author Kyle Cranmer
16
17#include "RooGlobalFunc.h"
26
27#include "RooDataSet.h"
28#include "RooDataHist.h"
29#include "RooRealVar.h"
30#include "RooConstVar.h"
31#include "RooAddition.h"
32#include "RooProduct.h"
33#include "RooProdPdf.h"
34#include "RooAddPdf.h"
35
36#include "TROOT.h"
37#include "RooPolynomial.h"
38#include "RooRandom.h"
39
40#include "RooProfileLL.h"
41
42#include "RooPlot.h"
43
44#include "TCanvas.h"
45#include "TH1F.h"
46#include "TH2F.h"
47#include "TTree.h"
48#include "TMarker.h"
49#include "TStopwatch.h"
50
51#include <iostream>
52
53// use this order for safety on library loading
54using namespace RooFit;
55using namespace RooStats;
56
57void rs401d_FeldmanCousins(bool doFeldmanCousins = false, bool doMCMC = true)
58{
59
60 // to time the macro
61 TStopwatch t;
62 t.Start();
63
64 // Taken from Feldman & Cousins paper, Phys.Rev.D57:3873-3889,1998.
65 // e-Print: physics/9711021 (see page 13.)
66 //
67 // Quantum mechanics dictates that the probability of such a transformation is given by the formula
68 // $P (\nu\mu \rightarrow \nu e ) = sin^2 (2\theta) sin^2 (1.27 \Delta m^2 L /E )$
69 // where P is the probability for a $\nu\mu$ to transform into a $\nu e$ , L is the distance in km between
70 // the creation of the neutrino from meson decay and its interaction in the detector, E is the
71 // neutrino energy in GeV, and $\Delta m^2 = |m^2 - m^2 |$ in $(eV/c^2 )^2$ .
72 //
73 // To demonstrate how this works in practice, and how it compares to alternative approaches
74 // that have been used, we consider a toy model of a typical neutrino oscillation experiment.
75 // The toy model is defined by the following parameters: Mesons are assumed to decay to
76 // neutrinos uniformly in a region 600 m to 1000 m from the detector. The expected background
77 // from conventional $\nu e$ interactions and misidentified $\nu\mu$ interactions is assumed to be 100
78 // events in each of 5 energy bins which span the region from 10 to 60 GeV. We assume that
79 // the $\nu\mu$ flux is such that if $P (\nu\mu \rightarrow \nu e ) = 0.01$ averaged over any bin, then that bin
80 // would
81 // have an expected additional contribution of 100 events due to $\nu\mu \rightarrow \nu e$ oscillations.
82
83 // Make signal model model
84 RooRealVar E("E", "", 15, 10, 60, "GeV");
85 RooRealVar L("L", "", .800, .600, 1.0, "km"); // need these units in formula
86 RooRealVar deltaMSq("deltaMSq", "#Delta m^{2}", 40, 1, 300, "eV/c^{2}");
87 RooRealVar sinSq2theta("sinSq2theta", "sin^{2}(2#theta)", .006, .0, .02);
88 // RooRealVar deltaMSq("deltaMSq","#Delta m^{2}",40,20,70,"eV/c^{2}");
89 // RooRealVar sinSq2theta("sinSq2theta","sin^{2}(2#theta)", .006,.001,.01);
90 // PDF for oscillation only describes deltaMSq dependence, sinSq2theta goes into sigNorm
91 auto oscillationFormula = "std::pow(std::sin(1.27 * x[2] * x[0] / x[1]), 2)";
92 RooGenericPdf PnmuTone("PnmuTone", "P(#nu_{#mu} #rightarrow #nu_{e}", oscillationFormula, {L, E, deltaMSq});
93
94 // only E is observable, so create the signal model by integrating out L
95 RooAbsPdf *sigModel = PnmuTone.createProjection(L);
96
97 // create $ \int dE' dL' P(E',L' | \Delta m^2)$.
98 // Given RooFit will renormalize the PDF in the range of the observables,
99 // the average probability to oscillate in the experiment's acceptance
100 // needs to be incorporated into the extended term in the likelihood.
101 // Do this by creating a RooAbsReal representing the integral and divide by
102 // the area in the E-L plane.
103 // The integral should be over "primed" observables, so we need
104 // an independent copy of PnmuTone not to interfere with the original.
105
106 // Independent copy for Integral
107 RooRealVar EPrime("EPrime", "", 15, 10, 60, "GeV");
108 RooRealVar LPrime("LPrime", "", .800, .600, 1.0, "km"); // need these units in formula
109 RooGenericPdf PnmuTonePrime("PnmuTonePrime", "P(#nu_{#mu} #rightarrow #nu_{e}", oscillationFormula, {LPrime, EPrime, deltaMSq});
111
112 // Getting the flux is a bit tricky. It is more clear to include a cross section term that is not
113 // explicitly referred to in the text, eg.
114 // number events in bin = flux * cross-section for nu_e interaction in E bin * average prob nu_mu osc. to nu_e in bin
115 // let maxEventsInBin = flux * cross-section for nu_e interaction in E bin
116 // maxEventsInBin * 1% chance per bin = 100 events / bin
117 // therefore maxEventsInBin = 10,000.
118 // for 5 bins, this means maxEventsTot = 50,000
119 RooConstVar maxEventsTot("maxEventsTot", "maximum number of sinal events", 50000);
120 RooConstVar inverseArea("inverseArea", "1/(#Delta E #Delta L)",
121 1. / (EPrime.getMax() - EPrime.getMin()) / (LPrime.getMax() - LPrime.getMin()));
122
123 // $sigNorm = maxEventsTot \cdot \int dE dL \frac{P_{oscillate\ in\ experiment}}{Area} \cdot {sin}^2(2\theta)$
125 // bkg = 5 bins * 100 events / bin
126 RooConstVar bkgNorm("bkgNorm", "normalization for background", 500);
127
128 // flat background (0th order polynomial, so no arguments for coefficients)
129 RooPolynomial bkgEShape("bkgEShape", "flat bkg shape", E);
130
131 // total model
133
134 // for debugging, check model tree
135 // model.printCompactTree();
136 // model.graphVizTree("model.dot");
137
138 // turn off some messages
139 RooMsgService::instance().setStreamStatus(0, kFALSE);
140 RooMsgService::instance().setStreamStatus(1, kFALSE);
141 RooMsgService::instance().setStreamStatus(2, kFALSE);
142
143 // --------------------------------------
144 // n events in data to data, simply sum of sig+bkg
145 Int_t nEventsData = bkgNorm.getVal() + sigNorm.getVal();
146 cout << "generate toy data with nEvents = " << nEventsData << endl;
147 // adjust random seed to get a toy dataset similar to one in paper.
148 // Found by trial and error (3 trials, so not very "fine tuned")
149 RooRandom::randomGenerator()->SetSeed(3);
150 // create a toy dataset
151 RooDataSet *data = model.generate(RooArgSet(E), nEventsData);
152
153 // --------------------------------------
154 // make some plots
155 TCanvas *dataCanvas = new TCanvas("dataCanvas");
156 dataCanvas->Divide(2, 2);
157
158 // plot the PDF
159 dataCanvas->cd(1);
160 TH1 *hh = PnmuTone.createHistogram("hh", E, Binning(40), YVar(L, Binning(40)), Scaling(kFALSE));
161 hh->SetLineColor(kBlue);
162 hh->SetTitle("True Signal Model");
163 hh->Draw("surf");
164
165 // plot the data with the best fit
166 dataCanvas->cd(2);
167 RooPlot *Eframe = E.frame();
168 data->plotOn(Eframe);
169 model.fitTo(*data, Extended());
170 model.plotOn(Eframe);
171 model.plotOn(Eframe, Components(*sigModel), LineColor(kRed));
172 model.plotOn(Eframe, Components(bkgEShape), LineColor(kGreen));
173 model.plotOn(Eframe);
174 Eframe->SetTitle("toy data with best fit model (and sig+bkg components)");
175 Eframe->Draw();
176
177 // plot the likelihood function
178 dataCanvas->cd(3);
179 std::unique_ptr<RooAbsReal> nll{model.createNLL(*data, Extended(true))};
180 RooProfileLL pll("pll", "", *nll, RooArgSet(deltaMSq, sinSq2theta));
181 // TH1* hhh = nll.createHistogram("hhh",sinSq2theta,Binning(40),YVar(deltaMSq,Binning(40))) ;
182 TH1 *hhh = pll.createHistogram("hhh", sinSq2theta, Binning(40), YVar(deltaMSq, Binning(40)), Scaling(kFALSE));
183 hhh->SetLineColor(kBlue);
184 hhh->SetTitle("Likelihood Function");
185 hhh->Draw("surf");
186
187 dataCanvas->Update();
188
189 // --------------------------------------------------------------
190 // show use of Feldman-Cousins utility in RooStats
191 // set the distribution creator, which encodes the test statistic
192 RooArgSet parameters(deltaMSq, sinSq2theta);
193 RooWorkspace *w = new RooWorkspace();
194
196 modelConfig.SetWorkspace(*w);
197 modelConfig.SetPdf(model);
198 modelConfig.SetParametersOfInterest(parameters);
199
201 fc.SetTestSize(.1); // set size of test
202 fc.UseAdaptiveSampling(true);
203 fc.SetNBins(10); // number of points to test per parameter
204
205 // use the Feldman-Cousins tool
208 interval = fc.GetInterval();
209
210 // ---------------------------------------------------------
211 // show use of ProfileLikeihoodCalculator utility in RooStats
213 plc.SetTestSize(.1);
214
215 ConfInterval *plcInterval = plc.GetInterval();
216
217 // --------------------------------------------
218 // show use of MCMCCalculator utility in RooStats
220
221 if (doMCMC) {
222 // turn some messages back on
223 RooMsgService::instance().setStreamStatus(0, kTRUE);
224 RooMsgService::instance().setStreamStatus(1, kTRUE);
225
227 mcmcWatch.Start();
228
231 mc.SetNumIters(5000);
232 mc.SetNumBurnInSteps(100);
233 mc.SetUseKeys(true);
234 mc.SetTestSize(.1);
235 mc.SetAxes(axisList); // set which is x and y axis in posterior histogram
236 // mc.SetNumBins(50);
237 mcInt = (MCMCInterval *)mc.GetInterval();
238
239 mcmcWatch.Stop();
240 mcmcWatch.Print();
241 }
242 // -------------------------------
243 // make plot of resulting interval
244
245 dataCanvas->cd(4);
246
247 // first plot a small dot for every point tested
248 if (doFeldmanCousins) {
249 RooDataHist *parameterScan = (RooDataHist *)fc.GetPointsToScan();
250 TH2F *hist = parameterScan->createHistogram(deltaMSq,sinSq2theta, 30, 30);
251 // hist->Draw();
252 TH2F *forContour = (TH2F *)hist->Clone();
253
254 // now loop through the points and put a marker if it's in the interval
256 // loop over points to test
257 for (Int_t i = 0; i < parameterScan->numEntries(); ++i) {
258 // get a parameter point from the list of points to test.
259 tmpPoint = (RooArgSet *)parameterScan->get(i)->clone("temp");
260
261 if (interval) {
262 if (interval->IsInInterval(*tmpPoint)) {
263 forContour->SetBinContent(
264 hist->FindBin(tmpPoint->getRealValue("sinSq2theta"), tmpPoint->getRealValue("deltaMSq")), 1);
265 } else {
266 forContour->SetBinContent(
267 hist->FindBin(tmpPoint->getRealValue("sinSq2theta"), tmpPoint->getRealValue("deltaMSq")), 0);
268 }
269 }
270
271 delete tmpPoint;
272 }
273
274 if (interval) {
275 Double_t level = 0.5;
276 forContour->SetContour(1, &level);
277 forContour->SetLineWidth(2);
278 forContour->SetLineColor(kRed);
279 forContour->Draw("cont2,same");
280 }
281 }
282
284 if (mcInt) {
285 cout << "MCMC actual confidence level: " << mcInt->GetActualConfidenceLevel() << endl;
287 mcPlot->SetLineColor(kMagenta);
288 mcPlot->Draw();
289 }
290 dataCanvas->Update();
291
293 plotInt.SetTitle("90% Confidence Intervals");
294 if (mcInt)
295 plotInt.Draw("same");
296 else
297 plotInt.Draw();
298 dataCanvas->Update();
299
300 /// print timing info
301 t.Stop();
302 t.Print();
303}
int Int_t
Definition RtypesCore.h:45
constexpr Bool_t kFALSE
Definition RtypesCore.h:101
double Double_t
Definition RtypesCore.h:59
constexpr Bool_t kTRUE
Definition RtypesCore.h:100
@ kRed
Definition Rtypes.h:66
@ kGreen
Definition Rtypes.h:66
@ kMagenta
Definition Rtypes.h:66
@ kBlue
Definition Rtypes.h:66
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:40
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:59
Efficient implementation of a sum of PDFs of the form.
Definition RooAddPdf.h:33
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:55
Represents a constant real-valued object.
Definition RooConstVar.h:23
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
Container class to hold unbinned data.
Definition RooDataSet.h:57
Implementation of a probability density function that takes a RooArgList of servers and a C++ express...
static RooMsgService & instance()
Return reference to singleton instance.
Plot frame and a container for graphics objects within that frame.
Definition RooPlot.h:45
RooPolynomial implements a polynomial p.d.f of the form.
Represents the product of a given set of RooAbsReal objects.
Definition RooProduct.h:29
Implements the profile likelihood estimator for a given likelihood and set of parameters of interest.
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
ConfInterval is an interface class for a generic interval in the RooStats framework.
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.
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.
MCMCInterval is a concrete implementation of the RooStats::ConfInterval interface.
ModelConfig is a simple class that holds configuration information specifying how a model should be u...
Definition ModelConfig.h:35
The ProfileLikelihoodCalculator is a concrete implementation of CombinedCalculator (the interface cla...
Persistable container for RooFit projects.
The Canvas class.
Definition TCanvas.h:23
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:59
virtual Int_t FindBin(Double_t x, Double_t y=0, Double_t z=0)
Return Global bin number corresponding to x,y,z.
Definition TH1.cxx:3672
TObject * Clone(const char *newname="") const override
Make a complete copy of the underlying object.
Definition TH1.cxx:2752
2-D histogram with a float per channel (see TH1 documentation)
Definition TH2.h:307
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.
RooCmdArg YVar(const RooAbsRealLValue &var, const RooCmdArg &arg={})
RooCmdArg Scaling(bool flag)
RooCmdArg Components(Args_t &&... argsOrArgSet)
RooCmdArg Binning(const RooAbsBinning &binning)
RooCmdArg LineColor(Color_t color)
RooArgList L(Args_t &&... args)
Definition RooArgList.h:156
double nll(double pdf, double weight, int binnedL, int doBinOffset)
Definition MathFuncs.h:353
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition JSONIO.h:26
Namespace for the RooStats classes.
Definition Asimov.h:19
constexpr Double_t E()
Base of natural log: .
Definition TMath.h:93