 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
11 from __future__ import print_function
12 import ROOT
13
14
15 # Create model and dataset
16 # ----------------------------------------------
17
18 # Construct a Gaussian pdf
19 x = ROOT.RooRealVar("x", "x", -10, 10)
20
21 m = ROOT.RooRealVar("m", "m", 0, -10, 10)
22 s = ROOT.RooRealVar("s", "s", 2, 0.1, 10)
23 gauss = ROOT.RooGaussian("gauss", "gauss(x,m,s)", x, m, s)
24
25 # Construct a flat pdf (polynomial of 0th order)
26 poly = ROOT.RooPolynomial("poly", "poly(x)", x)
27
28 # model = f*gauss + (1-f)*poly
29 f = ROOT.RooRealVar("f", "f", 0.5, 0., 1.)
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
39 d = 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
46 fconstraint = 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
61 modelc = ROOT.RooProdPdf(
62  "modelc", "model with constraint", ROOT.RooArgList(model, fconstraint))
63
64 # Fit model (without use of constraint term)
65 r1 = model.fitTo(d, ROOT.RooFit.Save())
66
67 # Fit modelc with constraint term on parameter f
68 r2 = 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
79 fconstext = ROOT.RooGaussian("fconstext", "fconstext", f, ROOT.RooFit.RooConst(
80  0.2), ROOT.RooFit.RooConst(0.1))
81
82 # Fit with external constraint
83 r3 = model.fitTo(d, ROOT.RooFit.ExternalConstraints(
84  ROOT.RooArgSet(fconstext)), ROOT.RooFit.Save())
85
86 # Print the fit results
87 print("fit result without constraint (data generated at f=0.5)")
88 r1.Print("v")
89 print("fit result with internal constraint (data generated at f=0.5, is f=0.8+/-0.2)")
90 r2.Print("v")
91 print("fit result with (another) external constraint (data generated at f=0.5, is f=0.2+/-0.1)")
92 r3.Print("v")