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