{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ae7613c6-67fe-4e2e-bf6e-ba4adbeec39d",
   "metadata": {},
   "source": [
    "# Les tableaux `numpy.array` \n",
    "\n",
    "Le module `numpy` permet de manipuler les tableaux de données, données qui ont toutes le même type numérique. Le nombre de dimension est variable. Ce module est particulièrement optimisé et est au centre de tous les modules de calculs scientifiques en `python`. Il faut donc connaitre ce module et savoir utiliser la structure `numpy.array`. \n",
    "\n",
    "La syntaxe introduite dans `numpy` est devenue une référence et est utilisée dans les autres modules tels que `pytorch` ou `tensorflow`. Ces modules spécialisés dans le deep learning ont recodé les tableaux (appelés `tensor`) pour pouvoir être utilisés sur GPU (carte graphique) et faire du calcul intensif. Ce n'est pas le cas des `numpy.array`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "68ea36d9-9ff8-4a7d-849a-a6601327914f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.443426Z",
     "iopub.status.busy": "2022-11-28T13:35:32.443187Z",
     "iopub.status.idle": "2022-11-28T13:35:32.535919Z",
     "shell.execute_reply": "2022-11-28T13:35:32.534970Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.443369Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70479828-51f5-4af0-8d0f-2eb9094f0d91",
   "metadata": {},
   "source": [
    "## Création et propriétés"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a08d98c-e87f-4071-bb6a-5281c4ed61c5",
   "metadata": {},
   "source": [
    "Création à partir d'une liste de listes. Sans option supplémentaire le type est détecté automatiquement."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "80e6659d-b472-4606-9746-3fe79b6b4601",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:21:46.121675Z",
     "start_time": "2022-02-16T12:21:46.118888Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.538793Z",
     "iopub.status.busy": "2022-11-28T13:35:32.538382Z",
     "iopub.status.idle": "2022-11-28T13:35:32.544564Z",
     "shell.execute_reply": "2022-11-28T13:35:32.543781Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.538763Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[8 3 2 4]\n",
      " [5 1 6 0]\n",
      " [9 7 4 1]]\n"
     ]
    }
   ],
   "source": [
    "a = np.array([[8,3,2,4], [5,1,6,0], [9,7,4,1]])\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8df67147-27b5-4ea3-84f0-c3a7e67f3f57",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.546151Z",
     "iopub.status.busy": "2022-11-28T13:35:32.545642Z",
     "iopub.status.idle": "2022-11-28T13:35:32.551287Z",
     "shell.execute_reply": "2022-11-28T13:35:32.550371Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.546120Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "L'objet a est de type: <class 'numpy.ndarray'>\n",
      "L'appel a[0] vaut [8 3 2 4] et est de type <class 'numpy.ndarray'>\n",
      "L'appel a[0,0] vaut 8 et est de type <class 'numpy.int64'>\n"
     ]
    }
   ],
   "source": [
    "print(\"L'objet a est de type:\", type(a))\n",
    "print(f\"L'appel a[0] vaut {a[0]} et est de type\", type(a[0]))\n",
    "print(f\"L'appel a[0,0] vaut {a[0,0]} et est de type\", type(a[0,0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2e05bbd-4210-4363-aa00-859acdb4d9df",
   "metadata": {},
   "source": [
    "**Remarque:** le type entier utilisé dans `numpy` est le type `numpy.int64` c'est à dire un entier codé sur 64 bits et le nombre le type `int` par défaut de python."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2cb44531-049e-41ef-a0f2-2fa03123722e",
   "metadata": {},
   "source": [
    "Quelques champs qui informent sur la structure du tableau `a`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "44174c4e-9476-4afc-9ec6-b8066d543d6c",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:21:46.127147Z",
     "start_time": "2022-02-16T12:21:46.123955Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.553087Z",
     "iopub.status.busy": "2022-11-28T13:35:32.552693Z",
     "iopub.status.idle": "2022-11-28T13:35:32.558180Z",
     "shell.execute_reply": "2022-11-28T13:35:32.557300Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.553055Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dimension: 2\n",
      "Taille: 12\n",
      "Forme: (3, 4)\n",
      "Types des éléments: int64\n"
     ]
    }
   ],
   "source": [
    "print(\"Dimension:\", a.ndim)\n",
    "print(\"Taille:\", a.size)     # attention len(a) = 3\n",
    "print(\"Forme:\", a.shape)\n",
    "print(\"Types des éléments:\", a.dtype) # type des éléments"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d446063d-ec42-4c66-8a22-a0144dec8157",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:22.638843Z",
     "start_time": "2022-02-16T12:22:22.633935Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.559885Z",
     "iopub.status.busy": "2022-11-28T13:35:32.559480Z",
     "iopub.status.idle": "2022-11-28T13:35:32.571143Z",
     "shell.execute_reply": "2022-11-28T13:35:32.570227Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.559855Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.sum() == np.sum(a)       # on peut utiliser la méthode ou une fonction globale"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c06ffb70-d4d6-4471-8d17-71d2a47d2dda",
   "metadata": {},
   "source": [
    "Pour changer le type des éléments on peut utiliser la méthode `astype`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f4b04700-1b27-4071-a5d4-addf6058acde",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.574026Z",
     "iopub.status.busy": "2022-11-28T13:35:32.573132Z",
     "iopub.status.idle": "2022-11-28T13:35:32.582437Z",
     "shell.execute_reply": "2022-11-28T13:35:32.580495Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.573987Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[8.+0.j, 3.+0.j, 2.+0.j, 4.+0.j],\n",
       "       [5.+0.j, 1.+0.j, 6.+0.j, 0.+0.j],\n",
       "       [9.+0.j, 7.+0.j, 4.+0.j, 1.+0.j]])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.astype('complex')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4dea6622-9f4a-4cde-8703-1d86a5d4e4ef",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:34.398240Z",
     "start_time": "2022-02-16T12:22:34.393545Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.587857Z",
     "iopub.status.busy": "2022-11-28T13:35:32.587487Z",
     "iopub.status.idle": "2022-11-28T13:35:32.594862Z",
     "shell.execute_reply": "2022-11-28T13:35:32.592872Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.587816Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[8.0, 3.0, 2.0, 4.0], [5.0, 1.0, 6.0, 0.0], [9.0, 7.0, 4.0, 1.0]]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.astype('float').tolist()      # bien sûr on peut enchaîner les méthodes"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "701f4533-204f-4056-b0dd-5fbb21a9ab0f",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## Création à partir de fonctions `numpy`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "afa2e6bd-e1ac-43dc-b637-bab27db54813",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.596750Z",
     "iopub.status.busy": "2022-11-28T13:35:32.596242Z",
     "iopub.status.idle": "2022-11-28T13:35:32.606983Z",
     "shell.execute_reply": "2022-11-28T13:35:32.605698Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.596716Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.array([ i+1 for i in range(10) ])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "ca9f7597-7a33-40c4-9fa8-77ab2749eec1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.609008Z",
     "iopub.status.busy": "2022-11-28T13:35:32.608650Z",
     "iopub.status.idle": "2022-11-28T13:35:32.615965Z",
     "shell.execute_reply": "2022-11-28T13:35:32.614908Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.608980Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.array([ i+1 for i in range(10) ], dtype='float', ndmin=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "d0db30ec-d2c3-4ed2-992e-94c02b1a6f8a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:34.591549Z",
     "start_time": "2022-02-16T12:22:34.587348Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.618181Z",
     "iopub.status.busy": "2022-11-28T13:35:32.617556Z",
     "iopub.status.idle": "2022-11-28T13:35:32.625059Z",
     "shell.execute_reply": "2022-11-28T13:35:32.623896Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.618146Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([10, 12, 14, 16, 18])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.arange(10, 20, step=2)    # même syntaxe que range "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4fb67ad3-8017-41ff-9141-7c08d50f8e80",
   "metadata": {},
   "source": [
    "**Remarque:** pour la fonction `np.arange` on a effectivement création en mémoire de la plage de valeurs alors que `range` renvoie un objet abstrait itérable (pas de création mémoire). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "4c005d46-8047-44db-a971-2c44d1a4dead",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:34.694055Z",
     "start_time": "2022-02-16T12:22:34.690001Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.627461Z",
     "iopub.status.busy": "2022-11-28T13:35:32.626876Z",
     "iopub.status.idle": "2022-11-28T13:35:32.640513Z",
     "shell.execute_reply": "2022-11-28T13:35:32.639162Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.627426Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0., 0., 0., 0.],\n",
       "       [0., 0., 0., 0.]])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.zeros((2, 4))             # de même il y a np.ones"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f15efbf-4438-423d-a086-6b7abe2b8ee4",
   "metadata": {},
   "source": [
    "La matrice indicatrice s'obtient par la méthode `eye`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "34e1a3a8-a2ec-4b7a-83b0-5e9b8af9cba9",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:34.793632Z",
     "start_time": "2022-02-16T12:22:34.790142Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.642700Z",
     "iopub.status.busy": "2022-11-28T13:35:32.642196Z",
     "iopub.status.idle": "2022-11-28T13:35:32.655589Z",
     "shell.execute_reply": "2022-11-28T13:35:32.653838Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.642665Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1., 0., 0.],\n",
       "       [0., 1., 0.],\n",
       "       [0., 0., 1.]])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.eye(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "2b0f995d-32f3-4639-82f0-1bb71cb45d2a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:34.892995Z",
     "start_time": "2022-02-16T12:22:34.889345Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.658470Z",
     "iopub.status.busy": "2022-11-28T13:35:32.657827Z",
     "iopub.status.idle": "2022-11-28T13:35:32.665969Z",
     "shell.execute_reply": "2022-11-28T13:35:32.664581Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.658433Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1., 0., 0.],\n",
       "       [0., 2., 0.],\n",
       "       [0., 0., 3.]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.diag([1., 2, 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "0425777e-b892-4d44-b47c-9d61c29e858b",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:34.995243Z",
     "start_time": "2022-02-16T12:22:34.991015Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.667661Z",
     "iopub.status.busy": "2022-11-28T13:35:32.667259Z",
     "iopub.status.idle": "2022-11-28T13:35:32.675529Z",
     "shell.execute_reply": "2022-11-28T13:35:32.674415Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.667639Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.linspace(0, 1, num=6)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b72e3eb-88f1-4f95-8aba-dba5881a397b",
   "metadata": {},
   "source": [
    "Il faut toujours consuler l'aide disponible. Par exemple consulter la documentation de la fonction `np.asarray`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f93b7552-5f20-436d-b729-7d641830a0b7",
   "metadata": {},
   "source": [
    "## Dimensions et axes"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae23df67-a007-45be-8da5-c23676eb3768",
   "metadata": {},
   "source": [
    "En `numpy` les tableaux multidimensionnels sont contruits en utilisant la représentation en ligne (row-major order, cf. [page wikipedia](https://en.wikipedia.org/wiki/Row-_and_column-major_order)). \n",
    "\n",
    "Ainsi un tableau de dimension 1 peut s'identifier comme un vecteur ligne.\n",
    "\n",
    "Une matrice (dimension 2) peut se voir comme un tableau de lignes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "2f4dcfd0-f1e9-46b9-bd29-e51ebf840cb8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.677213Z",
     "iopub.status.busy": "2022-11-28T13:35:32.676716Z",
     "iopub.status.idle": "2022-11-28T13:35:32.683480Z",
     "shell.execute_reply": "2022-11-28T13:35:32.682389Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.677191Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "une vecteur ligne:  [ 1.  4. 10.]\n",
      "une matrice:  [[8. 3. 2.]\n",
      " [5. 1. 6.]]\n"
     ]
    }
   ],
   "source": [
    "u = np.array([1., 4, 10])\n",
    "a = np.array([[8., 3, 2], [5, 1., 6]])\n",
    "print(\"une vecteur ligne: \", u)\n",
    "print(\"une matrice: \", a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "ac186314-322b-44a0-a557-9ccbbaf767a6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.686419Z",
     "iopub.status.busy": "2022-11-28T13:35:32.685397Z",
     "iopub.status.idle": "2022-11-28T13:35:32.692682Z",
     "shell.execute_reply": "2022-11-28T13:35:32.691866Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.686381Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dtype('float64')"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "u.dtype"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "23bb506f-bf47-4ea0-8b9a-b18d42f130cb",
   "metadata": {},
   "source": [
    "Le vecteur ligne `u` a 1 seule dimension, 1 seul axe (`axis`) de taille 3. \n",
    "\n",
    "La matrice `a` a 2 dimensions, 2 axes. Le premier axe (`axis 0`) est de taille 2 et le deuxième axe est de taille 3."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "f497899c-01bd-4f31-8b35-ea2db365087b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.694141Z",
     "iopub.status.busy": "2022-11-28T13:35:32.693665Z",
     "iopub.status.idle": "2022-11-28T13:35:32.699701Z",
     "shell.execute_reply": "2022-11-28T13:35:32.699050Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.694120Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.0"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a[0, 1] # on accède à l'élément d'indice 0 sur le 1er axe et et d'indice 1 sur le 2ème axe"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d3cfebca-5fde-4fa1-a9c8-42ac014a5941",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## Accès aux éléments\n",
    "![indexing](img/numpy_indexing.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9eb3da2-9884-4752-9237-ed1110ebd861",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "![fancing indexing](img/numpy_fancy_indexing.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d690644-8ea1-4cc2-9f59-f4000373f37d",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## Modification, transformation"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0591c78-efdf-4bb5-91e9-a214d2067c6b",
   "metadata": {},
   "source": [
    "- La méthode `reshape` renvoie **une vue** du tableau qui l'appelle et ce tableau n'est pas modifié. \n",
    "\n",
    "- La méthode `resize` modifie le tableau (change la forme) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "7d9106fe-4001-4a57-ab04-9244058e2672",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:35.302829Z",
     "start_time": "2022-02-16T12:22:35.299005Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.701231Z",
     "iopub.status.busy": "2022-11-28T13:35:32.700758Z",
     "iopub.status.idle": "2022-11-28T13:35:32.709000Z",
     "shell.execute_reply": "2022-11-28T13:35:32.707120Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.701208Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: [0 1 2 3 4 5 6 7]\n",
      "b: [[0 1 2 3]\n",
      " [4 5 6 7]]\n"
     ]
    }
   ],
   "source": [
    "a = np.arange(8)\n",
    "b = a.reshape((2,4))    # renvoie **une vue de a**, a et b partagent les mêmes données\n",
    "print(\"a:\", a)\n",
    "print(\"b:\", b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "7d19bb13-71fd-4d08-875a-098ea990a575",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:35.402647Z",
     "start_time": "2022-02-16T12:22:35.399146Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.711581Z",
     "iopub.status.busy": "2022-11-28T13:35:32.711197Z",
     "iopub.status.idle": "2022-11-28T13:35:32.718806Z",
     "shell.execute_reply": "2022-11-28T13:35:32.717678Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.711552Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: [  0   1   2   3   4 100   6   7]\n"
     ]
    }
   ],
   "source": [
    "b[1,1] = 100            # on modifie b: l'élément 5 devient 100\n",
    "print(\"a:\", a)          # on affiche a "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "8f081b37-ce0d-4eb8-a19a-4efe3def648e",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:35.504261Z",
     "start_time": "2022-02-16T12:22:35.500534Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.721386Z",
     "iopub.status.busy": "2022-11-28T13:35:32.720961Z",
     "iopub.status.idle": "2022-11-28T13:35:32.726386Z",
     "shell.execute_reply": "2022-11-28T13:35:32.725490Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.721354Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b: [[  0   1]\n",
      " [  2   3]\n",
      " [  4 100]\n",
      " [  6   7]]\n",
      "a: [  0   1   2   3   4 100   6   7]\n"
     ]
    }
   ],
   "source": [
    "b.resize((4,2))         # modification in-place\n",
    "print(\"b:\", b)\n",
    "print(\"a:\", a)          # a n'est pas modifié"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57f2a2a2-0e43-4d7d-a821-85f8edb7662b",
   "metadata": {},
   "source": [
    "Pour ajouter un axe, par exemple pour transformer un vecteur ligne en vecteur colonne on peut utiliser la méthode `reshape` ou ajouter un axe avec la syntaxe `[:, np.newaxis]` ou `[:, None]`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "f7cab511-2c3d-4ed8-9217-0323deb9a303",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.728296Z",
     "iopub.status.busy": "2022-11-28T13:35:32.727716Z",
     "iopub.status.idle": "2022-11-28T13:35:32.733622Z",
     "shell.execute_reply": "2022-11-28T13:35:32.732926Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.728261Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  0,   1,   2,   3,   4, 100,   6,   7])"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.T"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "080ef848-0fac-4af5-9773-1d6a9843ea83",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:35.604055Z",
     "start_time": "2022-02-16T12:22:35.600206Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.744094Z",
     "iopub.status.busy": "2022-11-28T13:35:32.743647Z",
     "iopub.status.idle": "2022-11-28T13:35:32.751343Z",
     "shell.execute_reply": "2022-11-28T13:35:32.750245Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.744060Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[  0],\n",
       "       [  1],\n",
       "       [  2],\n",
       "       [  3],\n",
       "       [  4],\n",
       "       [100],\n",
       "       [  6],\n",
       "       [  7]])"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.reshape(8, 1) \n",
    "a[:, np.newaxis]        # un vecteur ligne transformé en vecteur colonne"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "6f1a932a-a4ea-4e20-bda5-1cacbdb70041",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.753518Z",
     "iopub.status.busy": "2022-11-28T13:35:32.752816Z",
     "iopub.status.idle": "2022-11-28T13:35:32.760371Z",
     "shell.execute_reply": "2022-11-28T13:35:32.759640Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.753482Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[  0],\n",
       "       [  1],\n",
       "       [  2],\n",
       "       [  3],\n",
       "       [  4],\n",
       "       [100],\n",
       "       [  6],\n",
       "       [  7]])"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a[:, None]         # le mot clé np.newaxis est équivalent à None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "65888a1b-d3cc-4771-b36d-390a0d598de5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.761845Z",
     "iopub.status.busy": "2022-11-28T13:35:32.761469Z",
     "iopub.status.idle": "2022-11-28T13:35:32.766540Z",
     "shell.execute_reply": "2022-11-28T13:35:32.765856Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.761822Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 0\n",
      "1 1\n",
      "2 2\n",
      "3 3\n",
      "4 4\n",
      "5 100\n",
      "6 6\n",
      "7 7\n"
     ]
    }
   ],
   "source": [
    "for i,x in enumerate(b.flat):   # b.flat version \"vue\" applatie de b \n",
    "    print(i, x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "fe3ef57e-e70b-4721-825d-45ad728e85cd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.768025Z",
     "iopub.status.busy": "2022-11-28T13:35:32.767755Z",
     "iopub.status.idle": "2022-11-28T13:35:32.773011Z",
     "shell.execute_reply": "2022-11-28T13:35:32.771768Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.768006Z"
    }
   },
   "outputs": [],
   "source": [
    "c = b.flatten()   # une copie applatie (tous les axes sont écrasés)\n",
    "c[1] = 50"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "6f26fb92-8b29-47dd-9426-16ff44808052",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.775270Z",
     "iopub.status.busy": "2022-11-28T13:35:32.774518Z",
     "iopub.status.idle": "2022-11-28T13:35:32.781088Z",
     "shell.execute_reply": "2022-11-28T13:35:32.780076Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.775213Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  0,  50,   2,   3,   4, 100,   6,   7])"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "04b9ea5f-cfa2-4af7-a675-ca916b9f3ebf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.782358Z",
     "iopub.status.busy": "2022-11-28T13:35:32.781963Z",
     "iopub.status.idle": "2022-11-28T13:35:32.788108Z",
     "shell.execute_reply": "2022-11-28T13:35:32.786332Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.782334Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[  0,   1],\n",
       "       [  2,   3],\n",
       "       [  4, 100],\n",
       "       [  6,   7]])"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "1c9fa225-e5f9-4a90-89cb-a1f0885f88bc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.790762Z",
     "iopub.status.busy": "2022-11-28T13:35:32.790012Z",
     "iopub.status.idle": "2022-11-28T13:35:32.796772Z",
     "shell.execute_reply": "2022-11-28T13:35:32.796057Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.790720Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  0,   1,   2,   3,   4, 100,   6,   7])"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47f2fd0f-6008-4984-9f2b-637cd72edf7d",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## Opérations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "bfc8d489-ed57-4160-8c09-830523ad5ddf",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:35.772452Z",
     "start_time": "2022-02-16T12:22:35.768848Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.798276Z",
     "iopub.status.busy": "2022-11-28T13:35:32.797814Z",
     "iopub.status.idle": "2022-11-28T13:35:32.805272Z",
     "shell.execute_reply": "2022-11-28T13:35:32.804294Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.798250Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "moyenne:  15.375\n",
      "variance:  1027.984375\n",
      "variance sans biais:  1174.8392857142858\n"
     ]
    }
   ],
   "source": [
    "print(\"moyenne: \", np.mean(a))              # moyenne\n",
    "print(\"variance: \", np.var(a))               # version biaisée voir documentation\n",
    "print(\"variance sans biais: \", np.var(a, ddof=1))       # version sans biais"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "24b32173-a519-4c2a-9555-1b01167bdaae",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:35.876692Z",
     "start_time": "2022-02-16T12:22:35.871063Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.807463Z",
     "iopub.status.busy": "2022-11-28T13:35:32.807072Z",
     "iopub.status.idle": "2022-11-28T13:35:32.810860Z",
     "shell.execute_reply": "2022-11-28T13:35:32.809976Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.807440Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import math\n",
    "# math.sqrt(a)    # erreur si on execute cette cellule  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "c1435236-fca0-462f-b6cb-5f876d4b24d6",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:35.975049Z",
     "start_time": "2022-02-16T12:22:35.971275Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.812310Z",
     "iopub.status.busy": "2022-11-28T13:35:32.811761Z",
     "iopub.status.idle": "2022-11-28T13:35:32.817965Z",
     "shell.execute_reply": "2022-11-28T13:35:32.817278Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.812273Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.        ,  1.        ,  1.41421356,  1.73205081,  2.        ,\n",
       "       10.        ,  2.44948974,  2.64575131])"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.sqrt(a)              # toujours utiliser les fonctions numpy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "bd2988ad-11e7-4c5d-a29b-5e54e417ee0f",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:36.076041Z",
     "start_time": "2022-02-16T12:22:36.072942Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.819053Z",
     "iopub.status.busy": "2022-11-28T13:35:32.818741Z",
     "iopub.status.idle": "2022-11-28T13:35:32.824623Z",
     "shell.execute_reply": "2022-11-28T13:35:32.823960Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.819028Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  4,   4,   4,   4,   4, 100,   6,   7])"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.maximum(a, 4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "16d25d61-26c3-44d5-b8e8-cd76ad97f077",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:36.177213Z",
     "start_time": "2022-02-16T12:22:36.173864Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.826001Z",
     "iopub.status.busy": "2022-11-28T13:35:32.825729Z",
     "iopub.status.idle": "2022-11-28T13:35:32.830215Z",
     "shell.execute_reply": "2022-11-28T13:35:32.829463Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.825984Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "100"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.max(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80fae2cd-9ebf-4550-a597-e3468e0a1129",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## Opérations par axe, option `axis`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec6c10b0-f82f-49ec-bd71-69b53c769ac2",
   "metadata": {},
   "source": [
    "Les opérations par axe sont très importantes et doivent être bien comprises. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "47909d20-56c0-4a6e-8704-1fa5e31dab74",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:36.349687Z",
     "start_time": "2022-02-16T12:22:36.344906Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.831700Z",
     "iopub.status.busy": "2022-11-28T13:35:32.831354Z",
     "iopub.status.idle": "2022-11-28T13:35:32.838652Z",
     "shell.execute_reply": "2022-11-28T13:35:32.837057Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.831676Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4 lignes (axe 0) et 2 colonnes (axe 1)\n",
      "[[  0   1]\n",
      " [  2   3]\n",
      " [  4 100]\n",
      " [  6   7]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[  0,   1],\n",
       "       [  2,   3],\n",
       "       [  4, 100],\n",
       "       [  6,   7]])"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(f\"{b.shape[0]} lignes (axe 0) et {b.shape[1]} colonnes (axe 1)\")\n",
    "print(b)\n",
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "cad4d7d5-84e0-46d4-b84d-fdecfa1794cd",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:36.447926Z",
     "start_time": "2022-02-16T12:22:36.444482Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.840234Z",
     "iopub.status.busy": "2022-11-28T13:35:32.839793Z",
     "iopub.status.idle": "2022-11-28T13:35:32.846331Z",
     "shell.execute_reply": "2022-11-28T13:35:32.845263Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.840187Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "123"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.sum(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "785d0f92-7e75-4dec-9fac-84dbae606c72",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:36.551434Z",
     "start_time": "2022-02-16T12:22:36.547647Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.848171Z",
     "iopub.status.busy": "2022-11-28T13:35:32.847834Z",
     "iopub.status.idle": "2022-11-28T13:35:32.855018Z",
     "shell.execute_reply": "2022-11-28T13:35:32.853703Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.848147Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 12, 111])"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.sum(b, axis = 0)       # agit sur l'axe 0: on réduit l'axe 0 -> la somme des lignes "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "6fabb2c6-2929-4da6-b230-6d214abf62dc",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:36.652747Z",
     "start_time": "2022-02-16T12:22:36.649604Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.856806Z",
     "iopub.status.busy": "2022-11-28T13:35:32.856271Z",
     "iopub.status.idle": "2022-11-28T13:35:32.863718Z",
     "shell.execute_reply": "2022-11-28T13:35:32.862302Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.856782Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  1,   5, 104,  13])"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.sum(b, axis = 1)       # agit sur l'axe 1: on réduit l'axe 1 -> la somme des colonnes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "057af59b-b1f2-4292-b1ae-35857c94b1c0",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:36.751647Z",
     "start_time": "2022-02-16T12:22:36.746765Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.865851Z",
     "iopub.status.busy": "2022-11-28T13:35:32.865203Z",
     "iopub.status.idle": "2022-11-28T13:35:32.874782Z",
     "shell.execute_reply": "2022-11-28T13:35:32.873550Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.865797Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  6, 100])"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.max(b, axis = 0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "526b03da-03f5-43d1-a8df-4cff4f219736",
   "metadata": {
    "tags": [
     "Exercice"
    ]
   },
   "source": [
    "### Exercice \n",
    "\n",
    "On veut calculer \n",
    "\n",
    "$$\n",
    "\\sum_{k=1}^n k^2\n",
    "$$ \n",
    "\n",
    "pour différentes valeurs de $n$, $n=10,100,1000,10000,100000$. \n",
    "\n",
    "- Ecrire 2 implémentations différentes: l'une un python sans `numpy` et l'autre en utilisant `numpy`.\n",
    "- Comparer les temps de calculs de ces 2 versions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "0dd52a3f-402f-40f2-8274-7ff84e6de7ad",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.876576Z",
     "iopub.status.busy": "2022-11-28T13:35:32.876192Z",
     "iopub.status.idle": "2022-11-28T13:35:32.881445Z",
     "shell.execute_reply": "2022-11-28T13:35:32.880625Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.876553Z"
    },
    "tags": [
     "Correction",
     "hide-output"
    ]
   },
   "outputs": [],
   "source": [
    "def sum_squares_python(n):\n",
    "    result = 0\n",
    "    for k in range(n+1):\n",
    "        result += k**2\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "19ac880e-afac-4370-9422-061a169de402",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.883449Z",
     "iopub.status.busy": "2022-11-28T13:35:32.882967Z",
     "iopub.status.idle": "2022-11-28T13:35:32.889214Z",
     "shell.execute_reply": "2022-11-28T13:35:32.886342Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.883426Z"
    },
    "tags": [
     "Correction",
     "hide-output"
    ]
   },
   "outputs": [],
   "source": [
    "def sum_squares_numpy(n):\n",
    "    z = np.arange(n+1)\n",
    "    result = np.sum(z**2)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "482c4304-0d44-41df-8ed4-ff2a4b3700c7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:32.892123Z",
     "iopub.status.busy": "2022-11-28T13:35:32.891607Z",
     "iopub.status.idle": "2022-11-28T13:35:51.720585Z",
     "shell.execute_reply": "2022-11-28T13:35:51.719494Z",
     "shell.execute_reply.started": "2022-11-28T13:35:32.892060Z"
    },
    "tags": [
     "Correction",
     "hide-output"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "799 ns ± 10.7 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)\n",
      "10\n",
      "3.25 µs ± 41.5 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
      "100\n",
      "28.1 µs ± 880 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n",
      "1000\n",
      "286 µs ± 5.3 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n",
      "10000\n",
      "2.88 ms ± 39.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n",
      "100000\n",
      "28.5 ms ± 243 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
     ]
    }
   ],
   "source": [
    "#for n in 10**np.arange(5):\n",
    "#    print(n)\n",
    "#    %timeit sum_squares_python(n)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "d0179db5-8767-4f39-bc74-107057eb4a17",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:35:51.721850Z",
     "iopub.status.busy": "2022-11-28T13:35:51.721581Z",
     "iopub.status.idle": "2022-11-28T13:36:26.080383Z",
     "shell.execute_reply": "2022-11-28T13:36:26.079255Z",
     "shell.execute_reply.started": "2022-11-28T13:35:51.721828Z"
    },
    "tags": [
     "Correction",
     "hide-output"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "4.74 µs ± 15.8 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
      "10\n",
      "4.95 µs ± 152 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
      "100\n",
      "4.99 µs ± 43.9 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
      "1000\n",
      "6.11 µs ± 64.3 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
      "10000\n",
      "13.2 µs ± 777 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n",
      "100000\n",
      "83.2 µs ± 3.01 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "#for n in 10**np.arange(5):\n",
    "#    print(n)\n",
    "#    %timeit sum_squares_numpy(n)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f9344c4-a5b9-459d-9c50-fbdc507c3e95",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## Broadcasting\n",
    "\n",
    "Mécanisme très utilisé qu'il faut connaitre pour une bonne utilisation! Attention il peut y avoir des pièges."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "30bb9023-cc11-447e-9c22-7ea751eb07b1",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:36.919880Z",
     "start_time": "2022-02-16T12:22:36.916611Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.082011Z",
     "iopub.status.busy": "2022-11-28T13:36:26.081564Z",
     "iopub.status.idle": "2022-11-28T13:36:26.086573Z",
     "shell.execute_reply": "2022-11-28T13:36:26.085877Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.081986Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a = [ 0 10 20 30]\n",
      "b = [0 1 2]\n"
     ]
    }
   ],
   "source": [
    "a = 10 * np.arange(4)    # ou bien np.arange(31, step=10)\n",
    "b = np.arange(3)\n",
    "print(\"a =\", a)\n",
    "print(\"b =\", b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "4163bead-5df1-46ef-a62a-d3fbb8f8a210",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:37.021825Z",
     "start_time": "2022-02-16T12:22:37.018774Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.087600Z",
     "iopub.status.busy": "2022-11-28T13:36:26.087357Z",
     "iopub.status.idle": "2022-11-28T13:36:26.091434Z",
     "shell.execute_reply": "2022-11-28T13:36:26.090843Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.087579Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "c = [[ 0]\n",
      " [10]\n",
      " [20]\n",
      " [30]]\n"
     ]
    }
   ],
   "source": [
    "c = a[:, np.newaxis]\n",
    "print(\"c =\", c)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "f6eae127-b029-430e-9b7a-4eee4de2e43c",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-02-16T12:22:37.123734Z",
     "start_time": "2022-02-16T12:22:37.120863Z"
    },
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.092778Z",
     "iopub.status.busy": "2022-11-28T13:36:26.092549Z",
     "iopub.status.idle": "2022-11-28T13:36:26.097555Z",
     "shell.execute_reply": "2022-11-28T13:36:26.096893Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.092760Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2]\n",
      " [10 11 12]\n",
      " [20 21 22]\n",
      " [30 31 32]]\n"
     ]
    }
   ],
   "source": [
    "print(c + b)        # broadcasting"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd414074-27c6-498f-854e-0512983030bf",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "![broadcasting](img/numpy_broadcasting.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28b85dfb-b002-4d70-a731-e904564c0947",
   "metadata": {},
   "source": [
    "Pour une utilisation avancée du broadcasting (par exemple pour appliquer une fonction qui n'est pas un opérateur arithmétique classique) on peut utiliser `np.broadcast`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "f796d503-22df-42db-99b4-be9d3908cb23",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.098878Z",
     "iopub.status.busy": "2022-11-28T13:36:26.098608Z",
     "iopub.status.idle": "2022-11-28T13:36:26.103088Z",
     "shell.execute_reply": "2022-11-28T13:36:26.102304Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.098860Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "x = np.array([[1], [2], [3]])\n",
    "y = np.array([40, 50, 60])\n",
    "b = np.broadcast(x, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "beeb36d0-af06-420c-81ac-00070e099d34",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.104462Z",
     "iopub.status.busy": "2022-11-28T13:36:26.104112Z",
     "iopub.status.idle": "2022-11-28T13:36:26.107932Z",
     "shell.execute_reply": "2022-11-28T13:36:26.107356Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.104439Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 40\n",
      "1 50\n",
      "1 60\n",
      "2 40\n",
      "2 50\n",
      "2 60\n",
      "3 40\n",
      "3 50\n",
      "3 60\n"
     ]
    }
   ],
   "source": [
    "for u, v in b:\n",
    "    print(u, v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "6065acec-1ade-4d24-875e-21d2e4299f05",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.109245Z",
     "iopub.status.busy": "2022-11-28T13:36:26.108944Z",
     "iopub.status.idle": "2022-11-28T13:36:26.115163Z",
     "shell.execute_reply": "2022-11-28T13:36:26.114306Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.109226Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[41., 51., 61.],\n",
       "       [42., 52., 62.],\n",
       "       [43., 53., 63.]])"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = np.broadcast(x, y)\n",
    "out = np.empty(b.shape)\n",
    "out.flat = [u+v for (u,v) in b]\n",
    "out"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12b46cd5-6466-495a-a4fb-35808fe76b40",
   "metadata": {
    "tags": [
     "Exercice"
    ]
   },
   "source": [
    "### Exercice\n",
    "\n",
    "- Construire la matrice \n",
    "\n",
    "$$\n",
    "A = \\begin{pmatrix} 0 & 0 & 0 \\\\\n",
    "10 & 10 & 10 \\\\\n",
    "20 & 20 & 20 \\\\\n",
    "30 & 30 & 30\n",
    "\\end{pmatrix}\n",
    "$$ \n",
    "\n",
    "de plusieurs façons différentes:\n",
    "    1. construire un vecteur ligne (1 seul axe) $u= \\begin{pmatrix} 0 & 10 & 20 & 30 \\end{pmatrix}$ puis le convertir en vecteur colonne $v = u^\\top$ en utilisant la méthode `reshape` ou l'ajout d'un axe via `np.newaxis`, et appeler la fonction `np.repeat`\n",
    "    2. construire directement le vecteur colonne $v$ via l'option `ndim=2` et la fonction `np.repeat`\n",
    "    3. construire le vecteur ligne $u$ puis utiliser `np.repeat` et ensuite la méthode `reshape`.\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "1cd7a56a-4833-4f75-9998-9d5d4a8431dd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.116670Z",
     "iopub.status.busy": "2022-11-28T13:36:26.116274Z",
     "iopub.status.idle": "2022-11-28T13:36:26.124600Z",
     "shell.execute_reply": "2022-11-28T13:36:26.123836Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.116648Z"
    },
    "tags": [
     "Correction",
     "hide-output"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0,  0,  0],\n",
       "       [10, 10, 10],\n",
       "       [20, 20, 20],\n",
       "       [30, 30, 30]])"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# construction 1. \n",
    "u = np.arange(4)*10  # vecteur ligne (1 seul axe 0)\n",
    "\n",
    "# deux options pour transformer ce vecteur ligne en vecteur colonne:\n",
    "u.reshape((4, 1))  # on change la forme avec la méthode reshape\n",
    "u[:, None]         # on ajoute un axe supplémentaire avec cette syntaxe \n",
    "# pour plus de lisibilité on peut remplacer le mot-clé None par np.newaxis (c'est pareil!)\n",
    "v = u[:, np.newaxis]   # écriture un peu plus explicite\n",
    "\n",
    "# une fois qu'on a un vecteur colonne, on fait une répétition\n",
    "np.repeat(v, 3, axis=1) # on agit sur l'axe 1 pour faire la répétition\n",
    "\n",
    "# construction 2.\n",
    "# il est possible d'utiliser l'option ndmin=2\n",
    "v = np.array(np.arange(0, 40, step=10), ndmin=2)\n",
    "v = np.array([i for i in range(0,40,10)], ndmin=2)\n",
    "np.repeat(v, 3, axis=1) # on agit sur l'axe 1 pour faire la répétition\n",
    "\n",
    "# construction 3.\n",
    "u = np.arange(0, 40, step=10)\n",
    "np.repeat(u, 3).reshape((4, 3))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c3c9672-e74b-4228-9093-0cc7502452fb",
   "metadata": {},
   "source": [
    "## Algèbre linéaire"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79c4e9c0-ba41-40fd-aaea-cfdbdbad7c40",
   "metadata": {},
   "source": [
    "En bref:\n",
    "\n",
    "- `inner` pour calculer le produit scalaire, on peut aussi utiliser `dot` ou `vdot`\n",
    "- `outer` pour produit tensoriel entre 2 vecteurs\n",
    "- opérateur `@` pour un produit matriciel, ou la fonction `matmul`\n",
    "- pour la transposée d'une matrice `a` on utilise `a.T`\n",
    "- `einsum` fonction très générale et très optimisée, lire la documention...\n",
    "\n",
    "Les transformations sont dans le sous-module `linalg` de `numpy`\n",
    "\n",
    "- `cholesky` factorisation de Cholesky\n",
    "- `qr` décomposition QR\n",
    "- `svd` décomposition en valeurs singulières\n",
    "- `inv` inverse une matrice \n",
    "- `solve` résolution d'un système linéaire \n",
    "\n",
    "Pour en savoir plus il y a:\n",
    "\n",
    "- [Documentation officielle](https://numpy.org/doc/stable/reference/routines.linalg.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "ab5b6ad1-ceef-4ab8-8c42-d65a1da3d1f2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.126005Z",
     "iopub.status.busy": "2022-11-28T13:36:26.125575Z",
     "iopub.status.idle": "2022-11-28T13:36:26.129667Z",
     "shell.execute_reply": "2022-11-28T13:36:26.128870Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.125982Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['LinAlgError', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_umath_linalg', 'cholesky', 'cond', 'det', 'eig', 'eigh', 'eigvals', 'eigvalsh', 'inv', 'linalg', 'lstsq', 'matrix_power', 'matrix_rank', 'multi_dot', 'norm', 'pinv', 'qr', 'slogdet', 'solve', 'svd', 'tensorinv', 'tensorsolve', 'test']\n"
     ]
    }
   ],
   "source": [
    "print(dir(np.linalg))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "0e6b2807-21d6-47c7-98ad-9bde2c29181d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.131706Z",
     "iopub.status.busy": "2022-11-28T13:36:26.130954Z",
     "iopub.status.idle": "2022-11-28T13:36:26.136058Z",
     "shell.execute_reply": "2022-11-28T13:36:26.135447Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.131666Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "u = [0 1 2 3] \n",
      "v = [2 3 4 5]\n"
     ]
    }
   ],
   "source": [
    "u = np.arange(4)\n",
    "v = 2+u\n",
    "print(\"u =\", u, \"\\nv =\", v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "f0e5203e-2780-4a8c-818d-717b215c63d1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.137525Z",
     "iopub.status.busy": "2022-11-28T13:36:26.137222Z",
     "iopub.status.idle": "2022-11-28T13:36:26.141809Z",
     "shell.execute_reply": "2022-11-28T13:36:26.141160Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.137507Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.inner(u, v) == np.sum(u*v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "6f95bd7f-72be-414d-ab30-4b16ce7692cb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.142925Z",
     "iopub.status.busy": "2022-11-28T13:36:26.142724Z",
     "iopub.status.idle": "2022-11-28T13:36:26.147306Z",
     "shell.execute_reply": "2022-11-28T13:36:26.146213Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.142907Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  0  0  0]\n",
      " [ 2  3  4  5]\n",
      " [ 4  6  8 10]\n",
      " [ 6  9 12 15]]\n"
     ]
    }
   ],
   "source": [
    "A = np.outer(u, v)\n",
    "print(A)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "d981733b-7a7f-4307-a839-2a48e961f1c7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.148657Z",
     "iopub.status.busy": "2022-11-28T13:36:26.148229Z",
     "iopub.status.idle": "2022-11-28T13:36:26.153145Z",
     "shell.execute_reply": "2022-11-28T13:36:26.152495Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.148634Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "attention au produit: \n",
      " [[ 0  0  0  0]\n",
      " [ 0  3  8 15]\n",
      " [ 0  6 16 30]\n",
      " [ 0  9 24 45]]\n",
      "voici le produit matrice-vecteur: \n",
      " [ 0 26 52 78]\n"
     ]
    }
   ],
   "source": [
    "print(\"attention au produit: \\n\", A * u)\n",
    "print(\"voici le produit matrice-vecteur: \\n\", A @ u)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "e54fdab6-3f33-4db4-97f5-f0cf39cdd44f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-11-28T13:36:26.154714Z",
     "iopub.status.busy": "2022-11-28T13:36:26.154402Z",
     "iopub.status.idle": "2022-11-28T13:36:26.159163Z",
     "shell.execute_reply": "2022-11-28T13:36:26.158404Z",
     "shell.execute_reply.started": "2022-11-28T13:36:26.154697Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([28, 42, 56, 70])"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A.T @ u"
   ]
  }
 ],
 "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.11.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
