Logo ROOT  
Reference Guide
 
Loading...
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_image
8## \macro_code
9## \macro_output
10##
11## \date February 2018
12## \authors Clemens Lange, Wouter Verkerke (C++ version)
13
14import ROOT
15import math
16
17
18# Create dataset with X and Y values
19# -------------------------------------------------------------------
20
21# Make weighted XY dataset with asymmetric errors stored
22# The StoreError() argument is essential as it makes
23# the dataset store the error in addition to the values
24# of the observables. If errors on one or more observables
25# are asymmetric, can store the asymmetric error
26# using the StoreAsymError() argument
27
28x = ROOT.RooRealVar("x", "x", -11, 11)
29y = ROOT.RooRealVar("y", "y", -10, 200)
30dxy = ROOT.RooDataSet("dxy", "dxy", {x, y}, StoreError={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.0) if (i < 5) else (1.0 / 1.0))
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({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)
49c = ROOT.RooRealVar("c", "c", 0.0, -100, 100)
50f = ROOT.RooPolyVar("f", "f", x, [b, a, c])
51
52# Plot dataset in X-Y interpretation
53frame = x.frame(Title="Chi^2 fit of function set of (X#pmdX,Y#pmdY) values")
54dxy.plotOnXY(frame, YVar=y)
55
56# Fit chi^2 using X and Y errors
57fit1 = f.chi2FitTo(dxy, YVar=y, Save=True, PrintLevel=-1)
58fit1.Print()
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
65fit2 = f.chi2FitTo(dxy, YVar=y, Save=True, PrintLevel=-1, Integrate=True)
66fit2.Print()
67
68# Overlay alternate fit result
69f.plotOn(frame, LineStyle="--", LineColor="r")
70
71# Draw the plot on a canvas
72c = ROOT.TCanvas("rf609_xychi2fit", "rf609_xychi2fit", 600, 600)
73ROOT.gPad.SetLeftMargin(0.15)
74frame.GetYaxis().SetTitleOffset(1.4)
75frame.Draw()
76
77c.SaveAs("rf609_xychi2fit.png")