Logo ROOT   6.16/01
Reference Guide
rf604_constraints.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_roofit
3## \notebook -nodraw
4##
5## 'LIKELIHOOD AND MINIMIZATION' RooFit tutorial macro #604
6##
7## Fitting with constraints
8##
9## \macro_code
10##
11## \date February 2018
12## \author Clemens Lange
13## \author Wouter Verkerke (C version)
14
15from __future__ import print_function
16import ROOT
17
18
19# Create model and dataset
20# ----------------------------------------------
21
22# Construct a Gaussian p.d.f
23x = ROOT.RooRealVar("x", "x", -10, 10)
24
25m = ROOT.RooRealVar("m", "m", 0, -10, 10)
26s = ROOT.RooRealVar("s", "s", 2, 0.1, 10)
27gauss = ROOT.RooGaussian("gauss", "gauss(x,m,s)", x, m, s)
28
29# Construct a flat p.d.f (polynomial of 0th order)
30poly = ROOT.RooPolynomial("poly", "poly(x)", x)
31
32# model = f*gauss + (1-f)*poly
33f = ROOT.RooRealVar("f", "f", 0.5, 0., 1.)
34model = ROOT.RooAddPdf("model", "model", ROOT.RooArgList(gauss, poly), ROOT.RooArgList(f))
35
36# Generate small dataset for use in fitting below
37d = model.generate(ROOT.RooArgSet(x), 50)
38
39# Create constraint pdf
40# -----------------------------------------
41
42# Construct Gaussian constraint p.d.f on parameter f at 0.8 with
43# resolution of 0.1
44fconstraint = ROOT.RooGaussian(
45 "fconstraint", "fconstraint", f, ROOT.RooFit.RooConst(0.8), ROOT.RooFit.RooConst(0.1))
46
47# Method 1 - add internal constraint to model
48# -------------------------------------------------------------------------------------
49
50# Multiply constraint term with regular p.d.f using ROOT.RooProdPdf
51# Specify in fitTo() that internal constraints on parameter f should be
52# used
53
54# Multiply constraint with p.d.f
55modelc = ROOT.RooProdPdf(
56 "modelc", "model with constraint", ROOT.RooArgList(model, fconstraint))
57
58# Fit model (without use of constraint term)
59r1 = model.fitTo(d, ROOT.RooFit.Save())
60
61# Fit modelc with constraint term on parameter f
62r2 = modelc.fitTo(d, ROOT.RooFit.Constrain(ROOT.RooArgSet(f)), ROOT.RooFit.Save())
63
64# Method 2 - specify external constraint when fitting
65# ------------------------------------------------------------------------------------------
66
67# Construct another Gaussian constraint p.d.f on parameter f at 0.8 with
68# resolution of 0.1
69fconstext = ROOT.RooGaussian("fconstext", "fconstext", f, ROOT.RooFit.RooConst(
70 0.2), ROOT.RooFit.RooConst(0.1))
71
72# Fit with external constraint
73r3 = model.fitTo(d, ROOT.RooFit.ExternalConstraints(
74 ROOT.RooArgSet(fconstext)), ROOT.RooFit.Save())
75
76# Print the fit results
77print("fit result without constraint (data generated at f=0.5)")
78r1.Print("v")
79print("fit result with internal constraint (data generated at f=0.5, is f=0.8+/-0.2)")
80r2.Print("v")
81print("fit result with (another) external constraint (data generated at f=0.5, is f=0.2+/-0.1)")
82r3.Print("v")