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
13import ROOT
14import 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
27x = ROOT.RooRealVar("x", "x", -11, 11)
28y = ROOT.RooRealVar("y", "y", -10, 200)
29dxy = 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
33for 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
47a = ROOT.RooRealVar("a", "a", 0.0, -10, 10)
48b = ROOT.RooRealVar("b", "b", 0.0, -100, 100)
49f = ROOT.RooPolyVar(
50 "f", "f", x, ROOT.RooArgList(
51 b, a, ROOT.RooFit.RooConst(1)))
52
53# Plot dataset in X-Y interpretation
54frame = x.frame(ROOT.RooFit.Title(
55 "Chi^2 fit of function set of (X#pmdX,Y#pmdY) values"))
56dxy.plotOnXY(frame, ROOT.RooFit.YVar(y))
57
58# Fit chi^2 using X and Y errors
59f.chi2FitTo(dxy, ROOT.RooFit.YVar(y))
60
61# Overlay fitted function
62f.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
66f.chi2FitTo(dxy, ROOT.RooFit.YVar(y), ROOT.RooFit.Integrate(ROOT.kTRUE))
67
68# Overlay alternate fit result
69f.plotOn(frame, ROOT.RooFit.LineStyle(ROOT.kDashed),
70 ROOT.RooFit.LineColor(ROOT.kRed))
71
72# Draw the plot on a canvas
73c = ROOT.TCanvas("rf609_xychi2fit", "rf609_xychi2fit", 600, 600)
74ROOT.gPad.SetLeftMargin(0.15)
75frame.GetYaxis().SetTitleOffset(1.4)
76frame.Draw()
77
78c.SaveAs("rf609_xychi2fit.png")