Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
rf609_xychi2fit.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_roofit
3 /// \notebook -js
4 /// Likelihood and minimization: setting up a chi^2 fit to an unbinned dataset with X,Y,err(Y) values (and optionally
5 /// err(X) values)
6 ///
7 /// \macro_image
8 /// \macro_output
9 /// \macro_code
10 /// \author 07/2008 - Wouter Verkerke
11 
12 #include "RooRealVar.h"
13 #include "RooDataSet.h"
14 #include "RooPolyVar.h"
15 #include "RooConstVar.h"
16 #include "RooChi2Var.h"
17 #include "TCanvas.h"
18 #include "TAxis.h"
19 #include "RooPlot.h"
20 #include "TRandom.h"
21 
22 using namespace RooFit;
23 
24 void rf609_xychi2fit()
25 {
26  // C r e a t e d a t a s e t w i t h X a n d Y v a l u e s
27  // -------------------------------------------------------------------
28 
29  // Make weighted XY dataset with asymmetric errors stored
30  // The StoreError() argument is essential as it makes
31  // the dataset store the error in addition to the values
32  // of the observables. If errors on one or more observables
33  // are asymmetric, one can store the asymmetric error
34  // using the StoreAsymError() argument
35 
36  RooRealVar x("x", "x", -11, 11);
37  RooRealVar y("y", "y", -10, 200);
38  RooDataSet dxy("dxy", "dxy", RooArgSet(x, y), StoreError(RooArgSet(x, y)));
39 
40  // Fill an example dataset with X,err(X),Y,err(Y) values
41  for (int i = 0; i <= 10; i++) {
42 
43  // Set X value and error
44  x = -10 + 2 * i;
45  x.setError(i < 5 ? 0.5 / 1. : 1.0 / 1.);
46 
47  // Set Y value and error
48  y = x.getVal() * x.getVal() + 4 * fabs(gRandom->Gaus());
49  y.setError(sqrt(y.getVal()));
50 
51  dxy.add(RooArgSet(x, y));
52  }
53 
54  // P e r f o r m c h i 2 f i t t o X + / - d x a n d Y + / - d Y v a l u e s
55  // ---------------------------------------------------------------------------------------
56 
57  // Make fit function
58  RooRealVar a("a", "a", 0.0, -10, 10);
59  RooRealVar b("b", "b", 0.0, -100, 100);
60  RooPolyVar f("f", "f", x, RooArgList(b, a, RooConst(1)));
61 
62  // Plot dataset in X-Y interpretation
63  RooPlot *frame = x.frame(Title("Chi^2 fit of function set of (X#pmdX,Y#pmdY) values"));
64  dxy.plotOnXY(frame, YVar(y));
65 
66  // Fit chi^2 using X and Y errors
67  f.chi2FitTo(dxy, YVar(y));
68 
69  // Overlay fitted function
70  f.plotOn(frame);
71 
72  // Alternative: fit chi^2 integrating f(x) over ranges defined by X errors, rather
73  // than taking point at center of bin
74  f.chi2FitTo(dxy, YVar(y), Integrate(kTRUE));
75 
76  // Overlay alternate fit result
77  f.plotOn(frame, LineStyle(kDashed), LineColor(kRed));
78 
79  // Draw the plot on a canvas
80  new TCanvas("rf609_xychi2fit", "rf609_xychi2fit", 600, 600);
81  gPad->SetLeftMargin(0.15);
82  frame->GetYaxis()->SetTitleOffset(1.4);
83  frame->Draw();
84 }