Logo ROOT  
Reference Guide
rf203_ranges.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_roofit
3## \notebook
4##
5## Addition and convolution: fitting and plotting in sub ranges
6##
7## \macro_code
8##
9## \date February 2018
10## \authors Clemens Lange, Wouter Verkerke (C++ version)
11
12from __future__ import print_function
13import ROOT
14
15# Set up model
16# ---------------------
17
18# Construct observables x
19x = ROOT.RooRealVar("x", "x", -10, 10)
20
21# Construct gaussx(x,mx,1)
22mx = ROOT.RooRealVar("mx", "mx", 0, -10, 10)
23gx = ROOT.RooGaussian("gx", "gx", x, mx, ROOT.RooFit.RooConst(1))
24
25# px = 1 (flat in x)
26px = ROOT.RooPolynomial("px", "px", x)
27
28# model = f*gx + (1-f)px
29f = ROOT.RooRealVar("f", "f", 0., 1.)
30model = ROOT.RooAddPdf(
31 "model", "model", ROOT.RooArgList(gx, px), ROOT.RooArgList(f))
32
33# Generated 10000 events in (x,y) from p.d.f. model
34modelData = model.generate(ROOT.RooArgSet(x), 10000)
35
36# Fit full range
37# ---------------------------
38
39# Fit p.d.f to all data
40r_full = model.fitTo(modelData, ROOT.RooFit.Save(ROOT.kTRUE))
41
42# Fit partial range
43# ----------------------------------
44
45# Define "signal" range in x as [-3,3]
46x.setRange("signal", -3, 3)
47
48# Fit p.d.f only to data in "signal" range
49r_sig = model.fitTo(modelData, ROOT.RooFit.Save(
50 ROOT.kTRUE), ROOT.RooFit.Range("signal"))
51
52# Plot/print results
53# ---------------------------------------
54
55# Make plot frame in x and add data and fitted model
56frame = x.frame(ROOT.RooFit.Title("Fitting a sub range"))
57modelData.plotOn(frame)
58model.plotOn(
59 frame, ROOT.RooFit.Range("Full"), ROOT.RooFit.LineStyle(
60 ROOT.kDashed), ROOT.RooFit.LineColor(
61 ROOT.kRed)) # Add shape in full ranged dashed
62model.plotOn(frame) # By default only fitted range is shown
63
64# Print fit results
65print("result of fit on all data ")
66r_full.Print()
67print("result of fit in in signal region (note increased error on signal fraction)")
68r_sig.Print()
69
70# Draw frame on canvas
71c = ROOT.TCanvas("rf203_ranges", "rf203_ranges", 600, 600)
72ROOT.gPad.SetLeftMargin(0.15)
73frame.GetYaxis().SetTitleOffset(1.4)
74frame.Draw()
75
76c.SaveAs("rf203_ranges.png")