{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python basics course"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Setting up conda environment on interactive E5a machines.\n",
    "```\n",
    "ssh interactive\n",
    "set_conda\n",
    "source activate root_forge_36\n",
    "```\n",
    "Start `jupyter` notebook with arbitrary 4-digit port\n",
    "```\n",
    "jupyter notebook --port <port_on_machine>\n",
    "```\n",
    "Open local terminal and do port forwarding\n",
    "```\n",
    "ssh -NfL <local_port>:localhost:<port_on_machine> interactive\n",
    "```\n",
    "Copy the following-like URL from machine to your browser\n",
    "```\n",
    "http://localhost:<port_on_machine>/?token= \n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Variables\n",
    "- Automatic lifetime management: variables start to exist when first assigned a value and are deleted when not used anymore in the program\n",
    "- Everything in Python can be assigned to a variable: numbers, strings, tuples, lists, dictionaries, functions, classes, class instances, modules\n",
    "- Variables must start with letter and consist of letters, numbers and underscore\n",
    "    - Variables should not start with an underscore (special meaning in Python)\n",
    "- Everything is a class with methods"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# boolean\n",
    "x = True\n",
    "x = False\n",
    "\n",
    "# numbers\n",
    "x = 1\n",
    "x = 2.3\n",
    "x = 1.234e-12\n",
    "x = 1 + 2j\n",
    "\n",
    "# strings: immutable sequence of characters\n",
    "x = \"hello\"\n",
    "x = 'world' # builtin unicode support\n",
    "\n",
    "# tuple: immutable sequence of values\n",
    "x = (1, 2, 3)\n",
    "y = (1, x, \"foo\")\n",
    "\n",
    "# list: mutable sequence of values\n",
    "y = [1, x, \"foo\"] # more on lists later\n",
    "\n",
    "# set: mutable set of values\n",
    "x = {1, 2, 3}\n",
    "\n",
    "# dict: key-value pairs\n",
    "x = {\"foo\": 1, \"bar\": 2, 2: \"bar\", 1: \"foo\"}\n",
    "\n",
    "# special: None to create an \"empty\" variable\n",
    "x = None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Operators"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 2\n",
    "b = 3\n",
    "print(a + b)\n",
    "print(a - b)\n",
    "print(a * b)\n",
    "print(a / b)\n",
    "print(a // b) #integer division\n",
    "print(a ** b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = \"hello\"\n",
    "x + \" world\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(x)\n",
    "x += \" students\"\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Control structures"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### if-else queries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 1\n",
    "if a % 2 == 0:\n",
    "    print(f\"{a} is an even number\")\n",
    "else:\n",
    "    print(f\"{a} is an odd number\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a=0\n",
    "if a == 0:\n",
    "    print(f\"{a} is 0\")\n",
    "elif a %2 == 0:\n",
    "    print(f\"{a} is an even number\")\n",
    "else:\n",
    "    print(f\"{a} is an odd number\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = True\n",
    "if a:\n",
    "    print(\"True\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "l = [2 > 3, 2 > 1, 2==2]\n",
    "\n",
    "if any(l):\n",
    "    print(\"At least one list element is True\")\n",
    "    \n",
    "if all(l):\n",
    "    print(\"Every list element is True\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loops"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(10):\n",
    "    print(i)\n",
    "while i < 9:\n",
    "    print(i)\n",
    "    i += 1\n",
    "planets = [\"mercury\", \"venus\", \"earth\", \"mars\", \"jupiter\", \"saturn\", \"neptune\", \"pluto\", \"sun\"]\n",
    "for planet in planets:\n",
    "    if planet == \"earth\":\n",
    "        continue\n",
    "    if planet == \"sun\":\n",
    "        break\n",
    "    if planet == \"pluto\":\n",
    "        break\n",
    "        #raise Exception('S. Cooper - \"I liked pluto\", but pluto is not a planet anymore')\n",
    "    else:\n",
    "        print(planet)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Lists\n",
    "Lists can contain objects of different data types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "empty_list = []\n",
    "filled_list = [1,2]\n",
    "array_list = [[1,2], [2,4]]\n",
    "physicists = [\"Schrödinger\", \"Pauli\", \"Hertz\"]\n",
    "random_list = [np.pi, \"Elektron\", (1,2), [\"Hideki Yukawa\", \"Steven Weinberg\", \"Bruno Pontecorvo\"]]\n",
    "print(empty_list, filled_list, array_list, random_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#empty_list[0]=\"LHCb\"\n",
    "#print(empty_list)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### List slicing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "experiments = [\"LHCb\", \"ATLAS\", \"CMS\", \"ALICE\", \"SuperKamiokande\", \"KATRIN\"]\n",
    "experiments[4] = \"HyperKamiokande\"\n",
    "print(experiments, experiments[:2], experiments[1:2], experiments[-1])\n",
    "experiments = [[\"LHCb\", \"ATLAS\", \"CMS\", \"ALICE\"], [\"ALEPH\", \"DELPHI\", \"L3\", \"OPAL\"],\n",
    "               [\"BaBar\", \"ARGUS\", \"TASSO\", \"H1\", \"Hera-B\"]]\n",
    "print(experiments[2][2:3])\n",
    "print(experiments[::2])\n",
    "print(experiments[::-1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### List operations\n",
    "\n",
    "- `append()` -> adds one element add the end of the list \n",
    "- `remove()` -> removes the given element from the list\n",
    "- `insert()` -> inserts element at given list index to the list\n",
    "- `extend()` -> adds elements of iterable objects (e.g. list, numpy array, ...) to the end of a list\n",
    "- `pop()` -> removes list element at given list index\n",
    "- `count()` -> counts number of elements in list\n",
    "- `index()` -> returns index of given element\n",
    "- `sort()` -> sorts list\n",
    "- `reverse()` -> reverses order of list elements\n",
    "- `copy()` -> returns copied list\n",
    "- `clear()` -> removes all list elements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "empty_list = []\n",
    "physicists = [\"Schrödinger\", \"Pauli\", \"Hertz\"]\n",
    "empty_list.append(\"Curie\")\n",
    "print(physicists+empty_list)\n",
    "print(2*physicists)\n",
    "physicists.remove(\"Pauli\")\n",
    "print(physicists)\n",
    "physicists.insert(1,\"von Neumann\")\n",
    "print(physicists)\n",
    "physicists.extend(np.array([1,2]))\n",
    "print(physicists)\n",
    "physicists_copy = physicists.copy()\n",
    "physicists.pop(2)\n",
    "print(physicists, physicists_copy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### List comprehensions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "x = np.linspace(0, 9, 10)\n",
    "x2 = [i**2 for i in x]\n",
    "print(x)\n",
    "print(x2)\n",
    "x2_even = [i**2 for i in x if i%2!= 0] \n",
    "x2_odd = [i**2 for i in x if i%2==0]\n",
    "print(x2_even)\n",
    "print(x2_odd)\n",
    "z = [x+y for x in range(3) for y in range(4)]\n",
    "print(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dictionaries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dictionary = {\"particles\": {\"hadrons\":[\"mesons\", \"baryons\"]\n",
    "                            , \"leptons\":[\"electron\",\"muon\",\"tau\"]}}\n",
    "dictionary.update({\"physicists\": [\"Marie Curie\", \"Albert Einstein\", \"Erwin Schrödinger\"]})\n",
    "dictionary[\"particles\"][\"hadrons\"].append(\"exotica\")\n",
    "print(dictionary)\n",
    "del dictionary[\"particles\"][\"hadrons\"]\n",
    "print(dictionary)\n",
    "dictionary[\"particles\"].update({\"hadrons\":{\"mesons\":[\"kaon\", \"pion\"], \"baryons\":[\"proton, neutron\"], \"exotica\":[\"tetraquark\", \"pentaquark\"]}})\n",
    "print(dictionary)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### String formatting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = \"simple string\"\n",
    "t = \"a\"\n",
    "s0 = \"%s\" %s\n",
    "s1 = \"more advanced string than {}\".format(s)\n",
    "s2 = \"{0} more advanced string than {0} {1}\".format(t, s) \n",
    "s3 = f\"{t} more advanced string than {t} {s}\"\n",
    "print(s0)\n",
    "print(s1)\n",
    "print(s2)\n",
    "print(s3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Numpy\n",
    "- `ndarray` for efficient storage of large multi-dimensional homogenous arrays of variables\n",
    "- Fast element-wise operations on arrays and vectorized computations\n",
    "- Powerful advanced indexing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "l = [1,2,3,4,5]\n",
    "na = np.array(l)\n",
    "print(l*2, na*2)\n",
    "na*na"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#predefined mathematical functions and numbers\n",
    "print(np.pi, np.e)\n",
    "print(np.cos(np.pi), np.tan(np.pi))\n",
    "np.around(np.pi, 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.array([[1,2,3],[23, 22, 33]])\n",
    "a.shape, a.size, a.ndim, a.dtype"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.eye(6)\n",
    "np.zeros(4)\n",
    "np.empty((2,3))\n",
    "print(np.ones((2,2,2)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_lin = np.linspace(1,1000,4)\n",
    "x_geom = np.geomspace(1, 1000, 4)\n",
    "x_log = np.logspace(1, 10, 4) #base^start to base^stop, default base is 10\n",
    "x_ln = np.logspace(1, 10, 4, base=np.e)\n",
    "x_ar = np.arange(1, 10, 1) #third number refers to step width\n",
    "print(x_lin, x_geom, x_log, x_ln, x_ar)\n",
    "#linspace, logspace, geomspace, arange"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Matrix and vector multiplication"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.array([1, 1, 1])\n",
    "print(a*a, np.inner(a,a)==np.dot(a, a), a @ a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.cross(a, a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A = np.zeros((4,4))\n",
    "A[:][1] = 1\n",
    "print(A @ A.T, np.dot(A, A.T))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.dot(a, a.T), np.outer(a, a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Indexing\n",
    "Can be done in the same way as indexing/slicing of lists"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "l = [i for i in range(1,10)]\n",
    "print(l)\n",
    "print(l, l[:2], l[2:], l[::-1], l[::2], l[:3][::2][::-1][-2])\n",
    "a = np.arange(1, 10, 1)\n",
    "print(a, a[:2], a[2:], a[::-1], a[::2], a[:3][::2][::-1][-2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a2d = np.array([[i for i in range(10)],[2*i for i in range(10)]])\n",
    "a2d[-1,2:5] \n",
    "a2d[:, -1]\n",
    "a2d[:, :] = 0\n",
    "a2d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "array_1 = np.array([1,2])\n",
    "array_2 = np.array([3,4])\n",
    "print(array_1+array_2, np.concatenate((array_1, array_2)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a2d = np.array([[i for i in range(10)],[2*i for i in range(10)]])\n",
    "a2d.T == np.transpose(a2d)\n",
    "b=3*np.eye(3)\n",
    "c=2*np.ones(3)\n",
    "print(b*c)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.array([i for i in range(10)])\n",
    "print(np.sum(a), np.prod(a), np.mean(a), np.abs(-1*a), np.sqrt(a), a%2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Reading and writing of text files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = np.array([1, 1, 1, 1])\n",
    "x = np.array([2, 1, 1, 0])\n",
    "\n",
    "np.savetxt(\"data.txt\", np.column_stack([n, x]))\n",
    "\n",
    "with open(\"data.txt\", \"r\") as f:\n",
    "    print(f.read())\n",
    "\n",
    "n_in, x_in = np.genfromtxt(\"data.txt\", unpack = True)\n",
    "print(n_in)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Scipy\n",
    "- The `scipy` library can be used for natural constants, integrating, "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Natural Constants"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import scipy.constants as c\n",
    "print(c.e, c.electron_mass)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in c.physical_constants.keys():\n",
    "    if i.find(\"electron\") != -1:\n",
    "        print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Integrating"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.integrate import quad, simps\n",
    "x = np.linspace(1,10, 1000)\n",
    "quad(lambda x: 1/x**2, 1, np.inf)\n",
    "quad(lambda x: x**3*np.exp(x), 0, 2)\n",
    "simps([i for i in range(10)], [i**2 for i in range(10)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Special functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.special import erf, jv, sph_harm, eval_hermite, eval_legendre\n",
    "\n",
    "x = np.linspace(-1, 1, 51)\n",
    "y = [[eval_hermite(n,i) for i in x] for n in range(5)]\n",
    "\n",
    "for n,i in enumerate(y):\n",
    "    plt.plot(x, i, label=f\"$H_{n}$(x)\")\n",
    "    plt.legend(loc=\"best\")\n",
    "    plt.xlabel(r\"$x$\")\n",
    "    plt.ylabel(r\"$H_n(x)$\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy import stats\n",
    "x=np.array([1,2,3])\n",
    "stats.sem(x) == np.std(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x=np.linspace(0,10,100)\n",
    "\n",
    "def Gauss(x, mean, sigma):\n",
    "    '''Returns the value auf the Gauss function for given mean and sigma'''\n",
    "    z = (x - mean) / sigma\n",
    "    norm = np.sqrt(2 * np.pi) * sigma\n",
    "    return np.exp(-0.5 * z ** 2) / norm\n",
    "\n",
    "mean = sigma = 1\n",
    "Gauss(x, mean, sigma)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A docstring serves as description of your function to enhance usability"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "help(Gauss)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Do not define function that already exist."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.stats import norm\n",
    "norm.pdf(x, 0, 1)\n",
    "means = np.array([0, 1, 2])\n",
    "sigmas = np.array([1,2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Fun with loops\n",
    " - `range`: can be used to run over a set of integers\n",
    " - `enumerate`: \n",
    " - `zip`: can be used to run over multiple variables with same dimensions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "for i in range(10):\n",
    "    plt.plot(x, Gauss(x, mean, i+1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in enumerate(means):\n",
    "    print(i)\n",
    "    \n",
    "for counter, value in enumerate(means):\n",
    "    print(\"The %s. mean value is:\" %counter, value)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i,j in zip(means, sigmas):\n",
    "    plt.plot(x, Gauss(x,i,j))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import itertools\n",
    "\n",
    "def Gauss(x, mean, sigma):\n",
    "    '''Returns the value auf the Gauss function for given mean and sigma'''\n",
    "    return 1/np.sqrt(2*np.pi*sigma)*np.exp(-(x-mean)**2/(2*sigma**2))\n",
    "\n",
    "means=[1,2,3]\n",
    "sigmas=[1,2]\n",
    "\n",
    "for i in itertools.product(means, sigmas):\n",
    "    plt.plot(x, Gauss(x, i[0], i[1]), label=f\"$\\mu = {i[0]}, \\sigma = {i[1]}$\")\n",
    "\n",
    "plt.legend()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reading from and writing to files "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### json\n",
    "json files can be used to write down nested python objects composed of dictionaries and lists, can be very useful when storing (fit) parameters and reading them in quickly in another file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(dictionary)\n",
    "y=json.dumps(dictionary, indent=4, sort_keys=True)\n",
    "print(y)\n",
    "with open('dictionary.txt', 'w') as output_file:\n",
    "    json.dump(y, output_file)\n",
    "with open('dictionary.txt') as input_file:\n",
    "    z = json.load(input_file)\n",
    "print(z)\n",
    "dictionary_of_particles=json.loads(z)\n",
    "print(dictionary_of_particles)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### pickle"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Matplotlib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Use `%matplotlib inline` to make plots visible in your jupyter notebook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Basic plotting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.linspace(0, 10, 11)\n",
    "y = np.array([i**2 for i in x])\n",
    "plt.plot(x, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may want to plot different things in the same plot. You can use different colors for this. A good choice of colors is the standard color cycle. See [here](https://matplotlib.org/users/dflt_style_changes.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(x, x, \"C0\")\n",
    "plt.plot(x, 2*x, \"C1\")\n",
    "plt.plot(x, 3*x, \"C2\")\n",
    "plt.plot(x, 4*x, \"C3\")\n",
    "plt.plot(x, 5*x, \"C4\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Data points are by default connected. You can avoid this by using a marker style that is not a line. See [here](https://matplotlib.org/3.1.1/api/markers_api.html) for other styles. Using different marker styles for different data in the same plot is preferred over using different colors as they can also be distinguished in a black-and-white print."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(x, x, 'C0x')\n",
    "plt.plot(x, 2*x, 'C1o')\n",
    "plt.plot(x, 3*x, 'C2s')\n",
    "plt.plot(x, 4*x, 'C3^')\n",
    "plt.plot(x, 5*x, 'C4*')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same accounts for lines (connected data points). See [here](https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html) for further information. The size of markers as well as the thickness of lines can be changed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(x, x, linestyle = 'solid')\n",
    "plt.plot(x, 3*x, linestyle ='dashed', linewidth=0.5, marker=\"x\", markersize=12)\n",
    "plt.plot(x, 4*x, linestyle ='dotted', linewidth=4)\n",
    "plt.plot(x, 5*x, linestyle = 'dashdot', linewidth=5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Plots are a very important instrument to visualize data and present results to others. A proper labelling of the data is therefore\n",
    "indispensable. For this purpose you should label your axes and use legends."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "plt.plot(x, x**2, 'C0o', label=\"data\")\n",
    "plt.plot(x, 2*x**2, 'C0o')\n",
    "plt.plot(x, x**2, 'C2-', label=\"connected data points\")\n",
    "plt.plot(x, x, 'C3^', markersize=12, label=\"Large red triangles describing data from pp collisions recorded by the LHCb experiment on 3th of february 2018\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"y\")\n",
    "plt.grid()\n",
    "plt.legend(loc=\"upper left\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Proper labelling means that the viewer of your plot gets all the essential information. However, the plot should be readable and only information that is really necessary should be displaced. You can align the legend by the loc argument. loc=\"best\" can be an useful option."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.axvline(x=0.2)\n",
    "plt.axvline(x=0.4, color=\"C3\")\n",
    "plt.axhline(y=0.4, linestyle=\"--\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you want to show mass windows or cut regions it can be useful to draw horizontal/vertical lines."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can vary the transparency of lines, markers, fillings with the alpha factor. This can in particular be useful when plotting histograms."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "plt.plot(x, x**2, \"C0o\", markersize=5)\n",
    "plt.plot(x, x**2, \"C1^\", markersize=12)\n",
    "plt.plot(x, x**3, \"C0o\", markersize=5)\n",
    "plt.plot(x, x**3, \"C1^\", markersize=12, alpha=0.5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Error bars"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Measurements are useless without knowing the uncertainty on the result. Therefore, also uncertainties on data points should be plotted. This can be done by using errorbars."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.errorbar(x, y, xerr=0.25*x, yerr=5, fmt=\"C0^\", label=\"data points\", markersize = 7)\n",
    "plt.legend(loc=\"lower right\", fontsize=15)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also show uncertainties on fit functions by using a filling between the fitted function and its $1\\sigma$ band"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "yerr = 10\n",
    "plt.plot(x, x**2, \"C1\")\n",
    "plt.fill_between(x, x**2-yerr, x**2+yerr, color=\"C3\", label=r\"$1\\sigma$-band\", alpha=0.5)\n",
    "plt.legend(loc=\"upper left\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sometimes you migth want to have specific ticks on you axes. You can define the positions and tick labels. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Scales"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.linspace(0, 2*np.pi, 1000)\n",
    "plt.plot(x, np.sin(x), \"C3-\")\n",
    "plt.xticks([0, np.pi, 2*np.pi], [0, r\"$\\pi$\", r\"$2\\pi$\" ])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.linspace(1,10,1000)\n",
    "plt.plot(x, np.exp(x))\n",
    "plt.yscale(\"log\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Subplots"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can use subplots to include two plots in one. In order to edit the different plots you can assign the different subplots to different axes. Some of the aforementioned functions have different names when applying them to an axes object. Whenever you want to plot multiple things with different scales, that show different things or the plot might be overpopulate subplots should be used instead. In general, readability is a key property of every plot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, (ax1, ax2) = plt.subplots(1,2, figsize=(12, 5))\n",
    "ax1.plot(x, np.sin(x))\n",
    "ax2.plot(x, np.cos(x))\n",
    "ax1.set_ylabel(r\"$\\mathrm{sin}(x)$\")\n",
    "ax2.set_ylabel(r\"$\\mathrm{cos}(x)$\")\n",
    "ax1.set_ylim(-2,2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you want to do subplots that have the same scaling you can use shared axes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "fig, (ax1, ax2) = plt.subplots(2, 2 , sharey = True, figsize=(10,5))\n",
    "ax1[0].plot(x, np.sin(x))\n",
    "ax1[1].plot(2*x, np.sin(2*x))\n",
    "ax2[0].plot(x, np.cos(x))\n",
    "ax2[1].plot(x,x)\n",
    "ax2[1].set_ylabel(\"linear\")\n",
    "ax1[0].set_ylabel(\"trigonometric function\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Histograms"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = np.random.normal(0, 1, 10000)\n",
    "plt.hist(data, bins = 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "n, bin_start = np.histogram(data, bins=40)\n",
    "bin_centres = bin_start[:-1]+(bin_start[1]-bin_start[0])/2\n",
    "plt.hist(bin_start[:-1], bin_start, weights=n)\n",
    "plt.errorbar(bin_centres, n, fmt=\"C3x\", yerr = [np.sqrt(i) for i in n])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Multi-dimensional histograms can be useful if you look for correlations between different variables. For example they are commonly used to make Dalitz plots where you can see resonances of a three-body decay."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_2 = np.random.normal(0.2, 1.3, 10000)\n",
    "plt.hist2d(data, data_2, bins=20)\n",
    "plt.xlabel(\"$x_1$\")\n",
    "plt.ylabel(\"$x_2$\")\n",
    "plt.colorbar(label=\"Events\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Exercise\n",
    "The Hamiltonian of the quantum harmonic oscillator is\n",
    "\\begin{align}\n",
    "\\hat{H}=\\hat{T}+\\hat{V}= \\frac{\\hat{p}^2}{2m}+ \\frac{m\\omega^2 \\hat{x}^2}{2}, \n",
    "\\end{align}\n",
    "with the potential $\\hat{V}$.\n",
    "The wave functions of the quantum harmonic oscillator describe the solutions of the Schrödinger equation and are given by\n",
    "\\begin{align}\n",
    "\\psi_n(x) = \\biggl(\\frac{m \\omega}{\\pi \\hbar}\\biggr)^{1/4} \\frac{1}{\\sqrt{2^n n!}} H_n\\biggl( \\sqrt{\\frac{m\\omega}{\\hbar} } x \\biggr) \\text{exp}\\biggl(-\\frac{1}{2}\\frac{m\\omega}{\\hbar} x^2\\biggr),\n",
    "\\end{align}\n",
    "where the $H_n$ correspond to the Hermite polynomials. The energy levels $n=0,1,2,...$ of the quantum harmonic oscillator are given by\n",
    "\\begin{align}\n",
    "E_n = \\hbar \\omega \\biggl( n + \\frac{1}{2}\\biggr)\n",
    "\\end{align}\n",
    "1. Write a function that returns the wave function of an energy state $n$ for given $m$ and $\\omega$. Search for and make use of existing functions in the scipy library to describe the Hermite polynomials.\n",
    "2. Plot the wave functions and energies for different energy states $n$ and compare them to the potential of the harmonic oscillator.\n",
    "3. Include the probability density functions in the same plotting style by using subplots.\n",
    "4. Calculate the probabilities to find a particle between |x|< 0.5 by integrating over the probability density functions.\n",
    "\n",
    "Comment: Use arbitrary units."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.integrate import quad\n",
    "from scipy.special import eval_hermite\n",
    "\n",
    "def harmonic_oscillator(x, n, m=1, omega=1, hbar=1):\n",
    "    return (m*omega/np.pi*hbar)**(1/4)*1/np.sqrt(2**n *np.math.factorial(n))*eval_hermite(n, np.sqrt(m*omega/hbar)*x)*np.e**(-0.5*m*omega/hbar*x**2)\n",
    "\n",
    "x = np.arange(-3, 3, 0.01)\n",
    "hbar=m=1\n",
    "omega=1.5\n",
    "fig, (ax1, ax2) = plt.subplots(1,2, figsize=(12,4))\n",
    "\n",
    "\n",
    "for n in range(7):\n",
    "    energy = hbar*omega*(n +1/2)\n",
    "    for ax in [ax1, ax2]:\n",
    "        ax.plot((-3, 3), (energy, energy), 'k-', linewidth=0.5)\n",
    "        ax.annotate(rf\"$E_{n}$\", (-3.5, energy))\n",
    "        \n",
    "    ax1.plot(x,harmonic_oscillator(x, n, m, omega, hbar) + energy, label=rf\"$\\psi_{n}(x)$\")\n",
    "    ax2.plot(x,np.abs(harmonic_oscillator(x, n, m, omega, hbar))**2 + energy, label=rf\"$P(x)$\")\n",
    "    ax1.fill_between(x, harmonic_oscillator(x, n, m, omega, hbar) + energy, energy)\n",
    "    ax2.fill_between(x, np.abs(harmonic_oscillator(x, n, m, omega, hbar))**2 + energy, energy)\n",
    "    prob=-np.diff(quad(lambda x: np.abs(harmonic_oscillator(x, n, m, omega, hbar))**2, -0.5, 0.5))\n",
    "    print(f\"The probability to find a particle between |x|<0.5 is {np.around(prob[0], 3)} for energy level n={n}\")\n",
    "    \n",
    "for ax in [ax1, ax2]:\n",
    "    ax.plot(x, m*omega**2*x**2/2, label=r\"V(x)\")\n",
    "    ax.set_xlim(-4, 5.5)\n",
    "    ax.set_yticks([hbar*omega*(i +1/2) for i in range(7)])\n",
    "    ax.set_yticklabels([r\"$\\frac{\"+f\"{i}\"+\"}{2}\\hbar \\omega$\" if i%2!=0 else f\"{int(i/2)}\"+r\"$\\hbar \\omega$\" for i in range(1,8)])\n",
    "    ax.set_xlabel(r\"$x$\")\n",
    "    ax.set_ylabel(r\"$E_n$\")\n",
    "    ax.legend(loc=\"best\")\n",
    "    \n",
    "print([r\"$\\frac{1}{2}\\hbar \\omega$\" for i in range(7)])\n",
    "-np.diff(quad(lambda x: np.abs(harmonic_oscillator(x, 0, m, omega, hbar))**2, -0.5, 0.5))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Uncertainties"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from uncertainties import ufloat\n",
    "import uncertainties.unumpy as unp"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Data points are always measured with an error. To properly calculate uncertainties of function using measured values with error one uses error propagation. `uncertainties` is a python library to automate error propagation. A single value with error can be described with an `ufloat`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = ufloat(1, 0.2)\n",
    "b = ufloat(2, 0.1)\n",
    "print(a, a+b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "c = ufloat(1, 0.2)\n",
    "print(a - a, a - c)\n",
    "a == c"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`uncertainties.unumpy` is an extension for using uncertainties with of numpy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.array([2,1,2,2])\n",
    "xerr = np.array([0.5, 0.4, 0.4, 0.45])\n",
    "\n",
    "data = unp.uarray(x, xerr)\n",
    "print(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For retrieving the values or unvertainties you can use the functions `nominal_values` and `std_devs`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "noms(data), stds(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For using `uncertainties` on predefined numpy functions you should use the unumpy versions e.g. `unp.exp, unp.cos`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#np.cos(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "unp.cos(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Argparse"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import argparse"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "parser = argparse.ArgumentParser()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can add positional arguments that have to be given during execution of script. You can add information to the requested arguments for users by using the argument `help=`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "parser.add_argument(\"particle\")\n",
    "parser.add_argument(\"mass\", help=\"add mass of particle you want to parse\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Run code with\n",
    "`python test_argparse.py electron 0.511`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Adding optional arguments."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "parser.add_argument(\"-v\", \"--verbose\", help=\"An argument for verbosity is expected\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`python test_argparse.py electron 0.511 -v True`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "parser.add_argument(\"-m\", help=\"No argument is expected\", action=\"store_true\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also specify the input type."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "parser.add_argument(\"-integer\", type=int)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can retrieve the parsed argument via `args = parser.parse_args()`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`print(f\"A {args.particle} has a mass of {mass}MeV\")`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sys"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you want to execute your code only partially `sys.exit()` can be useful to interrupt the execution of your script."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### pathlib\n",
    "`pathlib` is a python standard library that can be used to operate on directories, paths, ...\n",
    "It is a more object-oriented version of the `os` module as paths a created as objects rather than simple strings.\n",
    "See [here](https://docs.python.org/3/library/pathlib.html) for `pathlib` documentation and the corresponding `os` implementation. A documentation for `os` can be found [here](https://docs.python.org/3/library/os.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can get access to the current working directory with the `cwd()` method. This method can be directly accessed from the `Path` class without creating a class object. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "path = Path.cwd()\n",
    "print(path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Path(\"./build/\").exists()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Directories can be created/deleted with the `mkdir()` and `rmdir()` methods. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "build = Path(\"./build/\")\n",
    "if build.exists():\n",
    "    print(\"Path build exists!\")\n",
    "    build.rmdir()\n",
    "else:\n",
    "    print(\"Path does not exist!\")\n",
    "\n",
    "build.exists()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "build.mkdir()\n",
    "build.exists()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same can be done for files with `touch()` and `unlink()`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "file = Path('test.txt')\n",
    "file.touch()\n",
    "print(file.exists() and file.is_file())\n",
    "file.unlink()\n",
    "print(file.exists())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can check the type of the path with the `is_file()`and `is_dir()`, ... methods. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(build.is_file(), build.is_dir(), build.is_mount(), build.is_symlink())\n",
    "print(Path(\"build\").exists(), Path(\"build\").is_dir())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Returning a sorted list of paths in directory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "[str(i) for i in list(sorted(Path(\".\").glob(\"*.txt\")))]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can build paths by concatenating subpaths with `joinpath()`. This does not changed initial path."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_in_build = build.joinpath(\"test\")\n",
    "print(test_in_build, build)\n",
    "print(build.joinpath(\"test\", \"test_in_test\", \"test_in_test_in_test\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Paths can be renamed with `rename()`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if Path(\"test.txt\").exists():\n",
    "    Path(\"test.txt\").unlink()\n",
    "if Path(\"test2.txt\").exists():\n",
    "    Path(\"test2.txt\").unlink()\n",
    "    \n",
    "Path(\"test.txt\").touch()\n",
    "print([str(i) for i in list(sorted(Path(\".\").glob(\"*.txt\")))])\n",
    "if Path(\"test.txt\").exists():\n",
    "    print(\"Path exists.\")\n",
    "    Path(\"test.txt\").rename(Path(\"test2.txt\"))\n",
    "\n",
    "Path(\"test.txt\").exists()\n",
    "print([str(i) for i in list(sorted(Path(\".\").glob(\"*.txt\")))])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise:\n",
    "1.Check your directory for the existence of a `build` directory and create such a directory if possible"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if not Path(\"build\").exists():\n",
    "    Path(\"build\").mkdir()\n",
    "    print(\"created build directory!\")\n",
    "else:\n",
    "    print(\"build directory does already exists!\")"
   ]
  }
 ],
 "metadata": {
  "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.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
