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 
12 from __future__ import print_function
13 import ROOT
14 
15 # Set up model
16 # ---------------------
17 
18 # Construct observables x
19 x = ROOT.RooRealVar("x", "x", -10, 10)
20 
21 # Construct gaussx(x,mx,1)
22 mx = ROOT.RooRealVar("mx", "mx", 0, -10, 10)
23 gx = ROOT.RooGaussian("gx", "gx", x, mx, ROOT.RooFit.RooConst(1))
24 
25 # px = 1 (flat in x)
26 px = ROOT.RooPolynomial("px", "px", x)
27 
28 # model = f*gx + (1-f)px
29 f = ROOT.RooRealVar("f", "f", 0., 1.)
30 model = 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
34 modelData = model.generate(ROOT.RooArgSet(x), 10000)
35 
36 # Fit full range
37 # ---------------------------
38 
39 # Fit p.d.f to all data
40 r_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]
46 x.setRange("signal", -3, 3)
47 
48 # Fit p.d.f only to data in "signal" range
49 r_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
56 frame = x.frame(ROOT.RooFit.Title("Fitting a sub range"))
57 modelData.plotOn(frame)
58 model.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
62 model.plotOn(frame) # By default only fitted range is shown
63 
64 # Print fit results
65 print("result of fit on all data ")
66 r_full.Print()
67 print("result of fit in in signal region (note increased error on signal fraction)")
68 r_sig.Print()
69 
70 # Draw frame on canvas
71 c = ROOT.TCanvas("rf203_ranges", "rf203_ranges", 600, 600)
72 ROOT.gPad.SetLeftMargin(0.15)
73 frame.GetYaxis().SetTitleOffset(1.4)
74 frame.Draw()
75 
76 c.SaveAs("rf203_ranges.png")