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