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
17trnd = ROOT.TRandom3()
18
19# Create dataset with X and Y values
20# -------------------------------------------------------------------
21
22# Make weighted XY dataset with asymmetric errors stored
23# The StoreError() argument is essential as it makes
24# the dataset store the error in addition to the values
25# of the observables. If errors on one or more observables
26# are asymmetric, can store the asymmetric error
27# using the StoreAsymError() argument
28
29x = ROOT.RooRealVar("x", "x", -11, 11)
30y = ROOT.RooRealVar("y", "y", -10, 200)
31dxy = ROOT.RooDataSet("dxy", "dxy", {x, y}, StoreError={x, y})
32
33# Fill an example dataset with X,err(X),Y,err(Y) values
34for i in range(10):
35 x.setVal(-10 + 2 * i)
36 x.setError((0.5 / 1.0) if (i < 5) else (1.0 / 1.0))
37
38 # Set Y value and error
39 y.setVal(x.getVal() * x.getVal() + 4 * abs(trnd.Gaus()))
40 y.setError(math.sqrt(y.getVal()))
41
42 dxy.add({x, y})
43
44# Perform chi2 fit to X +/- dX and Y +/- dY values
45# ---------------------------------------------------------------------------------------
46
47# Make fit function
48a = ROOT.RooRealVar("a", "a", 0.0, -10, 10)
49b = ROOT.RooRealVar("b", "b", 0.0, -100, 100)
50c = ROOT.RooRealVar("c", "c", 0.0, -100, 100)
51f = ROOT.RooPolyVar("f", "f", x, [b, a, c])
52
53# Plot dataset in X-Y interpretation
54frame = x.frame(Title="Chi^2 fit of function set of (X#pmdX,Y#pmdY) values")
55dxy.plotOnXY(frame, YVar=y)
56
57# Fit chi^2 using X and Y errors
58fit1 = f.chi2FitTo(dxy, YVar=y, Save=True, PrintLevel=-1)
59fit1.Print()
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
66fit2 = f.chi2FitTo(dxy, YVar=y, Save=True, PrintLevel=-1, Integrate=True)
67fit2.Print()
68
69# Overlay alternate fit result
70f.plotOn(frame, LineStyle="--", LineColor="r")
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")