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