Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
rf102_dataimport.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_roofit
3/// \notebook -js
4/// Basic functionality: importing data from ROOT TTrees and THx histograms.
5///
6/// \macro_image
7/// \macro_code
8/// \macro_output
9///
10/// \date July 2008
11/// \author Wouter Verkerke
12
13#include "RooRealVar.h"
14#include "RooDataSet.h"
15#include "RooDataHist.h"
16#include "RooGaussian.h"
17#include "TCanvas.h"
18#include "RooPlot.h"
19#include "TTree.h"
20#include "TH1D.h"
21#include "TRandom.h"
22
23TH1 *makeTH1(TRandom &trnd);
24TTree *makeTTree(TRandom &trnd);
25
27{
28 using namespace RooFit;
29
30 // ---------------------------------------------------
31 // I m p o r t i n g R O O T h i s t o g r a m s
32 // ===================================================
33
34 TRandom3 trnd{};
35
36 // I m p o r t T H 1 i n t o a R o o D a t a H i s t
37 // ---------------------------------------------------------
38
39 // Create a ROOT TH1 histogram
40 TH1 *hh = makeTH1(trnd);
41
42 // Declare observable x
43 RooRealVar x("x", "x", -10, 10);
44
45 // Create a binned dataset that imports contents of TH1 and associates its contents to observable 'x'
46 RooDataHist dh("dh", "dh", x, Import(*hh));
47
48 // P l o t a n d f i t a R o o D a t a H i s t
49 // ---------------------------------------------------
50
51 // Make plot of binned dataset showing Poisson error bars (RooFit default)
52 RooPlot *frame = x.frame(Title("Imported TH1 with Poisson error bars"));
53 dh.plotOn(frame);
54
55 // Fit a Gaussian pdf to the data
56 RooRealVar mean("mean", "mean", 0, -10, 10);
57 RooRealVar sigma("sigma", "sigma", 3, 0.1, 10);
58 RooGaussian gauss("gauss", "gauss", x, mean, sigma);
59 gauss.fitTo(dh, PrintLevel(-1));
60 gauss.plotOn(frame);
61
62 // P l o t a n d f i t a R o o D a t a H i s t w i t h i n t e r n a l e r r o r s
63 // ---------------------------------------------------------------------------------------------
64
65 // If histogram has custom error (i.e. its contents is does not originate from a Poisson process
66 // but e.g. is a sum of weighted events) you can data with symmetric 'sum-of-weights' error instead
67 // (same error bars as shown by ROOT)
68 RooPlot *frame2 = x.frame(Title("Imported TH1 with internal errors"));
69 dh.plotOn(frame2, DataError(RooAbsData::SumW2));
70 gauss.plotOn(frame2);
71
72 // Please note that error bars shown (Poisson or SumW2) are for visualization only, the are NOT used
73 // in a maximum likelihood fit
74 //
75 // A (binned) ML fit will ALWAYS assume the Poisson error interpretation of data (the mathematical definition
76 // of likelihood does not take any external definition of errors). Data with non-unit weights can only be correctly
77 // fitted with a chi^2 fit (see rf602_chi2fit.C)
78
79 // -----------------------------------------
80 // I m p o r t i n g R O O T T T r e e s
81 // =========================================
82
83 // I m p o r t T T r e e i n t o a R o o D a t a S e t
84 // -----------------------------------------------------------
85
86 TTree *tree = makeTTree(trnd);
87
88 // Define 2nd observable y
89 RooRealVar y("y", "y", -10, 10);
90
91 // Construct unbinned dataset importing tree branches x and y matching between branches and RooRealVars
92 // is done by name of the branch/RRV
93 //
94 // Note that ONLY entries for which x,y have values within their allowed ranges as defined in
95 // RooRealVar x and y are imported. Since the y values in the import tree are in the range [-15,15]
96 // and RRV y defines a range [-10,10] this means that the RooDataSet below will have less entries than the TTree
97 // 'tree'
98
99 RooDataSet ds("ds", "ds", RooArgSet(x, y), Import(*tree));
100
101 // U s e a s c i i i m p o r t / e x p o r t f o r d a t a s e t s
102 // ------------------------------------------------------------------------------------
103 {
104 // Write data to output stream
105 std::ofstream outstream("rf102_testData.txt");
106 // Optionally, adjust the stream here (e.g. std::setprecision)
107 ds.write(outstream);
108 outstream.close();
109 }
110
111 // Read data from input stream. The variables of the dataset need to be supplied
112 // to the RooDataSet::read() function.
113 std::cout << "\n-----------------------\nReading data from ASCII\n";
114 RooDataSet *dataReadBack =
115 RooDataSet::read("rf102_testData.txt",
116 RooArgList(x, y), // variables to be read. If the file has more fields, these are ignored.
117 "D"); // Prints if a RooFit message stream listens for debug messages. Use Q for quiet.
118
119 dataReadBack->Print("V");
120
121 std::cout << "\nOriginal data, line 20:\n";
122 ds.get(20)->Print("V");
123
124 std::cout << "\nRead-back data, line 20:\n";
125 dataReadBack->get(20)->Print("V");
126
127 // P l o t d a t a s e t s w i t h m u l t i p l e b i n n i n g c h o i c e s
128 // ------------------------------------------------------------------------------------
129
130 // Print number of events in dataset
131 ds.Print();
132
133 // Print unbinned dataset with default frame binning (100 bins)
134 RooPlot *frame3 = y.frame(Title("Unbinned data shown in default frame binning"));
135 ds.plotOn(frame3);
136
137 // Print unbinned dataset with custom binning choice (20 bins)
138 RooPlot *frame4 = y.frame(Title("Unbinned data shown with custom binning"));
139 ds.plotOn(frame4, Binning(20));
140
141 RooPlot *frame5 = y.frame(Title("Unbinned data read back from ASCII file"));
142 ds.plotOn(frame5, Binning(20));
143 dataReadBack->plotOn(frame5, Binning(20), MarkerColor(kRed), MarkerStyle(5));
144
145 // Draw all frames on a canvas
146 TCanvas *c = new TCanvas("rf102_dataimport", "rf102_dataimport", 1000, 800);
147 c->Divide(3, 2);
148 c->cd(1);
149 gPad->SetLeftMargin(0.15);
150 frame->GetYaxis()->SetTitleOffset(1.4);
151 frame->Draw();
152 c->cd(2);
153 gPad->SetLeftMargin(0.15);
154 frame2->GetYaxis()->SetTitleOffset(1.4);
155 frame2->Draw();
156
157 c->cd(4);
158 gPad->SetLeftMargin(0.15);
159 frame3->GetYaxis()->SetTitleOffset(1.4);
160 frame3->Draw();
161 c->cd(5);
162 gPad->SetLeftMargin(0.15);
163 frame4->GetYaxis()->SetTitleOffset(1.4);
164 frame4->Draw();
165 c->cd(6);
166 gPad->SetLeftMargin(0.15);
167 frame4->GetYaxis()->SetTitleOffset(1.4);
168 frame5->Draw();
169}
170
171// Create ROOT TH1 filled with a Gaussian distribution
172TH1 *makeTH1(TRandom &trnd)
173{
174 TH1D *hh = new TH1D("hh", "hh", 25, -10, 10);
175 for (int i = 0; i < 100; i++) {
176 hh->Fill(trnd.Gaus(0, 3));
177 }
178 return hh;
179}
180
181// Create ROOT TTree filled with a Gaussian distribution in x and a uniform distribution in y
182TTree *makeTTree(TRandom &trnd)
183{
184 TTree *tree = new TTree("tree", "tree");
185 double *px = new double;
186 double *py = new double;
187 tree->Branch("x", px, "x/D");
188 tree->Branch("y", py, "y/D");
189 for (int i = 0; i < 100; i++) {
190 *px = trnd.Gaus(0, 3);
191 *py = trnd.Uniform() * 30 - 15;
192 tree->Fill();
193 }
194 return tree;
195}
#define c(i)
Definition RSha256.hxx:101
@ kRed
Definition Rtypes.h:66
#define gPad
void Print(Option_t *options=nullptr) const override
This method must be overridden when a class wants to print itself.
void Print(Option_t *options=nullptr) const override
This method must be overridden when a class wants to print itself.
Definition RooAbsData.h:227
virtual RooPlot * plotOn(RooPlot *frame, const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={}) const
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:24
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
Container class to hold unbinned data.
Definition RooDataSet.h:34
const RooArgSet * get(Int_t index) const override
Return RooArgSet with coordinates of event 'index'.
static RooDataSet * read(const char *filename, const RooArgList &variables, const char *opts="", const char *commonPath="", const char *indexCatName=nullptr)
Read data from a text file and create a dataset from it.
Plain Gaussian p.d.f.
Definition RooGaussian.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
TAxis * GetYaxis() const
Definition RooPlot.cxx:1224
void Draw(Option_t *options=nullptr) override
Draw this plot and all of the elements it contains.
Definition RooPlot.cxx:597
Variable that can be changed from the outside.
Definition RooRealVar.h:37
virtual void SetTitleOffset(Float_t offset=1)
Set distance between the axis and the axis title.
Definition TAttAxis.cxx:298
The Canvas class.
Definition TCanvas.h:23
1-D histogram with a double per channel (see TH1 documentation)
Definition TH1.h:671
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:59
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition TH1.cxx:3346
Random number generator class based on M.
Definition TRandom3.h:27
This is the base class for the ROOT Random number generators.
Definition TRandom.h:27
virtual Double_t Gaus(Double_t mean=0, Double_t sigma=1)
Samples a random number from the standard Normal (Gaussian) Distribution with the given mean and sigm...
Definition TRandom.cxx:275
virtual Double_t Uniform(Double_t x1=1)
Returns a uniform deviate on the interval (0, x1).
Definition TRandom.cxx:682
A TTree represents a columnar dataset.
Definition TTree.h:79
RooCmdArg Import(const char *state, TH1 &histo)
RooCmdArg PrintLevel(Int_t code)
RooCmdArg DataError(Int_t)
RooCmdArg MarkerColor(Color_t color)
RooCmdArg Binning(const RooAbsBinning &binning)
RooCmdArg MarkerStyle(Style_t style)
const Double_t sigma
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:64
const char * Title
Definition TXMLSetup.cxx:68