{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Important python packages and how to use them: scipy\n",
    "\n",
    "scipy provides, together with numpy, a broad spectrum for numerical methods commonly used in physics. Usually, it's worth to check in advance if there are functions provided by packages that perform operations much faster than implementing it on your own with e.g. for-loops etc. \n",
    "\n",
    "One of those is definetly scipy, which offers a wide range of functionalities for fitting, integration, solving differential equations, statistics and so much more. What we will take a look in the next couple of minutes are the fitting capabilities and a tool to estimate correlations between data (when you reconstruct something e.g. with a regression NN and you want to check how well these data correspond to the true ones).\n",
    "\n",
    "We import the curve_fit function from scipy, which is included in the optimize module. It uses a least squares algorithm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from scipy.optimize import curve_fit"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's create some pseudodata and inspect them"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.linspace(0, 20)\n",
    "\n",
    "# The data is distributed according to a function, that we define on our own\n",
    "def function(x, a, b, c):\n",
    "    return a * np.sin(x) + b * np.exp(-c * x)\n",
    "\n",
    "# We add some gaussian noise to the data\n",
    "y = function(x, 2.5, 1.3, 0.1) # these are the parameters we want to get back from the fit in the end\n",
    "y_noise = 0.3 * np.random.normal(size = x.size)\n",
    "y_noise += y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When we want to plot the data, we use the matplotlib package"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Plot the data\n",
    "plt.errorbar(x, y_noise, \n",
    "             fmt = \"o\",\n",
    "             label = \"Noisy pseudo-measurement\"\n",
    ")\n",
    "\n",
    "plt.plot(x, y, label = \"True function\", color = \"black\")\n",
    "\n",
    "plt.legend()\n",
    "plt.xlabel(r\"$x$-data\")\n",
    "plt.ylabel(r\"$y$-data\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we want to use the curve-fit functionalities to fit the noisy data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "parameters, covariance_matrix = curve_fit(function, x, y_noise)\n",
    "\n",
    "# more parameters can be provided here:\n",
    "# - sigma, absolute_sigma: std. dev. of values and whether they are relative or not\n",
    "# - maxfev: number of function evaluations\n",
    "# - p0=[...]: initial values for fit start\n",
    "# - bounds=[[...], [...]] limits for the fit\n",
    "\n",
    "# Let's get the parameters uncertainties from the covariance matrix, which includes also the relationship and dependendy between the fit parameters\n",
    "# What is the difference to the correlation?\n",
    "print(\"Covariance matrix =\\n\", covariance_matrix)\n",
    "parameter_uncertainties = np.sqrt(np.diag(covariance_matrix))\n",
    "print(\"\\nParameters =\", parameters)\n",
    "print(\"Parameter uncertainties =\", parameter_uncertainties)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We include the fit in our plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.errorbar(x, y_noise, \n",
    "             fmt = \"o\",\n",
    "             label = \"Noisy pseudo-data\"\n",
    ")\n",
    "\n",
    "plt.plot(x, y, label = \"True function\", color = \"black\")\n",
    "\n",
    "# To get a smooth fit function, we create a new x-array\n",
    "x_fit = np.linspace(np.min(x), np.max(x), 1001)\n",
    "plt.plot(x_fit, function(x_fit, *parameters), color = \"orange\", label = \"Fit function\") # the *-notation unpacks a vector\n",
    "\n",
    "# We can also draw the band of the fit uncertainty \n",
    "plt.fill_between(x_fit, \n",
    "                 function(x_fit, *(parameters - parameter_uncertainties)), \n",
    "                 function(x_fit, *(parameters + parameter_uncertainties)), \n",
    "                 color = \"orange\", alpha = 0.3\n",
    ")\n",
    "\n",
    "plt.legend()\n",
    "plt.xlabel(r\"$x$-data\")\n",
    "plt.ylabel(r\"$y$-data\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also examine the correlation. For this, we simply assume that our fit is our reconstruction of an observable (and we create ourself much more \"data\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_correlation = np.linspace(np.min(x), np.max(x), 100000)\n",
    "y_true = function(x_correlation, 2.5, 1.3, 0.5)\n",
    "y_reco = function(x_correlation, *parameters)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Always useful for such tasks: the 2D histogram or a scatter plot\n",
    "\n",
    "plt.hist2d(y_true, \n",
    "           y_reco, \n",
    "           bins = 20, \n",
    "           cmap = \"plasma\",\n",
    ")\n",
    "\n",
    "plt.colorbar(label = \"Entries\")\n",
    "plt.xlabel(\"True values\")\n",
    "plt.ylabel(\"Reconstructed values\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From the documentation (https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html):\n",
    "\"The Pearson correlation coefficient [1] measures the linear relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\"\n",
    "\n",
    "\n",
    "The correlation coefficient is calculated as follows:\n",
    "$$ r = \\frac{\\sum_{}^{} (x - \\bar{x})(y - \\bar{y})}{\\sqrt{\\sum_{}^{} (x - \\bar{x})^2 \\cdot \\sum_{}^{} (y - \\bar{y})^2}} $$\n",
    "\n",
    "First we include the pearson correlation from scipy.stats"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.stats import pearsonr\n",
    "\n",
    "correlation_result = pearsonr(y_true, y_reco)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Statistic =\", correlation_result.statistic)\n",
    "print(\"p-value =\", correlation_result.pvalue)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What does the statistic value refer to? What range does it cover?\n",
    "\n",
    "How would it look like when our reconstruction does not correlate to our true values? Let's try it out:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_reco_uncorrelated = np.random.normal(size = y_true.size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.scatter(y_true, \n",
    "            y_reco_uncorrelated, \n",
    "            s = 1, alpha = 0.5\n",
    ")\n",
    "\n",
    "# plt.colorbar(label = \"Entries\")\n",
    "plt.xlabel(\"True values\")\n",
    "plt.ylabel(\"Reconstructed values\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "correlation_result_uncorrelated = pearsonr(y_true, y_reco_uncorrelated)\n",
    "\n",
    "print(\"Statistic =\", correlation_result_uncorrelated.statistic)\n",
    "print(\"p-value =\", correlation_result_uncorrelated.pvalue)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What does the $p$-value refer to? Is it favorable to have a large or a small $p$-value?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "zfit_env",
   "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.9.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
