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