%%bash
root.exe -b -l -q roofit_tutorial_generate_data.C

"""
Explanation: A RooFit Tutorial
This tutorial will teach you the basics of using RooFit.
To start with we have to generate some data for use during the tutorial:
End of explanation
"""


!ls *.root

"""
Explanation: Besides printing a lot of text it also created a dataset for us in:
End of explanation
"""


%%bash
root.exe -b -l -q first_plots.C

from IPython.display import Image
Image(filename='dataplot.png') 

"""
Explanation: The first few bits of code in this tutorial will load the dataset from the
ntuple and plot them in the manner of RooFit. This is to get you started.
The first_plots.C script will load the data and make some basic plots to check everything is fine. We will display the images directly in the notebook here.
End of explanation
"""


!root -l -b -q mass_fits.C

Image(filename='masspdfplot.png') 

"""
Explanation: With these preliminary plots and sanity checks out of the way. Let's get going.
The tutorial is written in such a way that you can run cells one at a time and modify them as you go along. This way the code can be re-run at each step to see what happens. Each of the steps is coded up in its own root macro. You can edit them by going to the overview page of the webinterface. There simply click on the file you want to edit, make your changes and re-run the step here.
Your Mission
Your task is to try and fit to this dataset to extract the signal yield and lifetime.
We'll start with the signal yield, fitting to the mass distribution.
Then we'll try to extract the signal lifetime from the time distribution
Finally, we'll simultaneously fit to both time and mass to see if it
improves the errors.
End of explanation
"""


!root -b -q -l lifetime_fit.C

Image(filename='timepdfplot.png') 

!root -l -b -q combined_fits.C

"""
Explanation: This prints a lot of text output. Can you find the number of signal events from your fit in the output?
Lifetime fit
Now we'll try to fit the lifetime of the signal distribution
RooFit comes with a few pre-built "B-decay specific" PDFs that
include CP violation, resolution modelling, mistag rates, etc.
These are a little too overkill for a basic tutorial, so we'll
concern ourselves with a simple exponential decay model here.
Part of the power of RooFit is the way in which PDFs can be
modified using formulae. The RooExponential PDF is of the form
$f = e^{c\cdot x}$ but we want $f = e^{-\frac{x}{c}}$. We can do this with
a RooFormulaVar
End of explanation
"""


!root -l -b -q toystudies.C

Image('toystudy1.png')

Image('toystudy2.png')

"""
Explanation: Lastly, we do a short toy study based on the result of our fit: What is
the expected sensitivity of our model to the lifetime assuming the
result we measured? In my opinion this is the coolest feature of RooFit:
The models you build can be fit to data, can generate toy data or can
run big toy studies only with a couple of extra lines of code.
End of explanation
"""


