{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZMjNacnZ46Td"
   },
   "source": [
    "# Important Python packages and how to use them\n",
    "\n",
    "A big part of pythons 'power' is the vast availability of packages for nearly everything.\n",
    "If you want to do anything with python, it is always worth a quick look at google whether there\n",
    "is a package which is doing just that.\n",
    "\n",
    "### important packages we will discuss:\n",
    "\n",
    "- numpy: handling of numpy arrays for fast processing of large data arrays. Implements a lot of mathematical functions -> usage highly recommended for any sort of math task\n",
    "- matplotlib: for plots of all sort"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "WCC9cq0r46Tl"
   },
   "source": [
    "## 1. import\n",
    "Packages can be imported with the import keyword.\n",
    "For some packages there is a common alias like np for numpy. You can specify an alias as shown below. To import only a certain module from a package or only a function or class from a module, you can do so as well."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "UrqtgWkW46Tq"
   },
   "outputs": [],
   "source": [
    "# packages are included this way:\n",
    "import numpy\n",
    "\n",
    "# you can give an 'alias' to imported packages\n",
    "import numpy as np\n",
    "\n",
    "# you can import certain methods or classes from a package\n",
    "from scipy.optimize import curve_fit"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "mnOJH85P46T-"
   },
   "source": [
    "## 2. numpy: numerical python\n",
    "\n",
    "There is nearly always the need of processing arrays of numbers. If you use arrays, you should \"always\" use numpy arrays"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Pig5uLR-46UA"
   },
   "outputs": [],
   "source": [
    "# the numpy array is always recommended to use when it is about doing something with arrays\n",
    "a = np.array([1,2,3,4])\n",
    "\n",
    "print(a)\n",
    "\n",
    "# the handling is quite similar to lists\n",
    "print(a[-2:-1]) # the slicing means [-2:-2:]\n",
    "\n",
    "# very useful: functions executed with numpy arrays act on each entry normally without code changes:\n",
    "def f(x):\n",
    "    return x**2\n",
    "\n",
    "# a big exception are if statements, which wont work as expected on arrays!\n",
    "\n",
    "print(f(a))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ib51yrzA46UL"
   },
   "source": [
    "### numpy - some important features\n",
    "These are some methods you will need quite sure."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "yObYkbeS46UO"
   },
   "outputs": [],
   "source": [
    "# important features:\n",
    "\n",
    "# array of length 4 filled with zeros\n",
    "a = np.zeros(4)\n",
    "print(a)\n",
    "\n",
    "# array of length 3 filled with ones\n",
    "b = np.ones(3)\n",
    "print(b)\n",
    "\n",
    "\n",
    "# matrix of zeros with the size 3x4, meaning there will be 3 rows and 4 columns\n",
    "a = np.zeros((3,4))\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "M50BccAS46UW"
   },
   "outputs": [],
   "source": [
    "# linear distributed numbers between start and end (end included)\n",
    "# the third argument gives the length\n",
    "x = np.linspace(0, 10, 21)\n",
    "print('x =', x)\n",
    "\n",
    "# exponentially distributed numbers with the exponents from lower to higher\n",
    "# this means from 1*10**1 = 10 up to 1*10**5 = 100000\n",
    "y = np.logspace(1, 5, 11)\n",
    "print('y =', y)\n",
    "\n",
    "# numbers between low (included) and high (excluded) with stepwidth as third argument\n",
    "k = np.arange(0, 16, 3)\n",
    "print('k =', k)\n",
    "\n",
    "# many functions for arrays are efficiently implemented in numpy\n",
    "y = np.exp(x)\n",
    "print('np.exp(x) =', y)\n",
    "\n",
    "#similar: np.log, np.sqrt, np.sin, np.cos,.........\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# in np.random there are several random generators, for example normal, uniform, poisson, ...\n",
    "x = np.random.normal(0, 1, 1000) #this means, the mean of the distribution is 0, the sigma is 1 and we generate 1000 numbers\n",
    "\n",
    "# there are many useful functions implemented for arrays like mean, variance, std_devation, sum, prod\n",
    "mean = x.mean()\n",
    "print(\"Mean for x:\", mean)\n",
    "variance = x.var()\n",
    "print(\"variance for x:\",variance)\n",
    "std_devation = x.std(ddof=1)\n",
    "print(\"Std. deviation for x:\",std_devation)\n",
    "x_sum = x.sum()\n",
    "print(\"Sum of x:\", x_sum)\n",
    "x_prod = x.prod()\n",
    "print(\"Prod of x:\", x_prod)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Finding the maxima/minima or the indicies for these is also quickly done via\n",
    "\n",
    "x_max = x.max()\n",
    "print(\"Max value in x:\", x_max)\n",
    "\n",
    "x_min =x.min()\n",
    "print(\"Min value in x:\", x_min)\n",
    "\n",
    "index_max = x.argmax() # or argmin()\n",
    "print(\"Index of the maxima:\", index_max)\n",
    "\n",
    "# Check if its the right index?\n",
    "print(x[index_max]) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# How to handle higher dimension arrays\n",
    "\n",
    "# We create any array with size 100x100x100 with random values between 0 and 1\n",
    "x_3dim = np.random.normal(0,1, [100,100,100])\n",
    "\n",
    "# With .shape one can check the shape of an array\n",
    "print(\"Shape:\", x_3dim.shape)\n",
    "\n",
    "# With .size one can check the number of entries of an array\n",
    "print(\"Size:\", x_3dim.size)\n",
    "\n",
    "# With .reshape one can change the dimensions of an array for example to have 1D indicies\n",
    "# Warnining: This obviously this only works if the size of the array stays the same \n",
    "x_flattend = x_3dim.reshape(100*100*100)\n",
    "\n",
    "# Or you can use .flatten() to get a 1D array\n",
    "x_flattend_2nd_ver = x_3dim.flatten()\n",
    "\n",
    "print(\"Shape of flattend array:\", x_flattend.shape)\n",
    "print(\"Size of flattend array:\", x_flattend.size)\n",
    "print(\"Size of flattend array according to 2nd version: \", x_flattend_2nd_ver.size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Array / Matrix Operations\n",
    "# We initilaize 2 random arrays of size 2x2 with random intergers between 0 and 10\n",
    "x = np.random.randint(0,10,[2,2])\n",
    "y = np.random.randint(0,10,[2,2])\n",
    "print(\"x = \\n\", x)\n",
    "print(\"y = \\n\", y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Adding Subtraction works as expected\n",
    "print(\"x+y = \\n\", x+y)\n",
    "print(\"x-y = \\n\", x-y)\n",
    "# * or / are elementwise multiplication/division\n",
    "print(\"x*y = \\n\", x*y)\n",
    "print(\"x/y = \\n\", x/y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Matrix Multiplication is possible via @\n",
    "print(\"x@y = \\n\", x@y)\n",
    "# Matrices can be transposed via .T\n",
    "print(\"x = \\n\", x)\n",
    "print(\"x.T = \\n\", x.T)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "BNXLhFs346Uh"
   },
   "source": [
    "### masking\n",
    "Very often you want to \"filter\" an array by a value e.g. all values larger than a certain threshold. This can be done very easily!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Zt3hSc9h46Uk"
   },
   "outputs": [],
   "source": [
    "x = np.random.normal(0,1,5)\n",
    "\n",
    "# very useful for slicing\n",
    "print('gaussian distributed x =', x)\n",
    "print('Is x>0.2?', x>0.2)\n",
    "print('The numbers with x>0.2 are ',x[x>0.2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "NC7IhGvc46Uv"
   },
   "outputs": [],
   "source": [
    "# often overlooked but an extremely powerful tool:\n",
    "x = np.arange(-5, 5)\n",
    "print(\"Values: \", x)\n",
    "\n",
    "# entry-wise if evaluation\n",
    "print(\"Values are below zero at these indices: \", np.where(x < 0)[0])\n",
    "# you can also apply a function to the parts of the array where the condition is True or False\n",
    "print(\"Rectified values: \", np.where(x < 0, 0, 1))\n",
    "\n",
    "# you can chain multiple evaluations with \n",
    "# AND: (first condition in brackets) & (second condition in brackets)\n",
    "# OR: (first condition in brackets) | (second condition in brackets)\n",
    "print(\"Values: \", x)\n",
    "print(\"Values are below zero and above -3 at these indices: \", np.where((x < 0) & (x > -3))[0])\n",
    "print(\"Values are below zero or above 1 at these indices: \", np.where((x < 0) | (x > 1))[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "MRxovItc46U3"
   },
   "source": [
    "## 3. matplotlib\n",
    "matplotlib is a quite flexible library for easy plot creation. Usually pyplot from matplotlib is imported with the alias plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "RPuC4_e_46U4"
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# fill a histogram with the created numbers and show the histogram\n",
    "x = np.random.normal(0, 1, 1_000)\n",
    "plt.hist(x, bins=20)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "A9z5TQ5E46VB"
   },
   "source": [
    "### python histograms\n",
    "python sees histograms not quite as the same thing like for example root. In python they are stored and handles as a collection of:\n",
    "> (bin edges, bin contents, \"drawn\" bars for display)\n",
    "<br>\n",
    "\n",
    "You can get these from the function call of plt.hist "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Gx-uVn3S46VC"
   },
   "outputs": [],
   "source": [
    "things = plt.hist(x)\n",
    "print(things)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "RrFHoHvG46VK"
   },
   "source": [
    "### Example 3.1: Distributions and histograms\n",
    "\n",
    "Look up another distribution available from numpy random. Generate some data points, fill them into a histogram and show it."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Cwj158tW46VT"
   },
   "source": [
    "### plot with matplotlib\n",
    "This is an example of a more \"complex\" plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "SKUAKGBs46VU"
   },
   "outputs": [],
   "source": [
    "# lets create an array and calc some formula on it\n",
    "x = np.linspace(-4, 4) # remember: create 50 equally dirstibuted numbers between -4 and 4\n",
    "y = x**2\n",
    "\n",
    "# get a figure and specify the size (in inches ...)\n",
    "# first number corresponds to the width, second to the height\n",
    "# dpi are \"dots per inch\" and refer to image quality\n",
    "# 300 is good for printing (like a thesis), but you should prefer pdf files for this anyway\n",
    "f = plt.figure(figsize=(6,4), dpi=300) \n",
    "\n",
    "# plot the values, add a 'style' and a label\n",
    "plt.plot(x, y, 'k+', label = '$f(x) = x^2$') # k stands for black, the + will plot a + as the marker\n",
    "\n",
    "# add labels to the axis\n",
    "plt.xlabel('$x$')\n",
    "plt.ylabel('$y$')\n",
    "\n",
    "# add a legend to the best position\n",
    "plt.legend(loc='best')\n",
    "\n",
    "# activate the grid (True optional as argument)\n",
    "plt.grid()\n",
    "\n",
    "# make things look nice if something has gone wrong\n",
    "plt.tight_layout()\n",
    "\n",
    "# save to file\n",
    "plt.savefig('plot.png')\n",
    "\n",
    "# show\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "314SH95g46Vb"
   },
   "source": [
    "### Example 3.2: Enhance your histograms\n",
    "Add a label, x- and y- axis labels and a legend to your histograms. Use a different color and save it.\n",
    "### Example 3.3: Red dotted sine function\n",
    "Create an array from 0 to 2pi (np.pi is available ...) and compute the sine function of it. Plot it to a canvas using a red dashed line.\n",
    "\n",
    "### Example 3.4: Slicing plots\n",
    "Plot positive values black, negative ones red.\n",
    "\n",
    "### Example 3.5: Add gaussian noise\n",
    "Add gaussian noise to the sine plot and use the same color for all data points again."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "IPcKEXP146Vd"
   },
   "source": [
    "### errorbar\n",
    "For many plots in physics you need to also show the uncertainties of a given value. This can be done with the errorbar method, parsing the uncertainties as yerr=values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "-7Jq-iEp46Vf"
   },
   "outputs": [],
   "source": [
    "# another very important 'plotstyle': errorbar\n",
    "\n",
    "# get another figure\n",
    "plt.figure(figsize=(6,4), dpi=300)\n",
    "\n",
    "# the hist function returns the bin contents, the bin edges and the histogram itself\n",
    "x = np.random.normal(0, 1, 1000)\n",
    "content, edges, hist = plt.hist(x, label='histogram')\n",
    "#print(edges)\n",
    "#print(edges[:-1])\n",
    "#print(edges[1:])\n",
    "#print((edges[:-1]+edges[1:])/2)\n",
    "\n",
    "# add the errorbar plot\n",
    "# the style is specified using the fmt argument\n",
    "## we need the bin centres for the position of the errorbars\n",
    "## we can get them from the bin edges building the mean values of a pair of two edges\n",
    "## we can use our known form of indexing for that\n",
    "### plt.errorbar(x-position, y-position, yerr=values, xerr=values, ...)\n",
    "plt.errorbar((edges[:-1]+edges[1:])/2, y=content, yerr=np.sqrt(content), fmt='+', label='uncertainties')\n",
    "\n",
    "# adding the legend and show\n",
    "plt.legend(loc='best')\n",
    "plt.show()\n",
    "plt.clf()\n",
    "# errorbar also takes two arrays as yerr input for assymetric errorbars\n",
    "\n",
    "# other useful plot styles: semilogy, semilogx, loglog"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "colab": {
   "name": "2_Tutorial.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "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.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
