{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " Exercise 5: Fit Signal and background distribution of a histogramm "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "ImportError",
     "evalue": "Failed to import libcppyy3_8. Please check that ROOT has been built for Python 3.8",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "File \u001b[0;32m/cern/root/lib/cppyy/__init__.py:60\u001b[0m\n\u001b[1;32m     59\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m---> 60\u001b[0m     \u001b[43mimportlib\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mimport_module\u001b[49m\u001b[43m(\u001b[49m\u001b[43mlibcppyy_mod_name\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m     61\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m:\n",
      "File \u001b[0;32m~/anaconda3/envs/myML/lib/python3.8/importlib/__init__.py:127\u001b[0m, in \u001b[0;36mimport_module\u001b[0;34m(name, package)\u001b[0m\n\u001b[1;32m    126\u001b[0m         level \u001b[38;5;241m+\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[0;32m--> 127\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43m_bootstrap\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_gcd_import\u001b[49m\u001b[43m(\u001b[49m\u001b[43mname\u001b[49m\u001b[43m[\u001b[49m\u001b[43mlevel\u001b[49m\u001b[43m:\u001b[49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mpackage\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mlevel\u001b[49m\u001b[43m)\u001b[49m\n",
      "File \u001b[0;32m<frozen importlib._bootstrap>:1014\u001b[0m, in \u001b[0;36m_gcd_import\u001b[0;34m(name, package, level)\u001b[0m\n",
      "File \u001b[0;32m<frozen importlib._bootstrap>:991\u001b[0m, in \u001b[0;36m_find_and_load\u001b[0;34m(name, import_)\u001b[0m\n",
      "File \u001b[0;32m<frozen importlib._bootstrap>:973\u001b[0m, in \u001b[0;36m_find_and_load_unlocked\u001b[0;34m(name, import_)\u001b[0m\n",
      "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'libcppyy3_8'",
      "\nDuring handling of the above exception, another exception occurred:\n",
      "\u001b[0;31mImportError\u001b[0m                               Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[1], line 5\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mos\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m path\n\u001b[1;32m      4\u001b[0m \u001b[38;5;66;03m#import ROOT\u001b[39;00m\n\u001b[0;32m----> 5\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mROOT\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m TCanvas, TFile, TFormula, TH1D, TF1, TMinuit, TFitResult, TVirtualFitter\n\u001b[1;32m      6\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mROOT\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m gROOT, gBenchmark, gRandom, gSystem\n",
      "File \u001b[0;32m/cern/root/lib/ROOT/__init__.py:22\u001b[0m\n\u001b[1;32m     19\u001b[0m \u001b[38;5;66;03m# Prevent cppyy from filtering ROOT libraries\u001b[39;00m\n\u001b[1;32m     20\u001b[0m environ[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mCPPYY_NO_ROOT_FILTER\u001b[39m\u001b[38;5;124m'\u001b[39m] \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124m1\u001b[39m\u001b[38;5;124m'\u001b[39m\n\u001b[0;32m---> 22\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mcppyy\u001b[39;00m\n\u001b[1;32m     23\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mROOTSYS\u001b[39m\u001b[38;5;124m'\u001b[39m \u001b[38;5;129;01min\u001b[39;00m environ:\n\u001b[1;32m     24\u001b[0m     \u001b[38;5;66;03m# Revert setting made by cppyy\u001b[39;00m\n\u001b[1;32m     25\u001b[0m     cppyy\u001b[38;5;241m.\u001b[39mgbl\u001b[38;5;241m.\u001b[39mgROOT\u001b[38;5;241m.\u001b[39mSetBatch(\u001b[38;5;28;01mFalse\u001b[39;00m)\n",
      "File \u001b[0;32m/cern/root/lib/cppyy/__init__.py:62\u001b[0m\n\u001b[1;32m     60\u001b[0m     importlib\u001b[38;5;241m.\u001b[39mimport_module(libcppyy_mod_name)\n\u001b[1;32m     61\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m:\n\u001b[0;32m---> 62\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mImportError\u001b[39;00m(\n\u001b[1;32m     63\u001b[0m             \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mFailed to import \u001b[39m\u001b[38;5;132;01m{}\u001b[39;00m\u001b[38;5;124m. Please check that ROOT has been built for Python \u001b[39m\u001b[38;5;132;01m{}\u001b[39;00m\u001b[38;5;124m.\u001b[39m\u001b[38;5;132;01m{}\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;241m.\u001b[39mformat(\n\u001b[1;32m     64\u001b[0m                 libcppyy_mod_name, major, minor))\n\u001b[1;32m     66\u001b[0m \u001b[38;5;66;03m# ensure 'import libcppyy' will find the versioned module\u001b[39;00m\n\u001b[1;32m     67\u001b[0m sys\u001b[38;5;241m.\u001b[39mmodules[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mlibcppyy\u001b[39m\u001b[38;5;124m'\u001b[39m] \u001b[38;5;241m=\u001b[39m sys\u001b[38;5;241m.\u001b[39mmodules[libcppyy_mod_name]\n",
      "\u001b[0;31mImportError\u001b[0m: Failed to import libcppyy3_8. Please check that ROOT has been built for Python 3.8"
     ]
    }
   ],
   "source": [
    "import math\n",
    "import numpy as np\n",
    "from os import path\n",
    "#import ROOT\n",
    "from ROOT import TCanvas, TFile, TFormula, TH1D, TF1, TMinuit, TFitResult, TVirtualFitter\n",
    "from ROOT import gROOT, gBenchmark, gRandom, gSystem"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#read data from text file\n",
    "data = np.genfromtxt('FitTestData.txt', dtype='d')\n",
    "print(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# instanciate canvas and histogramm\n",
    "c = TCanvas( 'c','Fit Test',200,10,700,500)\n",
    "sig = TH1D( 'sig', 'Signal Mass', 100, 0. , 5. )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fill histogramm\n",
    "for x in data:\n",
    "  sig.Fill(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fit function: gaus + exponential\n",
    "def myN(x, p):\n",
    "  return p[0] * np.exp(-0.5 * ((x[0]-p[1])/p[2])**2) + p[3] * np.exp( p[4]*x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fit function: gaussian\n",
    "def myGauss(x, p):\n",
    "  return p[0] * np.exp(-0.5 * ((x[0]-p[1])/p[2])**2) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fit function: gaussian\n",
    "def myExp(x, p):\n",
    "  return p[0] * np.exp( p[1]*x[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# root formular mechanism\n",
    "form = TFormula( 'form', '[0] * exp(-0.5 * ((x-[1])/[2])**2) + [3] * exp( [4]*x)')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# define fit functions\n",
    "#f = TF1('f','form', 0 , 5 , 5)\n",
    "f = TF1('f',myN, 0 , 5 , 5)\n",
    "f_exp = TF1('f_exp',myExp, 0.1 , 1.2 , 2)\n",
    "f_gauss = TF1('f_exp',myGauss, 1.6 , 2.4 , 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# set start values of the fit\n",
    "f.SetParameters(250.,2.,.2,5.5,-0.7)\n",
    "f_gauss.SetParameters(250.,2.,.1)\n",
    "f_gauss.SetLineColor(3)\n",
    "f_exp.SetParameters(130.,-0.5)\n",
    "f_exp.SetLineColor(4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# perform fit\n",
    "# Options:  Q/V   Quiet/Verbose mode (default is between Q and V)\n",
    "#   E   Perform better errors estimation using the Minos technique\n",
    "#   M   Improve fit results\n",
    "#   R   Use the range specified in the function range\n",
    "#   +   Add this new fitted function to the list of fitted functions\n",
    "fit = sig.Fit(f, \"V M E S\",\"\",0.,5.)\n",
    "fit_exp = sig.Fit(f_exp, \"R+ E S\",\"\",0.1,1.2)\n",
    "fit_gauss = sig.Fit(f_gauss, \"R+ E S\",\"\",1.6,2.4)\n",
    "print (\"Fit results: mean=\",fit.Parameter(1),\" +/- \",fit.ParError(1), \n",
    "       \"  sigma=\",fit.Parameter(2),\" +/- \",fit.ParError(2) )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# print fit summary\n",
    "fit.Print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# drawing \n",
    "c.Draw()    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
