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