{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "<img width=\"800px\" src=\"../fidle/img/00-Fidle-header-01.svg\"></img>\n",
    "\n",
    "# <!-- TITLE --> [NP1] - A short introduction to Numpy\n",
    "<!-- DESC --> Numpy is an essential tool for the Scientific Python.\n",
    "<!-- AUTHOR : Jean-Luc Parouty (CNRS/SIMaP) -->\n",
    "\n",
    "## Objectives :\n",
    " - Comprendre les grands principes de Numpy et son potentiel\n",
    "\n",
    "Note : This notebook is strongly inspired by the UGA Python Introduction Course  \n",
    "See : **https://gricad-gitlab.univ-grenoble-alpes.fr/python-uga/py-training-2017**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Step 1 - Numpy the beginning\n",
    "\n",
    "Code using `numpy` usually starts with the import statement"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "NumPy provides the type `np.ndarray`. Such array are multidimensionnal sequences of homogeneous elements. They can be created for example with the commands:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([10. , 12.5, 15. , 17.5, 20. ])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# from a list\n",
    "l = [10.0, 12.5, 15.0, 17.5, 20.0]\n",
    "np.array(l)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 6.93990061e-310,  6.95333088e-310, -1.90019324e+120,\n",
       "        6.93987701e-310])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# fast but the values can be anything\n",
    "np.empty(4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0., 0., 0., 0., 0., 0.],\n",
       "       [0., 0., 0., 0., 0., 0.]])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# slower than np.empty but the values are all 0.\n",
    "np.zeros([2, 6])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(2, 3, 4) 24 float64\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[[1., 1., 1., 1.],\n",
       "        [1., 1., 1., 1.],\n",
       "        [1., 1., 1., 1.]],\n",
       "\n",
       "       [[1., 1., 1., 1.],\n",
       "        [1., 1., 1., 1.],\n",
       "        [1., 1., 1., 1.]]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# multidimensional array\n",
    "a = np.ones([2, 3, 4])\n",
    "print(a.shape, a.size, a.dtype)\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 2, 3])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# like range but produce 1D numpy array\n",
    "np.arange(4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0., 1., 2., 3.])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# np.arange can produce arrays of floats\n",
    "np.arange(4.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([10. , 12.5, 15. , 17.5, 20. ])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# another convenient function to generate 1D arrays\n",
    "np.linspace(10, 20, 5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A NumPy array can be easily converted to a Python list."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[10.0, 12.5, 15.0, 17.5, 20.0]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = np.linspace(10, 20 ,5)\n",
    "list(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[10.0, 12.5, 15.0, 17.5, 20.0]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Or even better\n",
    "a.tolist()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Step 2 - Access elements\n",
    "\n",
    "Elements in a `numpy` array can be accessed using indexing and slicing in any dimension. It also offers the same functionalities available in Fortan or Matlab.\n",
    "\n",
    "### 2.1 - Indexes and slices\n",
    "For example, we can create an array `A` and perform any kind of selection operations on it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.14726334, 0.90799321, 0.67130094, 0.23978162, 0.96444415],\n",
       "       [0.26039418, 0.06135763, 0.35856793, 0.73366941, 0.50698925],\n",
       "       [0.39557097, 0.55950866, 0.70056205, 0.65344863, 0.90891062],\n",
       "       [0.19049184, 0.56355734, 0.71701494, 0.66035889, 0.06400119]])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A = np.random.random([4, 5])\n",
    "A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.26039417830707656"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Get the element from second line, first column\n",
    "A[1, 0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.14726334, 0.90799321, 0.67130094, 0.23978162, 0.96444415],\n",
       "       [0.26039418, 0.06135763, 0.35856793, 0.73366941, 0.50698925]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Get the first two lines\n",
    "A[:2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.96444415, 0.50698925, 0.90891062, 0.06400119])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Get the last column\n",
    "A[:, -1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.14726334, 0.67130094, 0.96444415],\n",
       "       [0.26039418, 0.35856793, 0.50698925]])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Get the first two lines and the columns with an even index\n",
    "A[:2, ::2]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### 2.2 -  Using a mask to select elements validating a condition:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[False  True  True False  True]\n",
      " [False False False  True  True]\n",
      " [False  True  True  True  True]\n",
      " [False  True  True  True False]]\n",
      "[0.90799321 0.67130094 0.96444415 0.73366941 0.50698925 0.55950866\n",
      " 0.70056205 0.65344863 0.90891062 0.56355734 0.71701494 0.66035889]\n"
     ]
    }
   ],
   "source": [
    "cond = A > 0.5\n",
    "print(cond)\n",
    "print(A[cond])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The mask is in fact a particular case of the advanced indexing capabilities provided by NumPy. For example, it is even possible to use lists for indexing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.14726334 0.90799321 0.67130094 0.23978162 0.96444415]\n",
      " [0.26039418 0.06135763 0.35856793 0.73366941 0.50698925]\n",
      " [0.39557097 0.55950866 0.70056205 0.65344863 0.90891062]\n",
      " [0.19049184 0.56355734 0.71701494 0.66035889 0.06400119]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[0.14726334, 0.90799321, 0.96444415],\n",
       "       [0.26039418, 0.06135763, 0.50698925],\n",
       "       [0.39557097, 0.55950866, 0.90891062],\n",
       "       [0.19049184, 0.56355734, 0.06400119]])"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Selecting only particular columns\n",
    "print(A)\n",
    "A[:, [0, 1, 4]]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Step 3 -  Perform array manipulations\n",
    "### 3.1 - Apply arithmetic operations to whole arrays (element-wise):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[26.49431985, 34.90438372, 32.16365436, 27.45531142, 35.57459401],\n",
       "       [27.67174691, 25.61734103, 28.71425022, 32.87496493, 30.32693058],\n",
       "       [29.11218606, 30.9081365 , 32.49640767, 31.96148136, 34.91522467],\n",
       "       [26.94120557, 30.95317031, 32.68425986, 32.03966276, 25.6441081 ]])"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(A+5)**2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 - Apply functions element-wise:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1.15865904, 2.47934201, 1.95678132, 1.27097157, 2.62332907],\n",
       "       [1.29744141, 1.0632791 , 1.43127825, 2.08270892, 1.66028496],\n",
       "       [1.48523197, 1.74981253, 2.01488485, 1.92215822, 2.48161763],\n",
       "       [1.2098445 , 1.75691133, 2.04830976, 1.93548684, 1.06609367]])"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.exp(A) # With numpy arrays, use the functions from numpy !"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.3 - Setting parts of arrays"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.         0.90799321 0.67130094 0.23978162 0.96444415]\n",
      " [0.         0.06135763 0.35856793 0.73366941 0.50698925]\n",
      " [0.         0.55950866 0.70056205 0.65344863 0.90891062]\n",
      " [0.         0.56355734 0.71701494 0.66035889 0.06400119]]\n"
     ]
    }
   ],
   "source": [
    "A[:, 0] = 0.\n",
    "print(A)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.          1.10132983  1.48964487  4.17046144  1.03686668]\n",
      " [ 0.         16.29789234  2.78887186  1.36301171  1.97242842]\n",
      " [ 0.          1.78728245  1.42742531  1.53034219  1.1002182 ]\n",
      " [ 0.          1.77444232  1.39467107  1.51432807 15.62470834]]\n"
     ]
    }
   ],
   "source": [
    "# BONUS: Safe element-wise inverse with masks\n",
    "cond = (A != 0)\n",
    "A[cond] = 1./A[cond]\n",
    "print(A)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Step 4 - Attributes and methods of `np.ndarray` (see the [doc](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html#numpy.ndarray))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T               all             any             argmax          argmin          argpartition    \n",
      "argsort         astype          base            byteswap        choose          clip            \n",
      "compress        conj            conjugate       copy            ctypes          cumprod         \n",
      "cumsum          data            diagonal        dot             dtype           dump            \n",
      "dumps           fill            flags           flat            flatten         getfield        \n",
      "imag            item            itemset         itemsize        max             mean            \n",
      "min             nbytes          ndim            newbyteorder    nonzero         partition       \n",
      "prod            ptp             put             ravel           real            repeat          \n",
      "reshape         resize          round           searchsorted    setfield        setflags        \n",
      "shape           size            sort            squeeze         std             strides         \n",
      "sum             swapaxes        take            tobytes         tofile          tolist          \n",
      "tostring        trace           transpose       var             view            "
     ]
    }
   ],
   "source": [
    "for i,v in enumerate([s for s in dir(A) if not s.startswith('__')]):\n",
    "    print(f'{v:16}', end='')\n",
    "    if (i+1) % 6 == 0 :print('')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.          1.10132983  1.48964487  4.17046144  1.03686668]\n",
      " [ 0.         16.29789234  2.78887186  1.36301171  1.97242842]\n",
      " [ 0.          1.78728245  1.42742531  1.53034219  1.1002182 ]\n",
      " [ 0.          1.77444232  1.39467107  1.51432807 15.62470834]]\n",
      "Mean value 2.818696254398785\n",
      "Mean line [0.         5.24023674 1.77515328 2.14453585 4.93355541]\n",
      "Mean column [1.55966056 4.48444087 1.16905363 4.06162996]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# Ex1: Get the mean through different dimensions\n",
    "\n",
    "print(A)\n",
    "print('Mean value',  A.mean())\n",
    "print('Mean line',   A.mean(axis=0))\n",
    "print('Mean column', A.mean(axis=1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.          1.10132983  1.48964487  4.17046144  1.03686668]\n",
      " [ 0.         16.29789234  2.78887186  1.36301171  1.97242842]\n",
      " [ 0.          1.78728245  1.42742531  1.53034219  1.1002182 ]\n",
      " [ 0.          1.77444232  1.39467107  1.51432807 15.62470834]]\n",
      "(4, 5)\n",
      "[ 0.          1.10132983  1.48964487  4.17046144  1.03686668  0.\n",
      " 16.29789234  2.78887186  1.36301171  1.97242842  0.          1.78728245\n",
      "  1.42742531  1.53034219  1.1002182   0.          1.77444232  1.39467107\n",
      "  1.51432807 15.62470834] (20,)\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# Ex2: Convert a 2D array in 1D keeping all elements\n",
    "\n",
    "print(A)\n",
    "print(A.shape)\n",
    "A_flat = A.flatten()\n",
    "print(A_flat, A_flat.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.1 - Remark: dot product"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]\n",
      "385.0\n"
     ]
    }
   ],
   "source": [
    "b = np.linspace(0, 10, 11)\n",
    "c = b @ b\n",
    "# before 3.5:\n",
    "# c = b.dot(b)\n",
    "print(b)\n",
    "print(c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.2 -  For Matlab users\n",
    "\n",
    "|     ` `       | Matlab | Numpy |\n",
    "| ------------- | ------ | ----- |\n",
    "| element wise  |  `.*`  |  `*`  |\n",
    "|  dot product  |  `*`   |  `@`  |"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`numpy` arrays can also be sorted, even when they are composed of complex data if the type of the columns are explicitly stated with `dtypes`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 4.3 -  NumPy and SciPy sub-packages:\n",
    "\n",
    "We already saw `numpy.random` to generate `numpy` arrays filled with random values. This submodule also provides functions related to distributions (Poisson, gaussian, etc.) and permutations."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To perform linear algebra with dense matrices, we can use the submodule `numpy.linalg`. For instance, in order to compute the determinant of a random matrix, we use the method `det`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.33277412 0.18065847 0.10352574 0.48095553 0.97748505]\n",
      " [0.20756676 0.33166777 0.00808192 0.18868636 0.1722338 ]\n",
      " [0.94092977 0.21755657 0.52045179 0.45008315 0.1751413 ]\n",
      " [0.27404121 0.53531168 0.41209088 0.22503687 0.50026306]\n",
      " [0.23077516 0.99886616 0.74286904 0.40849416 0.57970741]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "-0.026288777656342802"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A = np.random.random([5,5])\n",
    "print(A)\n",
    "np.linalg.det(A)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.33166777 0.00808192]\n",
      " [0.21755657 0.52045179]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[ 3.0460928 , -0.04730175],\n",
       "       [-1.27331197,  1.94118039]])"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "squared_subA = A[1:3, 1:3]\n",
    "print(squared_subA)\n",
    "np.linalg.inv(squared_subA)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### 4.4 -  Introduction to Pandas: Python Data Analysis Library\n",
    "\n",
    "Pandas is an open source library providing high-performance, easy-to-use data structures and data analysis tools for Python.\n",
    "\n",
    "[Pandas tutorial](https://pandas.pydata.org/pandas-docs/stable/10min.html)\n",
    "[Grenoble Python Working Session](https://github.com/iutzeler/Pres_Pandas/)\n",
    "[Pandas for SQL Users](https://hackernoon.com/pandas-cheatsheet-for-sql-people-part-1-2976894acd0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "<img width=\"80px\" src=\"../fidle/img/00-Fidle-logo-01.svg\"></img>"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Diaporama",
  "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.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}