Likelihood and minimization: setting up a chi^2 fit to an unbinned dataset with X,Y,err(Y) values (and optionally err(X) values)
import ROOT
import math
x = ROOT.RooRealVar("x", "x", -11, 11)
y = ROOT.RooRealVar("y", "y", -10, 200)
dxy = ROOT.RooDataSet("dxy", "dxy", ROOT.RooArgSet(
x, y), ROOT.RooFit.StoreError(ROOT.RooArgSet(x, y)))
for i in range(10):
x.setVal(-10 + 2 * i)
x.setError((0.5 / 1.) if (i < 5) else (1.0 / 1.))
y.setVal(x.getVal() * x.getVal() + 4 * abs(ROOT.gRandom.Gaus()))
y.setError(math.sqrt(y.getVal()))
dxy.add(ROOT.RooArgSet(x, y))
a = ROOT.RooRealVar("a", "a", 0.0, -10, 10)
b = ROOT.RooRealVar("b", "b", 0.0, -100, 100)
f = ROOT.RooPolyVar(
"f", "f", x, ROOT.RooArgList(
b, a, ROOT.RooFit.RooConst(1)))
frame = x.frame(ROOT.RooFit.Title(
"Chi^2 fit of function set of (X#pmdX,Y#pmdY) values"))
dxy.plotOnXY(frame, ROOT.RooFit.YVar(y))
f.chi2FitTo(dxy, ROOT.RooFit.YVar(y))
f.plotOn(frame)
f.chi2FitTo(dxy, ROOT.RooFit.YVar(y), ROOT.RooFit.Integrate(ROOT.kTRUE))
f.plotOn(frame, ROOT.RooFit.LineStyle(ROOT.kDashed),
ROOT.RooFit.LineColor(ROOT.kRed))
c = ROOT.TCanvas("rf609_xychi2fit", "rf609_xychi2fit", 600, 600)
ROOT.gPad.SetLeftMargin(0.15)
frame.GetYaxis().SetTitleOffset(1.4)
frame.Draw()
c.SaveAs("rf609_xychi2fit.png")