Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
rf609_xychi2fit.py
Go to the documentation of this file.
1 ## \file
2 ## \ingroup tutorial_roofit
3 ## \notebook
4 ##
5 ## Likelihood and minimization: setting up a chi^2 fit to an unbinned dataset with X,Y,err(Y) values (and optionally err(X) values)
6 ##
7 ## \macro_code
8 ##
9 ## \date February 2018
10 ## \author Clemens Lange, Wouter Verkerke (C++ version)
11 
12 import ROOT
13 import math
14 
15 
16 # Create dataset with X and Y values
17 # -------------------------------------------------------------------
18 
19 # Make weighted XY dataset with asymmetric errors stored
20 # The StoreError() argument is essential as it makes
21 # the dataset store the error in addition to the values
22 # of the observables. If errors on one or more observables
23 # are asymmetric, can store the asymmetric error
24 # using the StoreAsymError() argument
25 
26 x = ROOT.RooRealVar("x", "x", -11, 11)
27 y = ROOT.RooRealVar("y", "y", -10, 200)
28 dxy = ROOT.RooDataSet("dxy", "dxy", ROOT.RooArgSet(
29  x, y), ROOT.RooFit.StoreError(ROOT.RooArgSet(x, y)))
30 
31 # Fill an example dataset with X,err(X),Y,err(Y) values
32 for i in range(10):
33  x.setVal(-10 + 2 * i)
34  x.setError((0.5 / 1.) if (i < 5) else (1.0 / 1.))
35 
36  # Set Y value and error
37  y.setVal(x.getVal() * x.getVal() + 4 * abs(ROOT.gRandom.Gaus()))
38  y.setError(math.sqrt(y.getVal()))
39 
40  dxy.add(ROOT.RooArgSet(x, y))
41 
42 # Perform chi2 fit to X +/- dX and Y +/- dY values
43 # ---------------------------------------------------------------------------------------
44 
45 # Make fit function
46 a = ROOT.RooRealVar("a", "a", 0.0, -10, 10)
47 b = ROOT.RooRealVar("b", "b", 0.0, -100, 100)
48 f = ROOT.RooPolyVar(
49  "f", "f", x, ROOT.RooArgList(
50  b, a, ROOT.RooFit.RooConst(1)))
51 
52 # Plot dataset in X-Y interpretation
53 frame = x.frame(ROOT.RooFit.Title(
54  "Chi^2 fit of function set of (X#pmdX,Y#pmdY) values"))
55 dxy.plotOnXY(frame, ROOT.RooFit.YVar(y))
56 
57 # Fit chi^2 using X and Y errors
58 f.chi2FitTo(dxy, ROOT.RooFit.YVar(y))
59 
60 # Overlay fitted function
61 f.plotOn(frame)
62 
63 # Alternative: fit chi^2 integrating f(x) over ranges defined by X errors, rather
64 # than taking point at center of bin
65 f.chi2FitTo(dxy, ROOT.RooFit.YVar(y), ROOT.RooFit.Integrate(ROOT.kTRUE))
66 
67 # Overlay alternate fit result
68 f.plotOn(frame, ROOT.RooFit.LineStyle(ROOT.kDashed),
69  ROOT.RooFit.LineColor(ROOT.kRed))
70 
71 # Draw the plot on a canvas
72 c = ROOT.TCanvas("rf609_xychi2fit", "rf609_xychi2fit", 600, 600)
73 ROOT.gPad.SetLeftMargin(0.15)
74 frame.GetYaxis().SetTitleOffset(1.4)
75 frame.Draw()
76 
77 c.SaveAs("rf609_xychi2fit.png")