ROOT   Reference Guide
Searching...
No Matches
rf609_xychi2fit.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_roofit
3## \notebook
4## Likelihood and minimization: setting up a chi^2 fit to an unbinned dataset with X,Y,err(Y)
5## values (and optionally err(X) values)
6##
7## \macro_code
8##
9## \date February 2018
10## \authors Clemens Lange, Wouter Verkerke (C++ version)
11
12import ROOT
13import 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
26x = ROOT.RooRealVar("x", "x", -11, 11)
27y = ROOT.RooRealVar("y", "y", -10, 200)
28dxy = 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
32for 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
41
42# Perform chi2 fit to X +/- dX and Y +/- dY values
43# ---------------------------------------------------------------------------------------
44
45# Make fit function
46a = ROOT.RooRealVar("a", "a", 0.0, -10, 10)
47b = ROOT.RooRealVar("b", "b", 0.0, -100, 100)
48f = ROOT.RooPolyVar(
49 "f", "f", x, ROOT.RooArgList(
50 b, a, ROOT.RooFit.RooConst(1)))
51
52# Plot dataset in X-Y interpretation
53frame = x.frame(ROOT.RooFit.Title(
54 "Chi^2 fit of function set of (X#pmdX,Y#pmdY) values"))
55dxy.plotOnXY(frame, ROOT.RooFit.YVar(y))
56
57# Fit chi^2 using X and Y errors
58f.chi2FitTo(dxy, ROOT.RooFit.YVar(y))
59
60# Overlay fitted function
61f.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
65f.chi2FitTo(dxy, ROOT.RooFit.YVar(y), ROOT.RooFit.Integrate(ROOT.kTRUE))
66
67# Overlay alternate fit result
68f.plotOn(frame, ROOT.RooFit.LineStyle(ROOT.kDashed),
69 ROOT.RooFit.LineColor(ROOT.kRed))
70
71# Draw the plot on a canvas
72c = ROOT.TCanvas("rf609_xychi2fit", "rf609_xychi2fit", 600, 600)
74frame.GetYaxis().SetTitleOffset(1.4)
75frame.Draw()
76
77c.SaveAs("rf609_xychi2fit.png")