Likelihood and minimization: fitting with constraints

**Author:** Clemens Lange, Wouter Verkerke (C++ version)

*This notebook tutorial was automatically generated with ROOTBOOK-izer from the macro found in the ROOT repository on Monday, January 17, 2022 at 10:08 AM.*

In [ ]:

```
from __future__ import print_function
import ROOT
```

Construct a Gaussian pdf

In [ ]:

```
x = ROOT.RooRealVar("x", "x", -10, 10)
m = ROOT.RooRealVar("m", "m", 0, -10, 10)
s = ROOT.RooRealVar("s", "s", 2, 0.1, 10)
gauss = ROOT.RooGaussian("gauss", "gauss(x,m,s)", x, m, s)
```

Construct a flat pdf (polynomial of 0th order)

In [ ]:

```
poly = ROOT.RooPolynomial("poly", "poly(x)", x)
```

model = f*gauss + (1-f)*poly

In [ ]:

```
f = ROOT.RooRealVar("f", "f", 0.5, 0.0, 1.0)
model = ROOT.RooAddPdf("model", "model", [gauss, poly], [f])
```

Generate small dataset for use in fitting below

In [ ]:

```
d = model.generate({x}, 50)
```

Construct Gaussian constraint pdf on parameter f at 0.8 with resolution of 0.1

In [ ]:

```
fconstraint = ROOT.RooGaussian("fconstraint", "fconstraint", f, ROOT.RooFit.RooConst(0.8), ROOT.RooFit.RooConst(0.1))
```

Multiply constraint term with regular pdf using ROOT.RooProdPdf Specify in fitTo() that internal constraints on parameter f should be used

Multiply constraint with pdf

In [ ]:

```
modelc = ROOT.RooProdPdf("modelc", "model with constraint", [model, fconstraint])
```

Fit model (without use of constraint term)

In [ ]:

```
r1 = model.fitTo(d, Save=True)
```

Fit modelc with constraint term on parameter f

In [ ]:

```
r2 = modelc.fitTo(d, Constrain={f}, Save=True)
```

Construct another Gaussian constraint pdf on parameter f at 0.8 with resolution of 0.1

In [ ]:

```
fconstext = ROOT.RooGaussian("fconstext", "fconstext", f, ROOT.RooFit.RooConst(0.2), ROOT.RooFit.RooConst(0.1))
```

Fit with external constraint

In [ ]:

```
r3 = model.fitTo(d, ExternalConstraints={fconstext}, Save=True)
```

Print the fit results

In [ ]:

```
print("fit result without constraint (data generated at f=0.5)")
r1.Print("v")
print("fit result with internal constraint (data generated at f=0.5, is f=0.8+/-0.2)")
r2.Print("v")
print("fit result with (another) external constraint (data generated at f=0.5, is f=0.2+/-0.1)")
r3.Print("v")
```