{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Graph fit example within pyROOT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Welcome to JupyROOT 6.20/08\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import ROOT\n",
    "from ROOT import TF1, TVirtualFitter, TGraphErrors, TCanvas, TMinuit, TFitResult, gROOT, TGraph"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Define the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "numDat = 10 \n",
    "x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype='d')\n",
    "dx = np.array([0.1,0.1,0.5,0.1,0.5,0.1,0.5,0.1,0.5,0.1], dtype='d')\n",
    "y = np.array([1.1 ,2.3 ,2.7 ,3.2 ,3.1 ,2.4 ,1.7 ,1.5 ,1.5  ,1.7 ], dtype='d')\n",
    "dy = np.array([0.15,0.22,0.29,0.39,0.31,0.21,0.13,0.15,0.19,0.13], dtype='d')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Define fit function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def myNFunc(x, p):\n",
    "    return p[0] + x[0]*p[1] + p[2]*x[0]**2 + p[3]*x[0]**3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create ROOT function and set start parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "func = TF1('func',myNFunc, 0.5 ,10.5, 4)\n",
    "func.SetParameters(-1.3, 2.6 , -0.24 , 0.005)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create Graph with error bars"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "Graph = TGraphErrors(numDat, x, y, dx, dy)\n",
    "Graph.SetTitle( 'Fit Graph' )\n",
    "Graph.SetMarkerColor( 4 )\n",
    "Graph.SetMarkerStyle( 21 )\n",
    "Graph.SetMaximum(4.)\n",
    "Graph.SetMinimum(-1.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Start fitter and return fit result for later processing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " FCN=2.15982 FROM MINOS     STATUS=SUCCESSFUL     90 CALLS        2039 TOTAL\n",
      "                     EDM=4.56889e-09    STRATEGY= 1      ERROR MATRIX ACCURATE \n",
      "  EXT PARAMETER                                   STEP         FIRST   \n",
      "  NO.   NAME      VALUE            ERROR          SIZE      DERIVATIVE \n",
      "   1  p0          -1.03327e+00   4.63548e-01  -1.99485e-03   1.64067e-03\n",
      "   2  p1           2.54886e+00   3.59144e-01   2.70551e-03  -5.29683e-02\n",
      "   3  p2          -4.84278e-01   7.01863e-02  -2.72411e-04  -7.70245e-01\n",
      "   4  p3           2.56882e-02   3.97082e-03   3.97082e-03  -1.30073e+00\n"
     ]
    }
   ],
   "source": [
    "result = Graph.Fit(func, \"M E S\",\"\",0.5,10.5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Confidence plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "values = result.GetConfidenceIntervals(0.66, False)\n",
    "interval = TGraphErrors(Graph.GetN())\n",
    "for i in range(Graph.GetN()):\n",
    "    interval.SetPoint(i, Graph.GetX()[i], func.Eval(Graph.GetX()[i] ))\n",
    "    interval.SetPointError(i, 0, values[i] )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Canvas for plotting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "c = TCanvas( 'c', 'A Simple Fit',700, 500)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Draw canvas and graph and 1 sigma confidence"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 11288 characters]\n",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "Graph.Draw(\"AP\")\n",
    "interval.SetFillColor(21)\n",
    "interval.Draw(\"3\")\n",
    "c.Draw()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Create graph for confidence interval\n",
    "\n",
    "Compute the confidence intervals at the x points of the created graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "GraphConf = TGraphErrors(Graph.GetN())\n",
    "GraphConf.SetTitle(\"Fit Polynomial with .95 confidence;x;f(x)\")\n",
    "for i in range(Graph.GetN()):\n",
    "    GraphConf.SetPoint(i, Graph.GetX()[i],0 )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "  \n",
    "TVirtualFitter.GetFitter().GetConfidenceIntervals(GraphConf,0.95)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the \"GraphConf\" graph contains function values as its y-coordinates\n",
    "and confidence intervals as the errors on these coordinates"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "myC = TCanvas(\"myC\", \"Confidence Intervall\",800, 800);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "GraphConf.SetLineColor(4)\n",
    "GraphConf.Draw(\"AP\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "Graph.SetLineColor(2)\n",
    "Graph.SetMarkerStyle(21)\n",
    "Graph.Draw(\"P SAME\")\n",
    "func.SetLineColor(4)\n",
    "func.Draw(\"SAME\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 19160 characters]\n",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "myC.Draw()"
   ]
  }
 ],
 "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
}
