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_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", {x, y}, StoreError={x, y})
29
30# Fill an example dataset with X,err(X),Y,err(Y) values
31for i in range(10):
32 x.setVal(-10 + 2 * i)
33 x.setError((0.5 / 1.0) if (i < 5) else (1.0 / 1.0))
34
35 # Set Y value and error
36 y.setVal(x.getVal() * x.getVal() + 4 * abs(ROOT.gRandom.Gaus()))
37 y.setError(math.sqrt(y.getVal()))
38
39 dxy.add({x, y})
40
41# Perform chi2 fit to X +/- dX and Y +/- dY values
42# ---------------------------------------------------------------------------------------
43
44# Make fit function
45a = ROOT.RooRealVar("a", "a", 0.0, -10, 10)
46b = ROOT.RooRealVar("b", "b", 0.0, -100, 100)
47f = ROOT.RooPolyVar("f", "f", x, [b, a, 1.0])
48
49# Plot dataset in X-Y interpretation
50frame = x.frame(Title="Chi^2 fit of function set of (X#pmdX,Y#pmdY) values")
51dxy.plotOnXY(frame, YVar=y)
52
53# Fit chi^2 using X and Y errors
54f.chi2FitTo(dxy, YVar=y)
55
56# Overlay fitted function
57f.plotOn(frame)
58
59# Alternative: fit chi^2 integrating f(x) over ranges defined by X errors, rather
60# than taking point at center of bin
61f.chi2FitTo(dxy, YVar=y, Integrate=True)
62
63# Overlay alternate fit result
64f.plotOn(frame, LineStyle="--", LineColor="r")
65
66# Draw the plot on a canvas
67c = ROOT.TCanvas("rf609_xychi2fit", "rf609_xychi2fit", 600, 600)
68ROOT.gPad.SetLeftMargin(0.15)
69frame.GetYaxis().SetTitleOffset(1.4)
70frame.Draw()
71
72c.SaveAs("rf609_xychi2fit.png")