 ROOT   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: fitting with constraints
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
16# Create model and dataset
17# ----------------------------------------------
18
19# Construct a Gaussian p.d.f
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 p.d.f (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., 1.)
32 "model",
33 "model",
34 ROOT.RooArgList(
35 gauss,
36 poly),
37 ROOT.RooArgList(f))
38
39# Generate small dataset for use in fitting below
40d = model.generate(ROOT.RooArgSet(x), 50)
41
42# Create constraint pdf
43# -----------------------------------------
44
45# Construct Gaussian constraint p.d.f on parameter f at 0.8 with
46# resolution of 0.1
47fconstraint = ROOT.RooGaussian(
48 "fconstraint",
49 "fconstraint",
50 f,
51 ROOT.RooFit.RooConst(0.8),
52 ROOT.RooFit.RooConst(0.1))
53
54# Method 1 - add internal constraint to model
55# -------------------------------------------------------------------------------------
56
57# Multiply constraint term with regular p.d.f using ROOT.RooProdPdf
58# Specify in fitTo() that internal constraints on parameter f should be
59# used
60
61# Multiply constraint with p.d.f
62modelc = ROOT.RooProdPdf(
63 "modelc", "model with constraint", ROOT.RooArgList(model, fconstraint))
64
65# Fit model (without use of constraint term)
66r1 = model.fitTo(d, ROOT.RooFit.Save())
67
68# Fit modelc with constraint term on parameter f
69r2 = modelc.fitTo(
70 d,
71 ROOT.RooFit.Constrain(
72 ROOT.RooArgSet(f)),
73 ROOT.RooFit.Save())
74
75# Method 2 - specify external constraint when fitting
76# ------------------------------------------------------------------------------------------
77
78# Construct another Gaussian constraint p.d.f on parameter f at 0.8 with
79# resolution of 0.1
80fconstext = ROOT.RooGaussian("fconstext", "fconstext", f, ROOT.RooFit.RooConst(
81 0.2), ROOT.RooFit.RooConst(0.1))
82
83# Fit with external constraint
84r3 = model.fitTo(d, ROOT.RooFit.ExternalConstraints(
85 ROOT.RooArgSet(fconstext)), ROOT.RooFit.Save())
86
87# Print the fit results
88print("fit result without constraint (data generated at f=0.5)")
89r1.Print("v")
90print("fit result with internal constraint (data generated at f=0.5, is f=0.8+/-0.2)")
91r2.Print("v")
92print("fit result with (another) external constraint (data generated at f=0.5, is f=0.2+/-0.1)")
93r3.Print("v")