mirror of
https://github.com/ArthurDanjou/ArtStudies.git
synced 2026-02-01 14:29:34 +01:00
Refactor code for improved readability and consistency across notebooks
- Standardized spacing around operators and function arguments in TP7_Kmeans.ipynb and neural_network.ipynb. - Enhanced the formatting of model building and training code in neural_network.ipynb for better clarity. - Updated the pyproject.toml to remove a specific TensorFlow version and added linting configuration for Ruff. - Improved comments and organization in the code to facilitate easier understanding and maintenance.
This commit is contained in:
@@ -1 +1 @@
|
|||||||
3.12
|
3.13
|
||||||
|
|||||||
@@ -76,24 +76,40 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"u = np.array([1,2,3,4,5])\n",
|
"u = np.array([1, 2, 3, 4, 5])\n",
|
||||||
"v = np.array([[1,2,3,4,5]])\n",
|
"v = np.array([[1, 2, 3, 4, 5]])\n",
|
||||||
"su=u.shape\n",
|
"su = u.shape\n",
|
||||||
"sv=v.shape\n",
|
"sv = v.shape\n",
|
||||||
"ut = np.transpose(u)\n",
|
"ut = np.transpose(u)\n",
|
||||||
"vt = np.transpose(v)\n",
|
"vt = np.transpose(v)\n",
|
||||||
"vt2 = np.array([[1],[2],[3],[4],[5]])\n",
|
"vt2 = np.array([[1], [2], [3], [4], [5]])\n",
|
||||||
"A = np.array([[1,2,0,0,0],[0,2,0,0,0],[0,0,3,0,0],[0,0,0,4,0],[0,0,0,0,5]])\n",
|
"A = np.array(\n",
|
||||||
"B = np.array([[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7],[4,5,6,7,8],[5,6,7,8,9]])\n",
|
" [\n",
|
||||||
"d=np.diag(A)\n",
|
" [1, 2, 0, 0, 0],\n",
|
||||||
"dd=np.array([np.diag(A)])\n",
|
" [0, 2, 0, 0, 0],\n",
|
||||||
"dt=np.transpose(d)\n",
|
" [0, 0, 3, 0, 0],\n",
|
||||||
"ddt=np.transpose(dd)\n",
|
" [0, 0, 0, 4, 0],\n",
|
||||||
"Ad=np.diag(np.diag(A))\n",
|
" [0, 0, 0, 0, 5],\n",
|
||||||
|
" ]\n",
|
||||||
|
")\n",
|
||||||
|
"B = np.array(\n",
|
||||||
|
" [\n",
|
||||||
|
" [1, 2, 3, 4, 5],\n",
|
||||||
|
" [2, 3, 4, 5, 6],\n",
|
||||||
|
" [3, 4, 5, 6, 7],\n",
|
||||||
|
" [4, 5, 6, 7, 8],\n",
|
||||||
|
" [5, 6, 7, 8, 9],\n",
|
||||||
|
" ]\n",
|
||||||
|
")\n",
|
||||||
|
"d = np.diag(A)\n",
|
||||||
|
"dd = np.array([np.diag(A)])\n",
|
||||||
|
"dt = np.transpose(d)\n",
|
||||||
|
"ddt = np.transpose(dd)\n",
|
||||||
|
"Ad = np.diag(np.diag(A))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(np.dot(np.linalg.inv(A), A))"
|
"print(np.dot(np.linalg.inv(A), A))"
|
||||||
]
|
]
|
||||||
@@ -138,11 +154,11 @@
|
|||||||
" x = 0 * b\n",
|
" x = 0 * b\n",
|
||||||
" n = len(b)\n",
|
" n = len(b)\n",
|
||||||
" if np.allclose(A, np.triu(A)):\n",
|
" if np.allclose(A, np.triu(A)):\n",
|
||||||
" for i in range(n-1, -1, -1):\n",
|
" for i in range(n - 1, -1, -1):\n",
|
||||||
" x[i] = (b[i] - np.dot(A[i,i+1:], x[i+1:])) / A[i,i]\n",
|
" x[i] = (b[i] - np.dot(A[i, i + 1 :], x[i + 1 :])) / A[i, i]\n",
|
||||||
" elif np.allclose(A, np.tril(A)):\n",
|
" elif np.allclose(A, np.tril(A)):\n",
|
||||||
" for i in range(n):\n",
|
" for i in range(n):\n",
|
||||||
" x[i] = (b[i] - np.dot(A[i,:i], x[:i])) / A[i,i]\n",
|
" x[i] = (b[i] - np.dot(A[i, :i], x[:i])) / A[i, i]\n",
|
||||||
" else:\n",
|
" else:\n",
|
||||||
" raise ValueError(\"A est ni triangulaire supérieure ni triangulaire inférieure\")\n",
|
" raise ValueError(\"A est ni triangulaire supérieure ni triangulaire inférieure\")\n",
|
||||||
" return x"
|
" return x"
|
||||||
@@ -171,7 +187,7 @@
|
|||||||
"b = np.dot(A, xe)\n",
|
"b = np.dot(A, xe)\n",
|
||||||
"x = remontee_descente(A, b)\n",
|
"x = remontee_descente(A, b)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(np.dot(x - xe, x-xe))"
|
"print(np.dot(x - xe, x - xe))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -263,9 +279,9 @@
|
|||||||
" U = A\n",
|
" U = A\n",
|
||||||
" n = len(A)\n",
|
" n = len(A)\n",
|
||||||
" for j in range(n):\n",
|
" for j in range(n):\n",
|
||||||
" for i in range(j+1, n):\n",
|
" for i in range(j + 1, n):\n",
|
||||||
" beta = U[i,j]/U[j,j]\n",
|
" beta = U[i, j] / U[j, j]\n",
|
||||||
" U[i,j:] = U[i,j:] - beta * U[j, j:]\n",
|
" U[i, j:] = U[i, j:] - beta * U[j, j:]\n",
|
||||||
" return U"
|
" return U"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -282,14 +298,16 @@
|
|||||||
" if n != m:\n",
|
" if n != m:\n",
|
||||||
" raise ValueError(\"Erreur de dimension : A doit etre carré\")\n",
|
" raise ValueError(\"Erreur de dimension : A doit etre carré\")\n",
|
||||||
" if n != b.size:\n",
|
" if n != b.size:\n",
|
||||||
" raise valueError(\"Erreur de dimension : le nombre de lignes de A doit être égal au nombr ede colonnes de b\")\n",
|
" raise valueError(\n",
|
||||||
" U = np.zeros((n, n+1))\n",
|
" \"Erreur de dimension : le nombre de lignes de A doit être égal au nombr ede colonnes de b\"\n",
|
||||||
|
" )\n",
|
||||||
|
" U = np.zeros((n, n + 1))\n",
|
||||||
" U = A\n",
|
" U = A\n",
|
||||||
" V = b\n",
|
" V = b\n",
|
||||||
" for j in range(n):\n",
|
" for j in range(n):\n",
|
||||||
" for i in range(j+1, n):\n",
|
" for i in range(j + 1, n):\n",
|
||||||
" beta = U[i,j]/U[j,j]\n",
|
" beta = U[i, j] / U[j, j]\n",
|
||||||
" U[i,j:] = U[i,j:] - beta * U[j, j:]\n",
|
" U[i, j:] = U[i, j:] - beta * U[j, j:]\n",
|
||||||
" V[i] = V[i] - beta * V[j]\n",
|
" V[i] = V[i] - beta * V[j]\n",
|
||||||
" return remontee_descente(U, V)"
|
" return remontee_descente(U, V)"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -9,9 +9,9 @@
|
|||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"%config InlineBackend.figure_format = 'retina'\n",
|
"%config InlineBackend.figure_format = 'retina'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"import numpy as np # pour les numpy array\n",
|
"import numpy as np # pour les numpy array\n",
|
||||||
"import matplotlib.pyplot as plt # librairie graphique\n",
|
"import matplotlib.pyplot as plt # librairie graphique\n",
|
||||||
"from scipy.integrate import odeint # seulement odeint"
|
"from scipy.integrate import odeint # seulement odeint"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -103,13 +103,14 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"# Initialisation des variables\n",
|
"# Initialisation des variables\n",
|
||||||
"T = 130\n",
|
"T = 130\n",
|
||||||
"t = np.arange(0, T+1)\n",
|
"t = np.arange(0, T + 1)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"K = 50 # capacité d'accueil maximale du milieu\n",
|
"K = 50 # capacité d'accueil maximale du milieu\n",
|
||||||
"K_star = 50 # capacité minimale pour maintenir l'espèce\n",
|
"K_star = 50 # capacité minimale pour maintenir l'espèce\n",
|
||||||
"r = 0.1 # taux de corissance de la capacité d'accueil du milieu.\n",
|
"r = 0.1 # taux de corissance de la capacité d'accueil du milieu.\n",
|
||||||
"t_fl = 30 # la find ed la période de formation.\n",
|
"t_fl = 30 # la find ed la période de formation.\n",
|
||||||
"K0 = 1 # Valeur initiale de la capacité d'accueil du milieu.\n",
|
"K0 = 1 # Valeur initiale de la capacité d'accueil du milieu.\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def C(t):\n",
|
"def C(t):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
@@ -117,11 +118,12 @@
|
|||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" return K_star + K / (1 + (K / K0 - 1) * np.exp(-r * (t - t_fl)))\n",
|
" return K_star + K / (1 + (K / K0 - 1) * np.exp(-r * (t - t_fl)))\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"# On trace le graphique de la solution exacte\n",
|
"# On trace le graphique de la solution exacte\n",
|
||||||
"plt.plot(t, C(t), label=\"C(t)\")\n",
|
"plt.plot(t, C(t), label=\"C(t)\")\n",
|
||||||
"plt.hlines(K_star, 0, T, linestyle='dotted', label=\"C = K*\", color='red')\n",
|
"plt.hlines(K_star, 0, T, linestyle=\"dotted\", label=\"C = K*\", color=\"red\")\n",
|
||||||
"plt.hlines(K + K_star, 0, T, linestyle='dotted', label=\"C = K + K*\", color='green')\n",
|
"plt.hlines(K + K_star, 0, T, linestyle=\"dotted\", label=\"C = K + K*\", color=\"green\")\n",
|
||||||
"plt.plot(t_fl, K0 + K_star, 'o', label=\"(t_fl, K0 + K*)\")\n",
|
"plt.plot(t_fl, K0 + K_star, \"o\", label=\"(t_fl, K0 + K*)\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.xlim(0, 130)\n",
|
"plt.xlim(0, 130)\n",
|
||||||
"plt.suptitle(\"Courbe de la solution exacte du problème\")\n",
|
"plt.suptitle(\"Courbe de la solution exacte du problème\")\n",
|
||||||
@@ -133,14 +135,16 @@
|
|||||||
"N0 = 10\n",
|
"N0 = 10\n",
|
||||||
"r_N = 0.2\n",
|
"r_N = 0.2\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def dN(N, t, C_sol):\n",
|
"def dN(N, t, C_sol):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Fonction calculant la dérivée de la solution approchée du problème à l'instant t dépendant de N(t) et de C(t)\n",
|
" Fonction calculant la dérivée de la solution approchée du problème à l'instant t dépendant de N(t) et de C(t)\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" return r_N * N * (1 - N / C_sol(t))\n",
|
" return r_N * N * (1 - N / C_sol(t))\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"t = np.linspace(0, T, 200)\n",
|
"t = np.linspace(0, T, 200)\n",
|
||||||
"N_sol = odeint(dN, N0, t, args=(C,)) # On calcule la solution a l'aide de odeint\n",
|
"N_sol = odeint(dN, N0, t, args=(C,)) # On calcule la solution a l'aide de odeint\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# On trace le graphique de la solution approchée en comparaison à la solution exacte\n",
|
"# On trace le graphique de la solution approchée en comparaison à la solution exacte\n",
|
||||||
"plt.plot(t, N_sol, label=\"Solution approchée\")\n",
|
"plt.plot(t, N_sol, label=\"Solution approchée\")\n",
|
||||||
@@ -219,42 +223,47 @@
|
|||||||
"T, N = 200, 100\n",
|
"T, N = 200, 100\n",
|
||||||
"H0, P0 = 1500, 500\n",
|
"H0, P0 = 1500, 500\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def F(X, t, a, b, c, d, p):\n",
|
"def F(X, t, a, b, c, d, p):\n",
|
||||||
" \"\"\"Fonction second membre pour le système\"\"\"\n",
|
" \"\"\"Fonction second membre pour le système\"\"\"\n",
|
||||||
" x, y = X\n",
|
" x, y = X\n",
|
||||||
" return np.array([x * (a - p - b*y), y * (-c - p + d*x)])\n",
|
" return np.array([x * (a - p - b * y), y * (-c - p + d * x)])\n",
|
||||||
"\n",
|
"\n",
|
||||||
"t = np.linspace(0, T, N+1)\n",
|
"\n",
|
||||||
"sardines, requins = np.meshgrid(\n",
|
"t = np.linspace(0, T, N + 1)\n",
|
||||||
" np.linspace(0.1, 3000, 20),\n",
|
"sardines, requins = np.meshgrid(np.linspace(0.1, 3000, 20), np.linspace(0.1, 4500, 30))\n",
|
||||||
" np.linspace(0.1, 4500, 30)\n",
|
|
||||||
")\n",
|
|
||||||
"fsardines = F((sardines, requins), t, a, b, c, d, 0)[0]\n",
|
"fsardines = F((sardines, requins), t, a, b, c, d, 0)[0]\n",
|
||||||
"frequins = F((sardines, requins), t, a, b, c, d, 0)[1]\n",
|
"frequins = F((sardines, requins), t, a, b, c, d, 0)[1]\n",
|
||||||
"n_sndmb = np.sqrt(fsardines**2 + frequins**2) \n",
|
"n_sndmb = np.sqrt(fsardines**2 + frequins**2)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# On crée une figure à trois graphiques\n",
|
"# On crée une figure à trois graphiques\n",
|
||||||
"fig = plt.figure(figsize=(12, 6))\n",
|
"fig = plt.figure(figsize=(12, 6))\n",
|
||||||
"ax = fig.add_subplot(1, 2, 2) # subplot pour le champ de vecteurs et le graphe sardines vs requins\n",
|
"ax = fig.add_subplot(\n",
|
||||||
"axr = fig.add_subplot(2, 2, 1) # subplot pour le graphe du nombre de requins en fonction du temps\n",
|
" 1, 2, 2\n",
|
||||||
"axs = fig.add_subplot(2, 2, 3) # subplot pour le graphe du nombre de sardines en fonction du temps \n",
|
") # subplot pour le champ de vecteurs et le graphe sardines vs requins\n",
|
||||||
"ax.quiver(sardines, requins, fsardines/n_sndmb, frequins/n_sndmb)\n",
|
"axr = fig.add_subplot(\n",
|
||||||
|
" 2, 2, 1\n",
|
||||||
|
") # subplot pour le graphe du nombre de requins en fonction du temps\n",
|
||||||
|
"axs = fig.add_subplot(\n",
|
||||||
|
" 2, 2, 3\n",
|
||||||
|
") # subplot pour le graphe du nombre de sardines en fonction du temps\n",
|
||||||
|
"ax.quiver(sardines, requins, fsardines / n_sndmb, frequins / n_sndmb)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"list_p = [0, 0.02, 0.04, 0.06]\n",
|
"list_p = [0, 0.02, 0.04, 0.06]\n",
|
||||||
"for k, pk in enumerate(list_p):\n",
|
"for k, pk in enumerate(list_p):\n",
|
||||||
" couleur = (0, k/len(list_p), 1-k/len(list_p))\n",
|
" couleur = (0, k / len(list_p), 1 - k / len(list_p))\n",
|
||||||
" X = odeint(F, np.array([H0, P0]), t, args=(a, b, c, d, pk))\n",
|
" X = odeint(F, np.array([H0, P0]), t, args=(a, b, c, d, pk))\n",
|
||||||
" \n",
|
"\n",
|
||||||
" # Tracer la courbe parametrée (H(t),P(t)) \n",
|
" # Tracer la courbe parametrée (H(t),P(t))\n",
|
||||||
" ax.plot(X[:, 0], X[:, 1], linewidth=2, color=couleur, label=f\"$p={pk}$\")\n",
|
" ax.plot(X[:, 0], X[:, 1], linewidth=2, color=couleur, label=f\"$p={pk}$\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
" # Tracer H en fonction du temps \n",
|
" # Tracer H en fonction du temps\n",
|
||||||
" axs.plot(t, X[:, 0], label=f\"Sardines pour p={pk}\", color=couleur)\n",
|
" axs.plot(t, X[:, 0], label=f\"Sardines pour p={pk}\", color=couleur)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" # Tracer P en fonction du temps\n",
|
" # Tracer P en fonction du temps\n",
|
||||||
" axr.plot(t, X[:, 1], label=f\"Requins pour p={pk}\", color=couleur)\n",
|
" axr.plot(t, X[:, 1], label=f\"Requins pour p={pk}\", color=couleur)\n",
|
||||||
" \n",
|
"\n",
|
||||||
"ax.axis('equal')\n",
|
"ax.axis(\"equal\")\n",
|
||||||
"ax.set_title(\"Champ de vecteur du problème de Lotka-Volterra\")\n",
|
"ax.set_title(\"Champ de vecteur du problème de Lotka-Volterra\")\n",
|
||||||
"ax.set_xlabel(\"Sardines\")\n",
|
"ax.set_xlabel(\"Sardines\")\n",
|
||||||
"ax.set_ylabel(\"Requins\")\n",
|
"ax.set_ylabel(\"Requins\")\n",
|
||||||
@@ -266,8 +275,8 @@
|
|||||||
"axs.set_xlabel(\"Temps t\")\n",
|
"axs.set_xlabel(\"Temps t\")\n",
|
||||||
"axs.set_ylabel(\"Sardines\")\n",
|
"axs.set_ylabel(\"Sardines\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"axs.set_title('Evolution des sardines')\n",
|
"axs.set_title(\"Evolution des sardines\")\n",
|
||||||
"axr.set_title('Evolution des requins')\n",
|
"axr.set_title(\"Evolution des requins\")\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -309,11 +318,11 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"def crank_nicolson(y0, T, N, r):\n",
|
"def crank_nicolson(y0, T, N, r):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" schéma de Crank-Nicolson pour le modèle de Malthus \n",
|
" schéma de Crank-Nicolson pour le modèle de Malthus\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Parameters\n",
|
" Parameters\n",
|
||||||
" ----------\n",
|
" ----------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" y0: float\n",
|
" y0: float\n",
|
||||||
" donnée initiale\n",
|
" donnée initiale\n",
|
||||||
" T: float\n",
|
" T: float\n",
|
||||||
@@ -325,34 +334,35 @@
|
|||||||
"\n",
|
"\n",
|
||||||
" Returns\n",
|
" Returns\n",
|
||||||
" -------\n",
|
" -------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" t: ndarray\n",
|
" t: ndarray\n",
|
||||||
" les instants où la solution approchée est calculée\n",
|
" les instants où la solution approchée est calculée\n",
|
||||||
" y: ndarray\n",
|
" y: ndarray\n",
|
||||||
" les valeurs de la solution approchée par le theta-schema\n",
|
" les valeurs de la solution approchée par le theta-schema\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" \n",
|
"\n",
|
||||||
" dt = T / N\n",
|
" dt = T / N\n",
|
||||||
" t = np.zeros(N+1)\n",
|
" t = np.zeros(N + 1)\n",
|
||||||
" y = np.zeros(N+1)\n",
|
" y = np.zeros(N + 1)\n",
|
||||||
" tk, yk = 0, y0\n",
|
" tk, yk = 0, y0\n",
|
||||||
" y[0] = yk\n",
|
" y[0] = yk\n",
|
||||||
" \n",
|
"\n",
|
||||||
" for n in range(N):\n",
|
" for n in range(N):\n",
|
||||||
" tk += dt\n",
|
" tk += dt\n",
|
||||||
" yk *= (2 + dt * r) / (2 - dt * r)\n",
|
" yk *= (2 + dt * r) / (2 - dt * r)\n",
|
||||||
" y[n+1] = yk\n",
|
" y[n + 1] = yk\n",
|
||||||
" t[n+1] = tk\n",
|
" t[n + 1] = tk\n",
|
||||||
" \n",
|
"\n",
|
||||||
" return t, y\n",
|
" return t, y\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def euler_explicit(y0, T, N, r):\n",
|
"def euler_explicit(y0, T, N, r):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" schéma de d'Euler pour le modèle de Malthus \n",
|
" schéma de d'Euler pour le modèle de Malthus\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Parameters\n",
|
" Parameters\n",
|
||||||
" ----------\n",
|
" ----------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" y0: float\n",
|
" y0: float\n",
|
||||||
" donnée initiale\n",
|
" donnée initiale\n",
|
||||||
" T: float\n",
|
" T: float\n",
|
||||||
@@ -364,29 +374,30 @@
|
|||||||
"\n",
|
"\n",
|
||||||
" Returns\n",
|
" Returns\n",
|
||||||
" -------\n",
|
" -------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" t: ndarray\n",
|
" t: ndarray\n",
|
||||||
" les instants où la solution approchée est calculée\n",
|
" les instants où la solution approchée est calculée\n",
|
||||||
" y: ndarray\n",
|
" y: ndarray\n",
|
||||||
" les valeurs de la solution approchée par le theta-schema\n",
|
" les valeurs de la solution approchée par le theta-schema\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" dt = T / N\n",
|
" dt = T / N\n",
|
||||||
" t = np.zeros(N+1)\n",
|
" t = np.zeros(N + 1)\n",
|
||||||
" y = np.zeros(N+1)\n",
|
" y = np.zeros(N + 1)\n",
|
||||||
" tk, yk = 0, y0\n",
|
" tk, yk = 0, y0\n",
|
||||||
" y[0] = yk\n",
|
" y[0] = yk\n",
|
||||||
" \n",
|
"\n",
|
||||||
" for n in range(N):\n",
|
" for n in range(N):\n",
|
||||||
" tk += dt\n",
|
" tk += dt\n",
|
||||||
" yk += dt * r * yk\n",
|
" yk += dt * r * yk\n",
|
||||||
" y[n+1] = yk\n",
|
" y[n + 1] = yk\n",
|
||||||
" t[n+1] = tk\n",
|
" t[n + 1] = tk\n",
|
||||||
" \n",
|
"\n",
|
||||||
" return t, y\n",
|
" return t, y\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def solution_exacte(t):\n",
|
"def solution_exacte(t):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Fonction calculant la solution exacte du modèle de Malthus à l'instant t \n",
|
" Fonction calculant la solution exacte du modèle de Malthus à l'instant t\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" return y0 * np.exp(r * t)"
|
" return y0 * np.exp(r * t)"
|
||||||
]
|
]
|
||||||
@@ -436,23 +447,25 @@
|
|||||||
"# Schéma d'Euler explicite\n",
|
"# Schéma d'Euler explicite\n",
|
||||||
"ax = fig.add_subplot(1, 2, 1)\n",
|
"ax = fig.add_subplot(1, 2, 1)\n",
|
||||||
"for n in liste_N:\n",
|
"for n in liste_N:\n",
|
||||||
" t, y = euler_explicit(y0, T, n, r) # On calcule la fonction Euler pour chaque n\n",
|
" t, y = euler_explicit(y0, T, n, r) # On calcule la fonction Euler pour chaque n\n",
|
||||||
" ax.scatter(t, y, label=f\"Solution approchée pour N={n}\")\n",
|
" ax.scatter(t, y, label=f\"Solution approchée pour N={n}\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
"ax.plot(t_exact, solution_exacte(t_exact), label='Solution exacte')\n",
|
"ax.plot(t_exact, solution_exacte(t_exact), label=\"Solution exacte\")\n",
|
||||||
"ax.legend()\n",
|
"ax.legend()\n",
|
||||||
"ax.axis('equal')\n",
|
"ax.axis(\"equal\")\n",
|
||||||
"ax.set_title(\"Schéma d'Euler explicite\")\n",
|
"ax.set_title(\"Schéma d'Euler explicite\")\n",
|
||||||
"ax.set_xlabel(\"Temps t\")\n",
|
"ax.set_xlabel(\"Temps t\")\n",
|
||||||
"ax.set_ylabel(\"y\")\n",
|
"ax.set_ylabel(\"y\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Schéma de Crank-Nicolson\n",
|
"# Schéma de Crank-Nicolson\n",
|
||||||
"ax = fig.add_subplot(1, 2, 2)\n",
|
"ax = fig.add_subplot(1, 2, 2)\n",
|
||||||
"for n in liste_N:\n",
|
"for n in liste_N:\n",
|
||||||
" t, y = crank_nicolson(y0, T, n, r) # On calcule la fonction Crank-Nicolson pour chaque n\n",
|
" t, y = crank_nicolson(\n",
|
||||||
|
" y0, T, n, r\n",
|
||||||
|
" ) # On calcule la fonction Crank-Nicolson pour chaque n\n",
|
||||||
" ax.scatter(t, y, label=f\"Solution approchée pour N={n}\")\n",
|
" ax.scatter(t, y, label=f\"Solution approchée pour N={n}\")\n",
|
||||||
"ax.plot(t_exact, solution_exacte(t_exact), label='Solution exacte')\n",
|
"ax.plot(t_exact, solution_exacte(t_exact), label=\"Solution exacte\")\n",
|
||||||
"ax.legend()\n",
|
"ax.legend()\n",
|
||||||
"ax.set_title(\"Schéma de Crank-Nicolson\")\n",
|
"ax.set_title(\"Schéma de Crank-Nicolson\")\n",
|
||||||
"ax.set_xlabel(\"Temps t\")\n",
|
"ax.set_xlabel(\"Temps t\")\n",
|
||||||
@@ -504,7 +517,7 @@
|
|||||||
" t, sol_appr = crank_nicolson(y0, T, n, r)\n",
|
" t, sol_appr = crank_nicolson(y0, T, n, r)\n",
|
||||||
" sol_ex = solution_exacte(t)\n",
|
" sol_ex = solution_exacte(t)\n",
|
||||||
" erreur = np.max(np.abs(sol_appr - sol_ex))\n",
|
" erreur = np.max(np.abs(sol_appr - sol_ex))\n",
|
||||||
" #erreur = np.linalg.norm(sol_appr - sol_ex, np.inf)\n",
|
" # erreur = np.linalg.norm(sol_appr - sol_ex, np.inf)\n",
|
||||||
" print(f\"Delta_t = {T / N:10.3e}, e = {erreur:10.3e}\")\n",
|
" print(f\"Delta_t = {T / N:10.3e}, e = {erreur:10.3e}\")\n",
|
||||||
" liste_erreur[k] = erreur\n",
|
" liste_erreur[k] = erreur\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -514,7 +527,7 @@
|
|||||||
"ax.scatter(liste_delta, liste_erreur, color=\"black\")\n",
|
"ax.scatter(liste_delta, liste_erreur, color=\"black\")\n",
|
||||||
"for p in [0.5, 1, 2]:\n",
|
"for p in [0.5, 1, 2]:\n",
|
||||||
" C = liste_erreur[-1] / (liste_delta[-1] ** p)\n",
|
" C = liste_erreur[-1] / (liste_delta[-1] ** p)\n",
|
||||||
" plt.plot(liste_delta, C * liste_delta ** p, label=f\"$p={p}$\")\n",
|
" plt.plot(liste_delta, C * liste_delta**p, label=f\"$p={p}$\")\n",
|
||||||
"ax.set_title(\"Erreur du schéma de Crank-Nicolson\")\n",
|
"ax.set_title(\"Erreur du schéma de Crank-Nicolson\")\n",
|
||||||
"ax.set_xlabel(r\"$\\Delta t$\")\n",
|
"ax.set_xlabel(r\"$\\Delta t$\")\n",
|
||||||
"ax.set_ylabel(r\"$e(\\Delta t)$\")\n",
|
"ax.set_ylabel(r\"$e(\\Delta t)$\")\n",
|
||||||
|
|||||||
@@ -153,22 +153,27 @@
|
|||||||
"def M(x):\n",
|
"def M(x):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Retourne la matrice du système (2)\n",
|
" Retourne la matrice du système (2)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Parameters\n",
|
" Parameters\n",
|
||||||
" ----------\n",
|
" ----------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" x: ndarray\n",
|
" x: ndarray\n",
|
||||||
" vecteurs contenant les valeurs [x0, x1, ..., xN]\n",
|
" vecteurs contenant les valeurs [x0, x1, ..., xN]\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Returns\n",
|
" Returns\n",
|
||||||
" -------\n",
|
" -------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" out: ndarray\n",
|
" out: ndarray\n",
|
||||||
" matrice du système (2)\n",
|
" matrice du système (2)\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" h = x[1:] - x[:-1] # x[i+1] - x[i]\n",
|
" h = x[1:] - x[:-1] # x[i+1] - x[i]\n",
|
||||||
" return np.diag(2*(1/h[:-1] + 1/h[1:])) + np.diag(1/h[1:-1], k=-1) + np.diag(1/h[1:-1], k=1)\n",
|
" return (\n",
|
||||||
" \n",
|
" np.diag(2 * (1 / h[:-1] + 1 / h[1:]))\n",
|
||||||
|
" + np.diag(1 / h[1:-1], k=-1)\n",
|
||||||
|
" + np.diag(1 / h[1:-1], k=1)\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
"# Test\n",
|
"# Test\n",
|
||||||
"print(M(np.array([0, 1, 2, 3, 4])))"
|
"print(M(np.array([0, 1, 2, 3, 4])))"
|
||||||
]
|
]
|
||||||
@@ -191,10 +196,10 @@
|
|||||||
"def sprime(x, y, p0, pN):\n",
|
"def sprime(x, y, p0, pN):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Retourne la solution du système (2)\n",
|
" Retourne la solution du système (2)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Parameters\n",
|
" Parameters\n",
|
||||||
" ----------\n",
|
" ----------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" x: ndarray\n",
|
" x: ndarray\n",
|
||||||
" vecteurs contenant les valeurs [x0, x1, ..., xN]\n",
|
" vecteurs contenant les valeurs [x0, x1, ..., xN]\n",
|
||||||
" y: ndarray\n",
|
" y: ndarray\n",
|
||||||
@@ -203,18 +208,18 @@
|
|||||||
" première valeur du vecteur p\n",
|
" première valeur du vecteur p\n",
|
||||||
" pN: int\n",
|
" pN: int\n",
|
||||||
" N-ième valeur du vecteur p\n",
|
" N-ième valeur du vecteur p\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Returns\n",
|
" Returns\n",
|
||||||
" -------\n",
|
" -------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" out: ndarray\n",
|
" out: ndarray\n",
|
||||||
" solution du système (2)\n",
|
" solution du système (2)\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" h = x[1:] - x[:-1]\n",
|
" h = x[1:] - x[:-1]\n",
|
||||||
" delta_y = (y[1:] - y[:-1]) / h\n",
|
" delta_y = (y[1:] - y[:-1]) / h\n",
|
||||||
" c = 3 * (delta_y[1:]/h[1:] + delta_y[:-1]/h[:-1])\n",
|
" c = 3 * (delta_y[1:] / h[1:] + delta_y[:-1] / h[:-1])\n",
|
||||||
" c[0] -= p0/h[0]\n",
|
" c[0] -= p0 / h[0]\n",
|
||||||
" c[-1] -= pN/h[-1]\n",
|
" c[-1] -= pN / h[-1]\n",
|
||||||
" return np.linalg.solve(M(x), c)"
|
" return np.linalg.solve(M(x), c)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -273,52 +278,54 @@
|
|||||||
"def f(x):\n",
|
"def f(x):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Retourne la fonction f évaluée aux points x\n",
|
" Retourne la fonction f évaluée aux points x\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Parameters\n",
|
" Parameters\n",
|
||||||
" ----------\n",
|
" ----------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" x: ndarray\n",
|
" x: ndarray\n",
|
||||||
" vecteurs contenant les valeurs [x0, x1, ..., xN]\n",
|
" vecteurs contenant les valeurs [x0, x1, ..., xN]\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Returns\n",
|
" Returns\n",
|
||||||
" -------\n",
|
" -------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" out: ndarray\n",
|
" out: ndarray\n",
|
||||||
" Valeur de la fonction f aux points x\n",
|
" Valeur de la fonction f aux points x\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" return 1 / (1 + x**2)\n",
|
" return 1 / (1 + x**2)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def fprime(x):\n",
|
"def fprime(x):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Retourne la fonction dérivée de f évaluée aux points x\n",
|
" Retourne la fonction dérivée de f évaluée aux points x\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Parameters\n",
|
" Parameters\n",
|
||||||
" ----------\n",
|
" ----------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" x: ndarray\n",
|
" x: ndarray\n",
|
||||||
" vecteurs contenant les valeurs [x0, x1, ..., xN]\n",
|
" vecteurs contenant les valeurs [x0, x1, ..., xN]\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Returns\n",
|
" Returns\n",
|
||||||
" -------\n",
|
" -------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" out: ndarray\n",
|
" out: ndarray\n",
|
||||||
" Valeur de la fonction dérivée de f aux points x\n",
|
" Valeur de la fonction dérivée de f aux points x\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" return -2*x/((1+x**2)**2)\n",
|
" return -2 * x / ((1 + x**2) ** 2)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Paramètres \n",
|
"\n",
|
||||||
|
"# Paramètres\n",
|
||||||
"xx = np.linspace(-5, 5, 200)\n",
|
"xx = np.linspace(-5, 5, 200)\n",
|
||||||
"x = np.linspace(-5, 5, 21)\n",
|
"x = np.linspace(-5, 5, 21)\n",
|
||||||
"pi = sprime(x, f(x), fprime(-5), fprime(5))\n",
|
"pi = sprime(x, f(x), fprime(-5), fprime(5))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Graphique\n",
|
"# Graphique\n",
|
||||||
"fig, ax = plt.subplots(figsize=(6, 6))\n",
|
"fig, ax = plt.subplots(figsize=(6, 6))\n",
|
||||||
"ax.plot(xx, fprime(xx), label=f'$f\\'$', color='red')\n",
|
"ax.plot(xx, fprime(xx), label=\"$f'$\", color=\"red\")\n",
|
||||||
"ax.scatter(x[1:-1], pi, label=f'$p_i$')\n",
|
"ax.scatter(x[1:-1], pi, label=\"$p_i$\")\n",
|
||||||
"ax.legend()\n",
|
"ax.legend()\n",
|
||||||
"ax.set_xlabel(f'$x$')\n",
|
"ax.set_xlabel(\"$x$\")\n",
|
||||||
"ax.set_ylabel(f'$f(x)$')\n",
|
"ax.set_ylabel(\"$f(x)$\")\n",
|
||||||
"ax.set_title('Les pentes de la spline cubique')"
|
"ax.set_title(\"Les pentes de la spline cubique\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -363,10 +370,10 @@
|
|||||||
"def splines(x, y, p0, pN):\n",
|
"def splines(x, y, p0, pN):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Retourne la matrice S de taille (4, N)\n",
|
" Retourne la matrice S de taille (4, N)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Parameters\n",
|
" Parameters\n",
|
||||||
" ----------\n",
|
" ----------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" x: ndarray\n",
|
" x: ndarray\n",
|
||||||
" vecteurs contenant les valeurs [x0, x1, ..., xN]\n",
|
" vecteurs contenant les valeurs [x0, x1, ..., xN]\n",
|
||||||
" y: ndarray\n",
|
" y: ndarray\n",
|
||||||
@@ -375,20 +382,20 @@
|
|||||||
" première valeur du vecteur p\n",
|
" première valeur du vecteur p\n",
|
||||||
" pN: int\n",
|
" pN: int\n",
|
||||||
" N-ième valeur du vecteur p\n",
|
" N-ième valeur du vecteur p\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Returns\n",
|
" Returns\n",
|
||||||
" -------\n",
|
" -------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" out: ndarray\n",
|
" out: ndarray\n",
|
||||||
" Matrice S de taille (4, N) tel que la i-ième ligne contient les valeurs a_i, b_i, c_i et d_i\n",
|
" Matrice S de taille (4, N) tel que la i-ième ligne contient les valeurs a_i, b_i, c_i et d_i\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" h = x[1:] - x[:-1]\n",
|
" h = x[1:] - x[:-1]\n",
|
||||||
" delta_y = (y[1:] - y[:-1]) / h\n",
|
" delta_y = (y[1:] - y[:-1]) / h\n",
|
||||||
" \n",
|
"\n",
|
||||||
" a = y\n",
|
" a = y\n",
|
||||||
" b = np.concatenate((np.array([p0]), sprime(x, y, p0, pN), np.array([pN])))\n",
|
" b = np.concatenate((np.array([p0]), sprime(x, y, p0, pN), np.array([pN])))\n",
|
||||||
" c = 3/h * delta_y - (b[1:] + 2*b[:-1]) / h\n",
|
" c = 3 / h * delta_y - (b[1:] + 2 * b[:-1]) / h\n",
|
||||||
" d = 1/h**2 * (b[1:] + b[:-1]) - 2/h**2 * delta_y\n",
|
" d = 1 / h**2 * (b[1:] + b[:-1]) - 2 / h**2 * delta_y\n",
|
||||||
" return np.transpose([a[:-1], b[:-1], c, d])"
|
" return np.transpose([a[:-1], b[:-1], c, d])"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -412,34 +419,38 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def spline_eval( x, xx, S ):\n",
|
"def spline_eval(x, xx, S):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Evalue une spline définie par des noeuds équirepartis\n",
|
" Evalue une spline définie par des noeuds équirepartis\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Parameters\n",
|
" Parameters\n",
|
||||||
" ----------\n",
|
" ----------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" x: ndarray\n",
|
" x: ndarray\n",
|
||||||
" noeuds définissant la spline\n",
|
" noeuds définissant la spline\n",
|
||||||
" \n",
|
"\n",
|
||||||
" xx: ndarray\n",
|
" xx: ndarray\n",
|
||||||
" abscisses des points d'évaluation\n",
|
" abscisses des points d'évaluation\n",
|
||||||
" \n",
|
"\n",
|
||||||
" S: ndarray\n",
|
" S: ndarray\n",
|
||||||
" de taille (x.size-1, 4)\n",
|
" de taille (x.size-1, 4)\n",
|
||||||
" tableau dont la i-ème ligne contient les coéficients du polynome cubique qui est la restriction\n",
|
" tableau dont la i-ème ligne contient les coéficients du polynome cubique qui est la restriction\n",
|
||||||
" de la spline à l'intervalle [x_i, x_{i+1}]\n",
|
" de la spline à l'intervalle [x_i, x_{i+1}]\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Returns\n",
|
" Returns\n",
|
||||||
" -------\n",
|
" -------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" ndarray\n",
|
" ndarray\n",
|
||||||
" ordonnées des points d'évaluation\n",
|
" ordonnées des points d'évaluation\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" ind = ( np.floor( ( xx - x[ 0 ] ) / ( x[ 1 ] - x[ 0 ] ) ) ).astype( int )\n",
|
" ind = (np.floor((xx - x[0]) / (x[1] - x[0]))).astype(int)\n",
|
||||||
" ind = np.where( ind == x.size-1, ind - 1 , ind )\n",
|
" ind = np.where(ind == x.size - 1, ind - 1, ind)\n",
|
||||||
" yy = S[ ind, 0 ] + S[ ind, 1 ] * ( xx - x[ ind ] ) + \\\n",
|
" yy = (\n",
|
||||||
" S[ ind, 2 ] * ( xx - x[ ind ] )**2 + S[ ind, 3 ] * ( xx - x[ ind ] )**3\n",
|
" S[ind, 0]\n",
|
||||||
|
" + S[ind, 1] * (xx - x[ind])\n",
|
||||||
|
" + S[ind, 2] * (xx - x[ind]) ** 2\n",
|
||||||
|
" + S[ind, 3] * (xx - x[ind]) ** 3\n",
|
||||||
|
" )\n",
|
||||||
" return yy"
|
" return yy"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -472,21 +483,21 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# Paramètres \n",
|
"# Paramètres\n",
|
||||||
"x = np.linspace(-5, 5, 6)\n",
|
"x = np.linspace(-5, 5, 6)\n",
|
||||||
"y = np.random.rand(5+1)\n",
|
"y = np.random.rand(5 + 1)\n",
|
||||||
"xx = np.linspace(-5, 5, 200)\n",
|
"xx = np.linspace(-5, 5, 200)\n",
|
||||||
"s = splines(x, y, 0, 0)\n",
|
"s = splines(x, y, 0, 0)\n",
|
||||||
"s_eval = spline_eval(x, xx, s)\n",
|
"s_eval = spline_eval(x, xx, s)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Graphique\n",
|
"# Graphique\n",
|
||||||
"fig, ax = plt.subplots(figsize=(6, 6))\n",
|
"fig, ax = plt.subplots(figsize=(6, 6))\n",
|
||||||
"ax.plot(xx, s_eval, label='spline cubique interpolateur', color='red')\n",
|
"ax.plot(xx, s_eval, label=\"spline cubique interpolateur\", color=\"red\")\n",
|
||||||
"ax.scatter(x, y, label=f'$(x_i, y_i)$')\n",
|
"ax.scatter(x, y, label=\"$(x_i, y_i)$\")\n",
|
||||||
"ax.legend()\n",
|
"ax.legend()\n",
|
||||||
"ax.set_xlabel(f'$x$')\n",
|
"ax.set_xlabel(\"$x$\")\n",
|
||||||
"ax.set_ylabel(f'$f(x)$')\n",
|
"ax.set_ylabel(\"$f(x)$\")\n",
|
||||||
"ax.set_title('Evaluation de la spline cubique')"
|
"ax.set_title(\"Evaluation de la spline cubique\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -525,7 +536,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# Paramètres \n",
|
"# Paramètres\n",
|
||||||
"a, b = -5, 5\n",
|
"a, b = -5, 5\n",
|
||||||
"N_list = [4, 9, 19]\n",
|
"N_list = [4, 9, 19]\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -533,17 +544,17 @@
|
|||||||
"fig, ax = plt.subplots(figsize=(15, 6))\n",
|
"fig, ax = plt.subplots(figsize=(15, 6))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for N in N_list:\n",
|
"for N in N_list:\n",
|
||||||
" x = np.linspace(a, b, N+1)\n",
|
" x = np.linspace(a, b, N + 1)\n",
|
||||||
" xx = np.linspace(a, b, 200)\n",
|
" xx = np.linspace(a, b, 200)\n",
|
||||||
" s = splines(x, f(x), 0, 0)\n",
|
" s = splines(x, f(x), 0, 0)\n",
|
||||||
" s_eval = spline_eval(x, xx, s)\n",
|
" s_eval = spline_eval(x, xx, s)\n",
|
||||||
" ax.plot(xx, s_eval, label=f'Spline cubique interpolateur pour N={N}')\n",
|
" ax.plot(xx, s_eval, label=f\"Spline cubique interpolateur pour N={N}\")\n",
|
||||||
" ax.scatter(x, f(x), label=f'f(x) pour N={N}')\n",
|
" ax.scatter(x, f(x), label=f\"f(x) pour N={N}\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
"ax.legend()\n",
|
"ax.legend()\n",
|
||||||
"ax.set_xlabel(f'$x$')\n",
|
"ax.set_xlabel(\"$x$\")\n",
|
||||||
"ax.set_ylabel(f'$f(x)$')\n",
|
"ax.set_ylabel(\"$f(x)$\")\n",
|
||||||
"ax.set_title('Evaluation de la spline cubique')"
|
"ax.set_title(\"Evaluation de la spline cubique\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -60,17 +60,20 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def f0(x): \n",
|
"def f0(x):\n",
|
||||||
" return np.exp(x)\n",
|
" return np.exp(x)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def f1(x):\n",
|
"def f1(x):\n",
|
||||||
" return 1 / (1 + 16*np.power(x, 2))\n",
|
" return 1 / (1 + 16 * np.power(x, 2))\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def f2(x):\n",
|
"def f2(x):\n",
|
||||||
" return np.power(np.abs(x**2 - 1/4), 3)\n",
|
" return np.power(np.abs(x**2 - 1 / 4), 3)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def f3(x):\n",
|
"def f3(x):\n",
|
||||||
" return np.power(np.abs(x+1/2), 1/2)"
|
" return np.power(np.abs(x + 1 / 2), 1 / 2)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -176,10 +179,12 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"for f in [f0, f1, f2, f3]:\n",
|
"for f in [f0, f1, f2, f3]:\n",
|
||||||
" print(f'Calcule de I(f) par la méthode de gauss et par la formule quadratique pour la fonction {f.__name__}')\n",
|
" print(\n",
|
||||||
|
" f\"Calcule de I(f) par la méthode de gauss et par la formule quadratique pour la fonction {f.__name__}\"\n",
|
||||||
|
" )\n",
|
||||||
" for n in range(1, 11):\n",
|
" for n in range(1, 11):\n",
|
||||||
" print(f\"Pour n = {n}, gauss = {gauss(f, n)} et quad = {quad(f, -1, 1)[0]}\")\n",
|
" print(f\"Pour n = {n}, gauss = {gauss(f, n)} et quad = {quad(f, -1, 1)[0]}\")\n",
|
||||||
" print('')"
|
" print(\"\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -211,10 +216,10 @@
|
|||||||
"def simpson(f, N):\n",
|
"def simpson(f, N):\n",
|
||||||
" if N % 2 == 0:\n",
|
" if N % 2 == 0:\n",
|
||||||
" raise ValueError(\"N doit est impair.\")\n",
|
" raise ValueError(\"N doit est impair.\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
" h = 2 / (2 * (N - 1) // 2)\n",
|
" h = 2 / (2 * (N - 1) // 2)\n",
|
||||||
" fx = f(np.linspace(-1, 1, N))\n",
|
" fx = f(np.linspace(-1, 1, N))\n",
|
||||||
" \n",
|
"\n",
|
||||||
" return (h / 3) * (fx[0] + 4 * fx[1:-1:2].sum() + 2 * fx[2:-1:2].sum() + fx[-1])"
|
" return (h / 3) * (fx[0] + 4 * fx[1:-1:2].sum() + 2 * fx[2:-1:2].sum() + fx[-1])"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -270,10 +275,12 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"for f in [f0, f1, f2, f3]:\n",
|
"for f in [f0, f1, f2, f3]:\n",
|
||||||
" print(f'Calcule de I(f) par la méthode de simpson et par la formule quadratique pour la fonction {f.__name__}')\n",
|
" print(\n",
|
||||||
|
" f\"Calcule de I(f) par la méthode de simpson et par la formule quadratique pour la fonction {f.__name__}\"\n",
|
||||||
|
" )\n",
|
||||||
" for n in range(3, 16, 2):\n",
|
" for n in range(3, 16, 2):\n",
|
||||||
" print(f\"Pour n = {n}, simpson = {simpson(f, n)} et quad = {quad(f, -1, 1)[0]}\")\n",
|
" print(f\"Pour n = {n}, simpson = {simpson(f, n)} et quad = {quad(f, -1, 1)[0]}\")\n",
|
||||||
" print('')"
|
" print(\"\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -336,7 +343,7 @@
|
|||||||
" elif N == 1:\n",
|
" elif N == 1:\n",
|
||||||
" return x\n",
|
" return x\n",
|
||||||
" else:\n",
|
" else:\n",
|
||||||
" return 2 * x * poly_tchebychev(x, N-1) - poly_tchebychev(x, N-2)"
|
" return 2 * x * poly_tchebychev(x, N - 1) - poly_tchebychev(x, N - 2)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -346,7 +353,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def points_tchebychev(N):\n",
|
"def points_tchebychev(N):\n",
|
||||||
" k = np.arange(1, N+1)\n",
|
" k = np.arange(1, N + 1)\n",
|
||||||
" return np.cos((2 * k - 1) * np.pi / (2 * N))"
|
" return np.cos((2 * k - 1) * np.pi / (2 * N))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -449,7 +456,7 @@
|
|||||||
" lamk = np.zeros(N)\n",
|
" lamk = np.zeros(N)\n",
|
||||||
" for k in range(N):\n",
|
" for k in range(N):\n",
|
||||||
" s = 0\n",
|
" s = 0\n",
|
||||||
" for m in range(1, N//2+1):\n",
|
" for m in range(1, N // 2 + 1):\n",
|
||||||
" T = poly_tchebychev(xk[k], 2 * m)\n",
|
" T = poly_tchebychev(xk[k], 2 * m)\n",
|
||||||
" s += 2 * T / (4 * np.power(m, 2) - 1)\n",
|
" s += 2 * T / (4 * np.power(m, 2) - 1)\n",
|
||||||
" lamk[k] = 2 / N * (1 - s)\n",
|
" lamk[k] = 2 / N * (1 - s)\n",
|
||||||
@@ -529,10 +536,12 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"for f in [f0, f1, f2, f3]:\n",
|
"for f in [f0, f1, f2, f3]:\n",
|
||||||
" print(f'Calcule de I(f) par la méthode de fejer et par la formule quadratique pour la fonction {f.__name__}')\n",
|
" print(\n",
|
||||||
|
" f\"Calcule de I(f) par la méthode de fejer et par la formule quadratique pour la fonction {f.__name__}\"\n",
|
||||||
|
" )\n",
|
||||||
" for n in range(1, 11):\n",
|
" for n in range(1, 11):\n",
|
||||||
" print(f\"Pour n = {n}, fejer = {fejer(f, n)} et quad = {quad(f, -1, 1)[0]}\")\n",
|
" print(f\"Pour n = {n}, fejer = {fejer(f, n)} et quad = {quad(f, -1, 1)[0]}\")\n",
|
||||||
" print('')"
|
" print(\"\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -568,26 +577,44 @@
|
|||||||
"figure = plt.figure(figsize=(15, 10))\n",
|
"figure = plt.figure(figsize=(15, 10))\n",
|
||||||
"for fi, f in enumerate([f0, f1, f2, f3]):\n",
|
"for fi, f in enumerate([f0, f1, f2, f3]):\n",
|
||||||
" error_gauss = np.zeros((N,))\n",
|
" error_gauss = np.zeros((N,))\n",
|
||||||
" error_simp = np.zeros(((N-1)//2,))\n",
|
" error_simp = np.zeros(((N - 1) // 2,))\n",
|
||||||
" error_fejer = np.zeros((N,))\n",
|
" error_fejer = np.zeros((N,))\n",
|
||||||
" I_quad, _ = quad(f, -1, 1)\n",
|
" I_quad, _ = quad(f, -1, 1)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" for n in range(1, N+1):\n",
|
" for n in range(1, N + 1):\n",
|
||||||
" I_gauss = gauss(f, n)\n",
|
" I_gauss = gauss(f, n)\n",
|
||||||
" error_gauss[n-1] = np.abs(I_gauss - I_quad)\n",
|
" error_gauss[n - 1] = np.abs(I_gauss - I_quad)\n",
|
||||||
" I_fejer = fejer(f, n)\n",
|
" I_fejer = fejer(f, n)\n",
|
||||||
" error_fejer[n-1] = np.abs(I_fejer - I_quad)\n",
|
" error_fejer[n - 1] = np.abs(I_fejer - I_quad)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" for n in range( 3, N+1, 2 ):\n",
|
" for n in range(3, N + 1, 2):\n",
|
||||||
" I_simp = simpson(f, n)\n",
|
" I_simp = simpson(f, n)\n",
|
||||||
" error_simp[(n-2)//2] = np.abs(I_simp - I_quad)\n",
|
" error_simp[(n - 2) // 2] = np.abs(I_simp - I_quad)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" ax = figure.add_subplot(2, 2, fi + 1)\n",
|
" ax = figure.add_subplot(2, 2, fi + 1)\n",
|
||||||
" ax.scatter(np.arange(1, N+1), np.log10(error_gauss, out = -16. * np.ones(error_gauss.shape), \n",
|
" ax.scatter(\n",
|
||||||
" where = (error_gauss > 1e-16)), label = 'Gauss', marker=\"+\")\n",
|
" np.arange(1, N + 1),\n",
|
||||||
" ax.scatter(np.arange(3, N+1, 2), np.log10( error_simp ), label = 'Simpson', marker=\"+\")\n",
|
" np.log10(\n",
|
||||||
" ax.scatter(np.arange(1, N+1), np.log10(error_fejer, out = -16. * np.ones(error_fejer.shape), \n",
|
" error_gauss,\n",
|
||||||
" where = (error_fejer > 1e-16)), label = 'Fejer', marker=\"+\")\n",
|
" out=-16.0 * np.ones(error_gauss.shape),\n",
|
||||||
|
" where=(error_gauss > 1e-16),\n",
|
||||||
|
" ),\n",
|
||||||
|
" label=\"Gauss\",\n",
|
||||||
|
" marker=\"+\",\n",
|
||||||
|
" )\n",
|
||||||
|
" ax.scatter(\n",
|
||||||
|
" np.arange(3, N + 1, 2), np.log10(error_simp), label=\"Simpson\", marker=\"+\"\n",
|
||||||
|
" )\n",
|
||||||
|
" ax.scatter(\n",
|
||||||
|
" np.arange(1, N + 1),\n",
|
||||||
|
" np.log10(\n",
|
||||||
|
" error_fejer,\n",
|
||||||
|
" out=-16.0 * np.ones(error_fejer.shape),\n",
|
||||||
|
" where=(error_fejer > 1e-16),\n",
|
||||||
|
" ),\n",
|
||||||
|
" label=\"Fejer\",\n",
|
||||||
|
" marker=\"+\",\n",
|
||||||
|
" )\n",
|
||||||
" ax.legend()\n",
|
" ax.legend()\n",
|
||||||
" ax.set_title(f\"Erreur de différentes méthodes de quadrature pour {f.__name__}\")\n",
|
" ax.set_title(f\"Erreur de différentes méthodes de quadrature pour {f.__name__}\")\n",
|
||||||
" ax.set_xlabel(\"n\")\n",
|
" ax.set_xlabel(\"n\")\n",
|
||||||
@@ -672,8 +699,13 @@
|
|||||||
"def f(x, k):\n",
|
"def f(x, k):\n",
|
||||||
" return x**k\n",
|
" return x**k\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"print(\"-----------------------------------------------------------------------\")\n",
|
"print(\"-----------------------------------------------------------------------\")\n",
|
||||||
"print(\"{:>5s} | {:>7s} {:>9s} {:>9s} {:>9s} {:>9s} {:>9s}\".format(\"N\", \"x^0\", \"x^2\", \"x^4\", \"x^6\", \"x^8\", \"x^10\"))\n",
|
"print(\n",
|
||||||
|
" \"{:>5s} | {:>7s} {:>9s} {:>9s} {:>9s} {:>9s} {:>9s}\".format(\n",
|
||||||
|
" \"N\", \"x^0\", \"x^2\", \"x^4\", \"x^6\", \"x^8\", \"x^10\"\n",
|
||||||
|
" )\n",
|
||||||
|
")\n",
|
||||||
"print(\"-----------------------------------------------------------------------\")\n",
|
"print(\"-----------------------------------------------------------------------\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for N in range(1, 11):\n",
|
"for N in range(1, 11):\n",
|
||||||
@@ -683,7 +715,10 @@
|
|||||||
" I_exact = 2 / (k + 1) if k % 2 == 0 else 0\n",
|
" I_exact = 2 / (k + 1) if k % 2 == 0 else 0\n",
|
||||||
" approx_error = np.abs(I_approx - I_exact)\n",
|
" approx_error = np.abs(I_approx - I_exact)\n",
|
||||||
" approx_errors.append(approx_error)\n",
|
" approx_errors.append(approx_error)\n",
|
||||||
" print(\"{:5d} | \".format(N) + \" \".join(\"{:.3f} \".format(e) for e in approx_errors))"
|
" print(\n",
|
||||||
|
" \"{:5d} | \".format(N)\n",
|
||||||
|
" + \" \".join(\"{:.3f} \".format(e) for e in approx_errors)\n",
|
||||||
|
" )"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -722,8 +757,13 @@
|
|||||||
"def f(x, k):\n",
|
"def f(x, k):\n",
|
||||||
" return x**k\n",
|
" return x**k\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"print(\"-----------------------------------------------------------------------\")\n",
|
"print(\"-----------------------------------------------------------------------\")\n",
|
||||||
"print(\"{:>5s} | {:>7s} {:>9s} {:>9s} {:>9s} {:>9s} {:>9s}\".format(\"N\", \"x^0\", \"x^2\", \"x^4\", \"x^6\", \"x^8\", \"x^10\"))\n",
|
"print(\n",
|
||||||
|
" \"{:>5s} | {:>7s} {:>9s} {:>9s} {:>9s} {:>9s} {:>9s}\".format(\n",
|
||||||
|
" \"N\", \"x^0\", \"x^2\", \"x^4\", \"x^6\", \"x^8\", \"x^10\"\n",
|
||||||
|
" )\n",
|
||||||
|
")\n",
|
||||||
"print(\"-----------------------------------------------------------------------\")\n",
|
"print(\"-----------------------------------------------------------------------\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for N in range(1, 11):\n",
|
"for N in range(1, 11):\n",
|
||||||
@@ -733,7 +773,10 @@
|
|||||||
" I_exact = 2 / (k + 1) if k % 2 == 0 else 0\n",
|
" I_exact = 2 / (k + 1) if k % 2 == 0 else 0\n",
|
||||||
" approx_error = np.abs(I_approx - I_exact)\n",
|
" approx_error = np.abs(I_approx - I_exact)\n",
|
||||||
" approx_errors.append(approx_error)\n",
|
" approx_errors.append(approx_error)\n",
|
||||||
" print(\"{:5d} | \".format(N) + \" \".join(\"{:.3f} \".format(e) for e in approx_errors))"
|
" print(\n",
|
||||||
|
" \"{:5d} | \".format(N)\n",
|
||||||
|
" + \" \".join(\"{:.3f} \".format(e) for e in approx_errors)\n",
|
||||||
|
" )"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -22,8 +22,8 @@
|
|||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"%config InlineBackend.figure_format = 'retina'\n",
|
"%config InlineBackend.figure_format = 'retina'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"import numpy as np # pour les numpy array\n",
|
"import numpy as np # pour les numpy array\n",
|
||||||
"import matplotlib.pyplot as plt # librairie graphique"
|
"import matplotlib.pyplot as plt # librairie graphique"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -72,11 +72,11 @@
|
|||||||
" N = len(x)\n",
|
" N = len(x)\n",
|
||||||
" M = len(xx)\n",
|
" M = len(xx)\n",
|
||||||
" L = np.ones((M, N))\n",
|
" L = np.ones((M, N))\n",
|
||||||
" \n",
|
"\n",
|
||||||
" for i in range(N):\n",
|
" for i in range(N):\n",
|
||||||
" for j in range(N):\n",
|
" for j in range(N):\n",
|
||||||
" if i != j:\n",
|
" if i != j:\n",
|
||||||
" L[:, i] *= (xx - x[j])/(x[i]-x[j])\n",
|
" L[:, i] *= (xx - x[j]) / (x[i] - x[j])\n",
|
||||||
" return L.dot(y)"
|
" return L.dot(y)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -119,7 +119,7 @@
|
|||||||
"y = np.random.rand(N)\n",
|
"y = np.random.rand(N)\n",
|
||||||
"xx = np.linspace(0, 1, 200)\n",
|
"xx = np.linspace(0, 1, 200)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.scatter(x,y)\n",
|
"plt.scatter(x, y)\n",
|
||||||
"plt.plot(xx, interp_Lagrange(x, y, xx))"
|
"plt.plot(xx, interp_Lagrange(x, y, xx))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -155,10 +155,16 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def equirepartis(a, b, N):\n",
|
"def equirepartis(a, b, N):\n",
|
||||||
" return np.array([a + (b-a) * (i-1)/(N-1) for i in range(1, N+1)])\n",
|
" return np.array([a + (b - a) * (i - 1) / (N - 1) for i in range(1, N + 1)])\n",
|
||||||
" \n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def tchebychev(a, b, N):\n",
|
"def tchebychev(a, b, N):\n",
|
||||||
" return np.array([(a+b)/2 + (b-a)/2 * np.cos((2*i-1)/(2*N)*np.pi) for i in range(1, N+1)])"
|
" return np.array(\n",
|
||||||
|
" [\n",
|
||||||
|
" (a + b) / 2 + (b - a) / 2 * np.cos((2 * i - 1) / (2 * N) * np.pi)\n",
|
||||||
|
" for i in range(1, N + 1)\n",
|
||||||
|
" ]\n",
|
||||||
|
" )"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -188,7 +194,7 @@
|
|||||||
" L = np.ones_like(xx)\n",
|
" L = np.ones_like(xx)\n",
|
||||||
" for j in range(N):\n",
|
" for j in range(N):\n",
|
||||||
" if i != j:\n",
|
" if i != j:\n",
|
||||||
" L *= (xx-x[j])/(x[i]-x[j]) \n",
|
" L *= (xx - x[j]) / (x[i] - x[j])\n",
|
||||||
" return L"
|
" return L"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -271,16 +277,16 @@
|
|||||||
" ax[0].set_title(f\"Points équi-repartis (N={n})\")\n",
|
" ax[0].set_title(f\"Points équi-repartis (N={n})\")\n",
|
||||||
" xeq = equirepartis(a, b, n)\n",
|
" xeq = equirepartis(a, b, n)\n",
|
||||||
" for i in range(n):\n",
|
" for i in range(n):\n",
|
||||||
" ax[0].scatter(xeq[i], 0, color='black')\n",
|
" ax[0].scatter(xeq[i], 0, color=\"black\")\n",
|
||||||
" ax[0].scatter(xeq[i], 1, color='black')\n",
|
" ax[0].scatter(xeq[i], 1, color=\"black\")\n",
|
||||||
" ax[0].plot(xx, Li(i, xeq, xx))\n",
|
" ax[0].plot(xx, Li(i, xeq, xx))\n",
|
||||||
" ax[0].grid()\n",
|
" ax[0].grid()\n",
|
||||||
" \n",
|
"\n",
|
||||||
" ax[1].set_title(f\"Points de Tchebychev (N={n})\")\n",
|
" ax[1].set_title(f\"Points de Tchebychev (N={n})\")\n",
|
||||||
" xchev = tchebychev(a, b, n)\n",
|
" xchev = tchebychev(a, b, n)\n",
|
||||||
" for i in range(n):\n",
|
" for i in range(n):\n",
|
||||||
" ax[1].scatter(xchev[i], 0, color='black')\n",
|
" ax[1].scatter(xchev[i], 0, color=\"black\")\n",
|
||||||
" ax[1].scatter(xchev[i], 1, color='black')\n",
|
" ax[1].scatter(xchev[i], 1, color=\"black\")\n",
|
||||||
" ax[1].plot(xx, Li(i, xchev, xx))\n",
|
" ax[1].plot(xx, Li(i, xchev, xx))\n",
|
||||||
" ax[1].grid()"
|
" ax[1].grid()"
|
||||||
]
|
]
|
||||||
@@ -325,20 +331,20 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"f = lambda x: 1/(1+x**2)\n",
|
"f = lambda x: 1 / (1 + x**2)\n",
|
||||||
"a, b = -5, 5\n",
|
"a, b = -5, 5\n",
|
||||||
"xx = np.linspace(a, b, 200)\n",
|
"xx = np.linspace(a, b, 200)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.plot(xx, f(xx), label='Courbe de f')\n",
|
"plt.plot(xx, f(xx), label=\"Courbe de f\")\n",
|
||||||
"for n in [5, 10, 20]:\n",
|
"for n in [5, 10, 20]:\n",
|
||||||
" xeq = equirepartis(a, b, n)\n",
|
" xeq = equirepartis(a, b, n)\n",
|
||||||
" for i in range(n):\n",
|
" for i in range(n):\n",
|
||||||
" plt.scatter(xeq[i], f(xeq[i]))\n",
|
" plt.scatter(xeq[i], f(xeq[i]))\n",
|
||||||
" plt.plot(xx, Li(i, xeq, xx))\n",
|
" plt.plot(xx, Li(i, xeq, xx))\n",
|
||||||
" \n",
|
"\n",
|
||||||
"plt.ylim(-1, 1)\n",
|
"plt.ylim(-1, 1)\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.title('Interpolation de f avec Lagrange pour N points répartis')\n",
|
"plt.title(\"Interpolation de f avec Lagrange pour N points répartis\")\n",
|
||||||
"plt.grid()"
|
"plt.grid()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -366,20 +372,20 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"f = lambda x: 1/(1+x**2)\n",
|
"f = lambda x: 1 / (1 + x**2)\n",
|
||||||
"a, b = -5, 5\n",
|
"a, b = -5, 5\n",
|
||||||
"xx = np.linspace(a, b, 200)\n",
|
"xx = np.linspace(a, b, 200)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.plot(xx, f(xx), label='Courbe de f')\n",
|
"plt.plot(xx, f(xx), label=\"Courbe de f\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for n in [5, 10, 20]:\n",
|
"for n in [5, 10, 20]:\n",
|
||||||
" xchev = tchebychev(a, b, n)\n",
|
" xchev = tchebychev(a, b, n)\n",
|
||||||
" for i in range(n):\n",
|
" for i in range(n):\n",
|
||||||
" plt.scatter(xchev[i], f(xchev[i]))\n",
|
" plt.scatter(xchev[i], f(xchev[i]))\n",
|
||||||
" plt.plot(xx, Li(i, xchev, xx))\n",
|
" plt.plot(xx, Li(i, xchev, xx))\n",
|
||||||
" \n",
|
"\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.title('Interpolation de f avec Lagrange pour N points de Tchebychev')\n",
|
"plt.title(\"Interpolation de f avec Lagrange pour N points de Tchebychev\")\n",
|
||||||
"plt.grid()"
|
"plt.grid()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -437,9 +443,11 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"N = np.arange(5, 101, 5)\n",
|
"N = np.arange(5, 101, 5)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def n_inf(f, p):\n",
|
"def n_inf(f, p):\n",
|
||||||
" return np.max([f, p])\n",
|
" return np.max([f, p])\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"# Norme inf en fct de N\n",
|
"# Norme inf en fct de N\n",
|
||||||
"for n in N:\n",
|
"for n in N:\n",
|
||||||
" xeq = equirepartis(a, b, n)\n",
|
" xeq = equirepartis(a, b, n)\n",
|
||||||
|
|||||||
@@ -98,16 +98,16 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"x = np.linspace(-1, 1, 200)\n",
|
"x = np.linspace(-1, 1, 200)\n",
|
||||||
"ax = fig.add_subplot(3, 3, 1)\n",
|
"ax = fig.add_subplot(3, 3, 1)\n",
|
||||||
"ax.plot(x, f1(x), label='Courbe f')\n",
|
"ax.plot(x, f1(x), label=\"Courbe f\")\n",
|
||||||
"ax.plot(x, x, label=f'$y=x$')\n",
|
"ax.plot(x, x, label=\"$y=x$\")\n",
|
||||||
"ax.scatter([i for i in x if f1(i) == i], [f1(i) for i in x if f1(i) == i])\n",
|
"ax.scatter([i for i in x if f1(i) == i], [f1(i) for i in x if f1(i) == i])\n",
|
||||||
"ax.legend()\n",
|
"ax.legend()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"x = np.linspace(-np.pi / 2, 5*np.pi / 2)\n",
|
"x = np.linspace(-np.pi / 2, 5 * np.pi / 2)\n",
|
||||||
"for fk, f in enumerate([f2, f3, f4, f5]):\n",
|
"for fk, f in enumerate([f2, f3, f4, f5]):\n",
|
||||||
" ax = fig.add_subplot(3, 3, fk+2)\n",
|
" ax = fig.add_subplot(3, 3, fk + 2)\n",
|
||||||
" ax.plot(x, f(x), label='Courbe f')\n",
|
" ax.plot(x, f(x), label=\"Courbe f\")\n",
|
||||||
" ax.plot(x, x, label=f'$y=x$')\n",
|
" ax.plot(x, x, label=\"$y=x$\")\n",
|
||||||
" ax.scatter([i for i in x if f(i) == i], [f(i) for i in x if f(i) == i])\n",
|
" ax.scatter([i for i in x if f(i) == i], [f(i) for i in x if f(i) == i])\n",
|
||||||
" ax.legend()"
|
" ax.legend()"
|
||||||
]
|
]
|
||||||
@@ -129,13 +129,13 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def point_fixe(f, x0, tol=1.e-6, itermax=5000):\n",
|
"def point_fixe(f, x0, tol=1.0e-6, itermax=5000):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Recherche de point fixe : méthode brute x_{n+1} = f(x_n)\n",
|
" Recherche de point fixe : méthode brute x_{n+1} = f(x_n)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Parameters\n",
|
" Parameters\n",
|
||||||
" ----------\n",
|
" ----------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" f: function\n",
|
" f: function\n",
|
||||||
" la fonction dont on cherche le point fixe\n",
|
" la fonction dont on cherche le point fixe\n",
|
||||||
" x0: float\n",
|
" x0: float\n",
|
||||||
@@ -144,10 +144,10 @@
|
|||||||
" critère d'arrêt : |x_{n+1} - x_n| < tol\n",
|
" critère d'arrêt : |x_{n+1} - x_n| < tol\n",
|
||||||
" itermax: int\n",
|
" itermax: int\n",
|
||||||
" le nombre maximal d'itérations autorisées\n",
|
" le nombre maximal d'itérations autorisées\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Returns\n",
|
" Returns\n",
|
||||||
" -------\n",
|
" -------\n",
|
||||||
" \n",
|
"\n",
|
||||||
" x: float\n",
|
" x: float\n",
|
||||||
" la valeur trouvée pour le point fixe\n",
|
" la valeur trouvée pour le point fixe\n",
|
||||||
" niter: int\n",
|
" niter: int\n",
|
||||||
@@ -225,14 +225,14 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"# F1\n",
|
"# F1\n",
|
||||||
"\n",
|
"\n",
|
||||||
"fig, ax = plt.subplots(figsize=(6,6))\n",
|
"fig, ax = plt.subplots(figsize=(6, 6))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"x, niter, xL = point_fixe(f1, -0.5)\n",
|
"x, niter, xL = point_fixe(f1, -0.5)\n",
|
||||||
"xx = np.linspace(-1, 1, 200)\n",
|
"xx = np.linspace(-1, 1, 200)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ax.plot(xx, f1(xx), label='Courbe f1')\n",
|
"ax.plot(xx, f1(xx), label=\"Courbe f1\")\n",
|
||||||
"ax.plot(xx, xx, label=f'$y=x$')\n",
|
"ax.plot(xx, xx, label=\"$y=x$\")\n",
|
||||||
"ax.scatter(x, f1(x), label='Point Fixe')\n",
|
"ax.scatter(x, f1(x), label=\"Point Fixe\")\n",
|
||||||
"ax.legend()\n",
|
"ax.legend()\n",
|
||||||
"ax.set_title(f\"Nombre d'itérations : {niter}\")"
|
"ax.set_title(f\"Nombre d'itérations : {niter}\")"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -103,38 +103,45 @@
|
|||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Fonction f définissant l'EDO\n",
|
|
||||||
"def f1(t,y):\n",
|
|
||||||
" return -t*y\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"# Solution exacte \n",
|
"# Fonction f définissant l'EDO\n",
|
||||||
"def uex1(t,y0):\n",
|
"def f1(t, y):\n",
|
||||||
" return y0 * np.exp(-t**2 /2)\n",
|
" return -t * y\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Solution exacte\n",
|
||||||
|
"def uex1(t, y0):\n",
|
||||||
|
" return y0 * np.exp(-(t**2) / 2)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(1)\n",
|
"plt.figure(1)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"## Solutions de l'EDO 1 telles que y(0)=1 et y(0)=2\n",
|
"## Solutions de l'EDO 1 telles que y(0)=1 et y(0)=2\n",
|
||||||
"\n",
|
"\n",
|
||||||
"tt=np.linspace(-3, 3, 100) # vecteur représentant l'intervalle de temps\n",
|
"tt = np.linspace(-3, 3, 100) # vecteur représentant l'intervalle de temps\n",
|
||||||
"y1=uex1(tt, 1) # sol. exacte avec y_0=1\n",
|
"y1 = uex1(tt, 1) # sol. exacte avec y_0=1\n",
|
||||||
"y2=uex1(tt, 2) # sol. exacte avec y_0=2\n",
|
"y2 = uex1(tt, 2) # sol. exacte avec y_0=2\n",
|
||||||
"plt.plot(tt,y1,label='y(0)=1')\n",
|
"plt.plot(tt, y1, label=\"y(0)=1\")\n",
|
||||||
"plt.plot(tt,y2,label='y(0)=2')\n",
|
"plt.plot(tt, y2, label=\"y(0)=2\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"##Tracé du champ de vecteurs\n",
|
"##Tracé du champ de vecteurs\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.title('Solution exacte pour y0 et y1')\n",
|
"plt.title(\"Solution exacte pour y0 et y1\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.xlabel('t')\n",
|
"plt.xlabel(\"t\")\n",
|
||||||
"plt.ylabel('y')\n",
|
"plt.ylabel(\"y\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"t=np.linspace(-5,5,35) # abcisse des points de la grille \n",
|
"t = np.linspace(-5, 5, 35) # abcisse des points de la grille\n",
|
||||||
"y=np.linspace(0,2.1,23) # ordonnées des points de la grille \n",
|
"y = np.linspace(0, 2.1, 23) # ordonnées des points de la grille\n",
|
||||||
"T,Y=np.meshgrid(t,y) # grille de points dans le plan (t,y) \n",
|
"T, Y = np.meshgrid(t, y) # grille de points dans le plan (t,y)\n",
|
||||||
"U=np.ones(T.shape)/np.sqrt(1+f1(T,Y)**2) # matrice avec les composantes horizontales des vecteurs (1), normalisées \n",
|
"U = np.ones(T.shape) / np.sqrt(\n",
|
||||||
"V=f1(T,Y)/np.sqrt(1+f1(T,Y)**2) # matrice avec les composantes verticales des vecteurs (f(t,y)), normalisées \n",
|
" 1 + f1(T, Y) ** 2\n",
|
||||||
"plt.quiver(T,Y,U,V,angles='xy',scale=20,color='cyan')\n",
|
") # matrice avec les composantes horizontales des vecteurs (1), normalisées\n",
|
||||||
"plt.axis([-5,5,0,2.1])"
|
"V = f1(T, Y) / np.sqrt(\n",
|
||||||
|
" 1 + f1(T, Y) ** 2\n",
|
||||||
|
") # matrice avec les composantes verticales des vecteurs (f(t,y)), normalisées\n",
|
||||||
|
"plt.quiver(T, Y, U, V, angles=\"xy\", scale=20, color=\"cyan\")\n",
|
||||||
|
"plt.axis([-5, 5, 0, 2.1])"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -185,40 +192,47 @@
|
|||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"# Fonction f définissant l'EDO\n",
|
"# Fonction f définissant l'EDO\n",
|
||||||
"def f2(t,y):\n",
|
"def f2(t, y):\n",
|
||||||
" return t * y**2\n",
|
" return t * y**2\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Solution exacte \n",
|
"\n",
|
||||||
"def uex2(t,y0):\n",
|
"# Solution exacte\n",
|
||||||
|
"def uex2(t, y0):\n",
|
||||||
" return y0 / (1 - y0 * t**2 / 2)\n",
|
" return y0 / (1 - y0 * t**2 / 2)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"plt.figure(1)\n",
|
"plt.figure(1)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"## Solutions de l'EDO 1 telles que y(0)=1 et y(0)=2\n",
|
"## Solutions de l'EDO 1 telles que y(0)=1 et y(0)=2\n",
|
||||||
"\n",
|
"\n",
|
||||||
"tt=np.linspace(-3, 3, 100) # vecteur représentant l'intervalle de temps\n",
|
"tt = np.linspace(-3, 3, 100) # vecteur représentant l'intervalle de temps\n",
|
||||||
"y1=uex2(tt, 1) # sol. exacte avec y_0=1\n",
|
"y1 = uex2(tt, 1) # sol. exacte avec y_0=1\n",
|
||||||
"y2=uex2(tt, 2) # sol. exacte avec y_0=2\n",
|
"y2 = uex2(tt, 2) # sol. exacte avec y_0=2\n",
|
||||||
"plt.plot(tt,y1,label='y(0)=1')\n",
|
"plt.plot(tt, y1, label=\"y(0)=1\")\n",
|
||||||
"plt.plot(tt,y2,label='y(0)=2')\n",
|
"plt.plot(tt, y2, label=\"y(0)=2\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"##Tracé du champ de vecteurs\n",
|
"##Tracé du champ de vecteurs\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.title('Solution exacte pour y0 et y1')\n",
|
"plt.title(\"Solution exacte pour y0 et y1\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.xlabel('t')\n",
|
"plt.xlabel(\"t\")\n",
|
||||||
"plt.ylabel('y')\n",
|
"plt.ylabel(\"y\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"xmin, xmax = -2, 2\n",
|
"xmin, xmax = -2, 2\n",
|
||||||
"ymin, ymax = -4, 4\n",
|
"ymin, ymax = -4, 4\n",
|
||||||
"\n",
|
"\n",
|
||||||
"t=np.linspace(xmin, xmax,35) # abcisse des points de la grille \n",
|
"t = np.linspace(xmin, xmax, 35) # abcisse des points de la grille\n",
|
||||||
"y=np.linspace(ymin, ymax) # ordonnées des points de la grille \n",
|
"y = np.linspace(ymin, ymax) # ordonnées des points de la grille\n",
|
||||||
"T,Y=np.meshgrid(t,y) # grille de points dans le plan (t,y) \n",
|
"T, Y = np.meshgrid(t, y) # grille de points dans le plan (t,y)\n",
|
||||||
"U=np.ones(T.shape)/np.sqrt(1+f2(T,Y)**2) # matrice avec les composantes horizontales des vecteurs (1), normalisées \n",
|
"U = np.ones(T.shape) / np.sqrt(\n",
|
||||||
"V=f1(T,Y)/np.sqrt(1+f2(T,Y)**2) # matrice avec les composantes verticales des vecteurs (f(t,y)), normalisées \n",
|
" 1 + f2(T, Y) ** 2\n",
|
||||||
"plt.quiver(T,Y,U,V,angles='xy',scale=20,color='cyan')\n",
|
") # matrice avec les composantes horizontales des vecteurs (1), normalisées\n",
|
||||||
|
"V = f1(T, Y) / np.sqrt(\n",
|
||||||
|
" 1 + f2(T, Y) ** 2\n",
|
||||||
|
") # matrice avec les composantes verticales des vecteurs (f(t,y)), normalisées\n",
|
||||||
|
"plt.quiver(T, Y, U, V, angles=\"xy\", scale=20, color=\"cyan\")\n",
|
||||||
"plt.axis([xmin, xmax, ymin, ymax])"
|
"plt.axis([xmin, xmax, ymin, ymax])"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -339,33 +353,34 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# Euler explicite\n",
|
"# Euler explicite\n",
|
||||||
"def euler_exp(t0,T,y0,h,f):\n",
|
"def euler_exp(t0, T, y0, h, f):\n",
|
||||||
" t = np.arange(t0, t0+T+h, h)\n",
|
" t = np.arange(t0, t0 + T + h, h)\n",
|
||||||
" y = np.empty(t.size)\n",
|
" y = np.empty(t.size)\n",
|
||||||
" y[0] = y0\n",
|
" y[0] = y0\n",
|
||||||
" N = len(t)-1\n",
|
" N = len(t) - 1\n",
|
||||||
" for n in range(N):\n",
|
" for n in range(N):\n",
|
||||||
" y[n+1] = y[n] + h * f(t[n], y[n])\n",
|
" y[n + 1] = y[n] + h * f(t[n], y[n])\n",
|
||||||
" return t, y\n",
|
" return t, y\n",
|
||||||
"\n",
|
"\n",
|
||||||
"t0=0\n",
|
"\n",
|
||||||
"T=1\n",
|
"t0 = 0\n",
|
||||||
"y0=1\n",
|
"T = 1\n",
|
||||||
|
"y0 = 1\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for f, uex in zip([f1, f2], [uex1, uex2]):\n",
|
"for f, uex in zip([f1, f2], [uex1, uex2]):\n",
|
||||||
" plt.figure()\n",
|
" plt.figure()\n",
|
||||||
" t = np.arange(0, 1, 1e-3)\n",
|
" t = np.arange(0, 1, 1e-3)\n",
|
||||||
" y = uex(t, y0)\n",
|
" y = uex(t, y0)\n",
|
||||||
" plt.plot(t, y, label='Solution exacte')\n",
|
" plt.plot(t, y, label=\"Solution exacte\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" for h in [1/5, 1/10, 1/50]:\n",
|
" for h in [1 / 5, 1 / 10, 1 / 50]:\n",
|
||||||
" tt, y = euler_exp(t0, T, y0, h, f)\n",
|
" tt, y = euler_exp(t0, T, y0, h, f)\n",
|
||||||
" plt.plot(tt, y, label=f'Solution approchée pour h={h}')\n",
|
" plt.plot(tt, y, label=f\"Solution approchée pour h={h}\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
" plt.title(f\"Solutions exacte et approchées de la fonction {f.__name__}\")\n",
|
" plt.title(f\"Solutions exacte et approchées de la fonction {f.__name__}\")\n",
|
||||||
" plt.legend()\n",
|
" plt.legend()\n",
|
||||||
" plt.xlabel('t')\n",
|
" plt.xlabel(\"t\")\n",
|
||||||
" plt.ylabel('y')"
|
" plt.ylabel(\"y\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -441,12 +456,14 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# Modèle de Verhulst\n",
|
"# Modèle de Verhulst\n",
|
||||||
"n=1\n",
|
"n = 1\n",
|
||||||
"d=0.75\n",
|
"d = 0.75\n",
|
||||||
"K=200\n",
|
"K = 200\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"def fV(t, P):\n",
|
||||||
|
" return (n - d) * P * (1 - P / K)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def fV(t,P):\n",
|
|
||||||
" return (n-d)*P*(1-P/K)\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -455,20 +472,24 @@
|
|||||||
"t0, T = 0, 50\n",
|
"t0, T = 0, 50\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for P in range(1, K+100, 15):\n",
|
"for P in range(1, K + 100, 15):\n",
|
||||||
" tt, yy = euler_exp(t0, T, P, h, fV)\n",
|
" tt, yy = euler_exp(t0, T, P, h, fV)\n",
|
||||||
" plt.plot(tt, yy, label=f'Solution approchée pour h={h}')\n",
|
" plt.plot(tt, yy, label=f\"Solution approchée pour h={h}\")\n",
|
||||||
" \n",
|
|
||||||
"plt.title(f\"Solution approchée du modèle de Verhulst pour la population d'individus\")\n",
|
|
||||||
"plt.xlabel('t')\n",
|
|
||||||
"plt.ylabel('y')\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"t=np.linspace(t0, T, 35) # abcisse des points de la grille \n",
|
"plt.title(\"Solution approchée du modèle de Verhulst pour la population d'individus\")\n",
|
||||||
"y=np.linspace(0, K+100, 23) # ordonnées des points de la grille \n",
|
"plt.xlabel(\"t\")\n",
|
||||||
"T,P=np.meshgrid(t,y) # grille de points dans le plan (t,y) \n",
|
"plt.ylabel(\"y\")\n",
|
||||||
"U=np.ones(T.shape)/np.sqrt(1+fV(T,P)**2) # matrice avec les composantes horizontales des vecteurs (1), normalisées \n",
|
"\n",
|
||||||
"V=fV(T,P)/np.sqrt(1+fV(T,P)**2) # matrice avec les composantes verticales des vecteurs (f(t,y)), normalisées \n",
|
"t = np.linspace(t0, T, 35) # abcisse des points de la grille\n",
|
||||||
"plt.quiver(T,P,U,V,angles='xy',scale=20,color='cyan')\n",
|
"y = np.linspace(0, K + 100, 23) # ordonnées des points de la grille\n",
|
||||||
|
"T, P = np.meshgrid(t, y) # grille de points dans le plan (t,y)\n",
|
||||||
|
"U = np.ones(T.shape) / np.sqrt(\n",
|
||||||
|
" 1 + fV(T, P) ** 2\n",
|
||||||
|
") # matrice avec les composantes horizontales des vecteurs (1), normalisées\n",
|
||||||
|
"V = fV(T, P) / np.sqrt(\n",
|
||||||
|
" 1 + fV(T, P) ** 2\n",
|
||||||
|
") # matrice avec les composantes verticales des vecteurs (f(t,y)), normalisées\n",
|
||||||
|
"plt.quiver(T, P, U, V, angles=\"xy\", scale=20, color=\"cyan\")\n",
|
||||||
"plt.legend(fontsize=4)"
|
"plt.legend(fontsize=4)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -527,29 +548,34 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"def fS(t,P):\n",
|
"def fS(t, P):\n",
|
||||||
" return (2-np.cos(t))*P-(P**2)/2-1\n",
|
" return (2 - np.cos(t)) * P - (P**2) / 2 - 1\n",
|
||||||
"\n",
|
"\n",
|
||||||
"P0=5\n",
|
"\n",
|
||||||
"t0=0\n",
|
"P0 = 5\n",
|
||||||
"T=10\n",
|
"t0 = 0\n",
|
||||||
"h=0.1\n",
|
"T = 10\n",
|
||||||
|
"h = 0.1\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"tt, yy = euler_exp(t0, T, P0, h, fS)\n",
|
"tt, yy = euler_exp(t0, T, P0, h, fS)\n",
|
||||||
"plt.plot(tt, yy, label=f'Solution approchée pour h={h}')\n",
|
"plt.plot(tt, yy, label=f\"Solution approchée pour h={h}\")\n",
|
||||||
" \n",
|
|
||||||
"plt.title(f\"Solutions approchée du modèle de Verhulst pour une population de saumons\")\n",
|
|
||||||
"plt.legend()\n",
|
|
||||||
"plt.xlabel('t')\n",
|
|
||||||
"plt.ylabel('y')\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"t=np.linspace(t0, T, 35) # abcisse des points de la grille \n",
|
"plt.title(\"Solutions approchée du modèle de Verhulst pour une population de saumons\")\n",
|
||||||
"y=np.linspace(0, 6, 23) # ordonnées des points de la grille \n",
|
"plt.legend()\n",
|
||||||
"T,P=np.meshgrid(t,y) # grille de points dans le plan (t,y) \n",
|
"plt.xlabel(\"t\")\n",
|
||||||
"U=np.ones(T.shape)/np.sqrt(1+fS(T,P)**2) # matrice avec les composantes horizontales des vecteurs (1), normalisées \n",
|
"plt.ylabel(\"y\")\n",
|
||||||
"V=fS(T,P)/np.sqrt(1+fS(T,P)**2) # matrice avec les composantes verticales des vecteurs (f(t,y)), normalisées \n",
|
"\n",
|
||||||
"plt.quiver(T,P,U,V,angles='xy',scale=20,color='cyan')\n"
|
"t = np.linspace(t0, T, 35) # abcisse des points de la grille\n",
|
||||||
|
"y = np.linspace(0, 6, 23) # ordonnées des points de la grille\n",
|
||||||
|
"T, P = np.meshgrid(t, y) # grille de points dans le plan (t,y)\n",
|
||||||
|
"U = np.ones(T.shape) / np.sqrt(\n",
|
||||||
|
" 1 + fS(T, P) ** 2\n",
|
||||||
|
") # matrice avec les composantes horizontales des vecteurs (1), normalisées\n",
|
||||||
|
"V = fS(T, P) / np.sqrt(\n",
|
||||||
|
" 1 + fS(T, P) ** 2\n",
|
||||||
|
") # matrice avec les composantes verticales des vecteurs (f(t,y)), normalisées\n",
|
||||||
|
"plt.quiver(T, P, U, V, angles=\"xy\", scale=20, color=\"cyan\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -95,53 +95,63 @@
|
|||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"# Fonction F définissant l'EDO\n",
|
"# Fonction F définissant l'EDO\n",
|
||||||
"def F(Y):\n",
|
"def F(Y):\n",
|
||||||
" x=Y[0]\n",
|
" x = Y[0]\n",
|
||||||
" y=Y[1]\n",
|
" y = Y[1]\n",
|
||||||
" A=np.array([[0,1],[-2,-3]])\n",
|
" A = np.array([[0, 1], [-2, -3]])\n",
|
||||||
" return np.dot(A,Y)\n",
|
" return np.dot(A, Y)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# ou \n",
|
"\n",
|
||||||
"def F1(x,y):\n",
|
"# ou\n",
|
||||||
|
"def F1(x, y):\n",
|
||||||
" return y\n",
|
" return y\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def F2(x,y):\n",
|
"\n",
|
||||||
" return -2*x-3*y\n",
|
"def F2(x, y):\n",
|
||||||
|
" return -2 * x - 3 * y\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Solution exacte de Y'=AY, Y(t_0)=Y_0\n",
|
"# Solution exacte de Y'=AY, Y(t_0)=Y_0\n",
|
||||||
"def uex(t,t0,Y0):\n",
|
"def uex(t, t0, Y0):\n",
|
||||||
" U1=np.array([1,-1])\n",
|
" U1 = np.array([1, -1])\n",
|
||||||
" U2=np.array([1,-2])\n",
|
" U2 = np.array([1, -2])\n",
|
||||||
" P=np.ones((2,2))\n",
|
" P = np.ones((2, 2))\n",
|
||||||
" P[:,0]=U1\n",
|
" P[:, 0] = U1\n",
|
||||||
" P[:,1]=U2\n",
|
" P[:, 1] = U2\n",
|
||||||
" C=np.linalg.solve(P,Y0)\n",
|
" C = np.linalg.solve(P, Y0)\n",
|
||||||
" return np.array([(C[0]*np.exp(-(t-t0))*U1[0]+C[1]*np.exp(-2*(t-t0))*U2[0]),(C[0]*np.exp(-(t-t0))*U1[1]+C[1]*np.exp(-2*(t-t0))*U2[1])])\n",
|
" return np.array(\n",
|
||||||
|
" [\n",
|
||||||
|
" (C[0] * np.exp(-(t - t0)) * U1[0] + C[1] * np.exp(-2 * (t - t0)) * U2[0]),\n",
|
||||||
|
" (C[0] * np.exp(-(t - t0)) * U1[1] + C[1] * np.exp(-2 * (t - t0)) * U2[1]),\n",
|
||||||
|
" ]\n",
|
||||||
|
" )\n",
|
||||||
"\n",
|
"\n",
|
||||||
"## Représentation des solutions pour chaque valeur de la donnée initiale \n",
|
"\n",
|
||||||
|
"## Représentation des solutions pour chaque valeur de la donnée initiale\n",
|
||||||
"tt = np.linspace(-10, 10, 100)\n",
|
"tt = np.linspace(-10, 10, 100)\n",
|
||||||
"t0 = tt[0]\n",
|
"t0 = tt[0]\n",
|
||||||
"for x, y in zip([1, -2, 0, 1, 3], [2, -2, -4, -2, 4]):\n",
|
"for x, y in zip([1, -2, 0, 1, 3], [2, -2, -4, -2, 4]):\n",
|
||||||
" sol = uex(tt, t0, [x, y])\n",
|
" sol = uex(tt, t0, [x, y])\n",
|
||||||
" plt.plot(sol[0], sol[1], label=f'$((x0, y0) = ({x}, {y})$')\n",
|
" plt.plot(sol[0], sol[1], label=f\"$((x0, y0) = ({x}, {y})$\")\n",
|
||||||
" plt.scatter(x, y)\n",
|
" plt.scatter(x, y)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"#Tracé du champ de vecteurs\n",
|
"# Tracé du champ de vecteurs\n",
|
||||||
"x=np.linspace(-5,5,26)\n",
|
"x = np.linspace(-5, 5, 26)\n",
|
||||||
"y=x\n",
|
"y = x\n",
|
||||||
"xx,yy=np.meshgrid(x,y)\n",
|
"xx, yy = np.meshgrid(x, y)\n",
|
||||||
"U=F1(xx,yy)/np.sqrt(F1(xx,yy)**2+F2(xx,yy)**2)\n",
|
"U = F1(xx, yy) / np.sqrt(F1(xx, yy) ** 2 + F2(xx, yy) ** 2)\n",
|
||||||
"V=F2(xx,yy)/np.sqrt(F1(xx,yy)**2+F2(xx,yy)**2)\n",
|
"V = F2(xx, yy) / np.sqrt(F1(xx, yy) ** 2 + F2(xx, yy) ** 2)\n",
|
||||||
"plt.quiver(xx,yy,U,V,angles='xy', scale=20, color='gray')\n",
|
"plt.quiver(xx, yy, U, V, angles=\"xy\", scale=20, color=\"gray\")\n",
|
||||||
"plt.axis([-5.,5,-5,5])\n",
|
"plt.axis([-5.0, 5, -5, 5])\n",
|
||||||
"\n",
|
"\n",
|
||||||
"## Représentation des espaces propres \n",
|
"## Représentation des espaces propres\n",
|
||||||
"plt.plot(tt, -tt, label=f'SEP associé à -1', linewidth=3)\n",
|
"plt.plot(tt, -tt, label=\"SEP associé à -1\", linewidth=3)\n",
|
||||||
"plt.plot(tt, -2*tt, label=f'SEP associé à -2', linewidth=3)\n",
|
"plt.plot(tt, -2 * tt, label=\"SEP associé à -2\", linewidth=3)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.legend(fontsize=7)\n",
|
"plt.legend(fontsize=7)\n",
|
||||||
"plt.title('Représentation des solutions et champs de vecteurs pour le système (S)')"
|
"plt.title(\"Représentation des solutions et champs de vecteurs pour le système (S)\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -210,13 +220,15 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"a, b, c, d = 0.1, 5e-5, 0.04, 5e-5\n",
|
"a, b, c, d = 0.1, 5e-5, 0.04, 5e-5\n",
|
||||||
"H0, P0 = 2000, 1000\n",
|
"H0, P0 = 2000, 1000\n",
|
||||||
"He, Pe = c/d, a/b\n",
|
"He, Pe = c / d, a / b\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def F1(H, P):\n",
|
"def F1(H, P):\n",
|
||||||
" return H * (a - b*P)\n",
|
" return H * (a - b * P)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def F2(H, P):\n",
|
"def F2(H, P):\n",
|
||||||
" return P * (-c + d*H)"
|
" return P * (-c + d * H)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -256,17 +268,17 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"xx, yy = np.linspace(0, 3000, 20), np.linspace (0, 4500, 30)\n",
|
"xx, yy = np.linspace(0, 3000, 20), np.linspace(0, 4500, 30)\n",
|
||||||
"h,p = np.meshgrid(xx, yy)\n",
|
"h, p = np.meshgrid(xx, yy)\n",
|
||||||
"n=np.sqrt(F1(h,p)**2+F2(h,p)**2)\n",
|
"n = np.sqrt(F1(h, p) ** 2 + F2(h, p) ** 2)\n",
|
||||||
"plt.quiver(h, p, F1(h,p)/n, F2(h,p)/n, angles='xy', scale=20, color='gray')\n",
|
"plt.quiver(h, p, F1(h, p) / n, F2(h, p) / n, angles=\"xy\", scale=20, color=\"gray\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.vlines(He, 0, 4500, label=f'H=He={He}')\n",
|
"plt.vlines(He, 0, 4500, label=f\"H=He={He}\")\n",
|
||||||
"plt.hlines(Pe, 0, 3000, label=f'P=Pe={Pe}')\n",
|
"plt.hlines(Pe, 0, 3000, label=f\"P=Pe={Pe}\")\n",
|
||||||
"plt.scatter(He, Pe, label=f'(H0, P0) = (He, Pe)')\n",
|
"plt.scatter(He, Pe, label=\"(H0, P0) = (He, Pe)\")\n",
|
||||||
"plt.scatter(H0, P0, label=f'(H, P)=(H0, P0)=({H0},{P0})', color='red')\n",
|
"plt.scatter(H0, P0, label=f\"(H, P)=(H0, P0)=({H0},{P0})\", color=\"red\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.title('Le modèle de Lotka-Volterra')\n",
|
"plt.title(\"Le modèle de Lotka-Volterra\")\n",
|
||||||
"plt.legend(fontsize=7)"
|
"plt.legend(fontsize=7)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -374,19 +386,20 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"a, b, c, d = 0.1, 5e-5, 0.04, 5e-5\n",
|
"a, b, c, d = 0.1, 5e-5, 0.04, 5e-5\n",
|
||||||
"T=200\n",
|
"T = 200\n",
|
||||||
"H0, P0 = 2000, 1000\n",
|
"H0, P0 = 2000, 1000\n",
|
||||||
"He, Pe = c/d, a/b\n",
|
"He, Pe = c / d, a / b\n",
|
||||||
"p=0.02\n",
|
"p = 0.02\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def voltEE(T, X0, h):\n",
|
"def voltEE(T, X0, h):\n",
|
||||||
" t = np.arange(0, T+h, h)\n",
|
" t = np.arange(0, T + h, h)\n",
|
||||||
" H = 0 * t\n",
|
" H = 0 * t\n",
|
||||||
" P = 0 * t\n",
|
" P = 0 * t\n",
|
||||||
" H[0], P[0] = X0\n",
|
" H[0], P[0] = X0\n",
|
||||||
" for n in range(len(t)-1):\n",
|
" for n in range(len(t) - 1):\n",
|
||||||
" H[n+1] = H[n] + h * F1(H[n], P[n])\n",
|
" H[n + 1] = H[n] + h * F1(H[n], P[n])\n",
|
||||||
" P[n+1] = P[n] + h * F2(H[n], P[n])\n",
|
" P[n + 1] = P[n] + h * F2(H[n], P[n])\n",
|
||||||
" return np.array([t, H, P])"
|
" return np.array([t, H, P])"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -438,22 +451,22 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"t, H, P = voltEE(T, [H0, P0], 0.001)\n",
|
"t, H, P = voltEE(T, [H0, P0], 0.001)\n",
|
||||||
"plt.plot(t, H, label='Population de sardines')\n",
|
"plt.plot(t, H, label=\"Population de sardines\")\n",
|
||||||
"plt.plot(t, P, label='Population de requins')\n",
|
"plt.plot(t, P, label=\"Population de requins\")\n",
|
||||||
"plt.legend(fontsize=7)\n",
|
"plt.legend(fontsize=7)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"xx, yy = np.linspace(0, 3000, 20), np.linspace (0, 4500, 30)\n",
|
"xx, yy = np.linspace(0, 3000, 20), np.linspace(0, 4500, 30)\n",
|
||||||
"h,p = np.meshgrid(xx, yy)\n",
|
"h, p = np.meshgrid(xx, yy)\n",
|
||||||
"n=np.sqrt(F1(h,p)**2 + F2(h,p)**2)\n",
|
"n = np.sqrt(F1(h, p) ** 2 + F2(h, p) ** 2)\n",
|
||||||
"plt.quiver (h, p, F1(h,p)/n, F2(h,p)/n, angles='xy', scale=20, color='gray')\n",
|
"plt.quiver(h, p, F1(h, p) / n, F2(h, p) / n, angles=\"xy\", scale=20, color=\"gray\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.vlines(He, 0, 4500, label=f'H=He={He}')\n",
|
"plt.vlines(He, 0, 4500, label=f\"H=He={He}\")\n",
|
||||||
"plt.hlines(Pe, 0, 3000, label=f'P=Pe={Pe}')\n",
|
"plt.hlines(Pe, 0, 3000, label=f\"P=Pe={Pe}\")\n",
|
||||||
"plt.scatter(He, Pe, label=f'(H0, P0) = (He, Pe)')\n",
|
"plt.scatter(He, Pe, label=\"(H0, P0) = (He, Pe)\")\n",
|
||||||
"plt.scatter(H0, P0, label=f'(H, P)=(H0, P0)=({H0},{P0})', color='red')\n",
|
"plt.scatter(H0, P0, label=f\"(H, P)=(H0, P0)=({H0},{P0})\", color=\"red\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.title('Le modèle de Lotka-Volterra')\n",
|
"plt.title(\"Le modèle de Lotka-Volterra\")\n",
|
||||||
"plt.legend(fontsize=7)\n",
|
"plt.legend(fontsize=7)\n",
|
||||||
"plt.plot(H, P)"
|
"plt.plot(H, P)"
|
||||||
]
|
]
|
||||||
@@ -467,25 +480,28 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"a, b, c, d = 0.1, 5e-5, 0.04, 5e-5\n",
|
"a, b, c, d = 0.1, 5e-5, 0.04, 5e-5\n",
|
||||||
"T=200\n",
|
"T = 200\n",
|
||||||
"H0, P0 = 2000, 1000\n",
|
"H0, P0 = 2000, 1000\n",
|
||||||
"He, Pe = c/d, a/b\n",
|
"He, Pe = c / d, a / b\n",
|
||||||
"p=0.02\n",
|
"p = 0.02\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def F1_p(H, P):\n",
|
"def F1_p(H, P):\n",
|
||||||
" return (a - p) * H - b * H * P\n",
|
" return (a - p) * H - b * H * P\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def F2_p(H, P):\n",
|
"def F2_p(H, P):\n",
|
||||||
" return (-c-p) * P + d * H * P\n",
|
" return (-c - p) * P + d * H * P\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def voltEE_p(T, X0, h):\n",
|
"def voltEE_p(T, X0, h):\n",
|
||||||
" t = np.arange(0, T+h, h)\n",
|
" t = np.arange(0, T + h, h)\n",
|
||||||
" H = 0 * t\n",
|
" H = 0 * t\n",
|
||||||
" P = 0 * t\n",
|
" P = 0 * t\n",
|
||||||
" H[0], P[0] = X0\n",
|
" H[0], P[0] = X0\n",
|
||||||
" for n in range(len(t)-1):\n",
|
" for n in range(len(t) - 1):\n",
|
||||||
" H[n+1] = H[n] + h * F1_p(H[n], P[n])\n",
|
" H[n + 1] = H[n] + h * F1_p(H[n], P[n])\n",
|
||||||
" P[n+1] = P[n] + h * F2_p(H[n], P[n])\n",
|
" P[n + 1] = P[n] + h * F2_p(H[n], P[n])\n",
|
||||||
" return np.array([t, H, P])"
|
" return np.array([t, H, P])"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -535,22 +551,22 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"t, H, P = voltEE_p(T, [H0, P0], 0.001)\n",
|
"t, H, P = voltEE_p(T, [H0, P0], 0.001)\n",
|
||||||
"plt.plot(t, H, label='Population de sardines')\n",
|
"plt.plot(t, H, label=\"Population de sardines\")\n",
|
||||||
"plt.plot(t, P, label='Population de requins')\n",
|
"plt.plot(t, P, label=\"Population de requins\")\n",
|
||||||
"plt.legend(fontsize=7)\n",
|
"plt.legend(fontsize=7)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"xx, yy = np.linspace(0, 3000, 20), np.linspace (0, 4500, 30)\n",
|
"xx, yy = np.linspace(0, 3000, 20), np.linspace(0, 4500, 30)\n",
|
||||||
"h,p = np.meshgrid(xx, yy)\n",
|
"h, p = np.meshgrid(xx, yy)\n",
|
||||||
"n=np.sqrt(F1(h,p)**2 + F2(h,p)**2)\n",
|
"n = np.sqrt(F1(h, p) ** 2 + F2(h, p) ** 2)\n",
|
||||||
"plt.quiver (h, p, F1(h,p)/n, F2(h,p)/n, angles='xy', scale=20, color='gray')\n",
|
"plt.quiver(h, p, F1(h, p) / n, F2(h, p) / n, angles=\"xy\", scale=20, color=\"gray\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.vlines(He, 0, 4500, label=f'H=He={He}')\n",
|
"plt.vlines(He, 0, 4500, label=f\"H=He={He}\")\n",
|
||||||
"plt.hlines(Pe, 0, 3000, label=f'P=Pe={Pe}')\n",
|
"plt.hlines(Pe, 0, 3000, label=f\"P=Pe={Pe}\")\n",
|
||||||
"plt.scatter(He, Pe, label=f'(H0, P0) = (He, Pe)')\n",
|
"plt.scatter(He, Pe, label=\"(H0, P0) = (He, Pe)\")\n",
|
||||||
"plt.scatter(H0, P0, label=f'(H, P)=(H0, P0)=({H0},{P0})', color='red')\n",
|
"plt.scatter(H0, P0, label=f\"(H, P)=(H0, P0)=({H0},{P0})\", color=\"red\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.title('Le modèle de Lotka-Volterra')\n",
|
"plt.title(\"Le modèle de Lotka-Volterra\")\n",
|
||||||
"plt.legend(fontsize=7)\n",
|
"plt.legend(fontsize=7)\n",
|
||||||
"plt.plot(H, P)"
|
"plt.plot(H, P)"
|
||||||
]
|
]
|
||||||
@@ -697,46 +713,49 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"gamma=0.5\n",
|
"gamma = 0.5\n",
|
||||||
"a=0.004\n",
|
"a = 0.004\n",
|
||||||
"lm=10\n",
|
"lm = 10\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def fphi(d):\n",
|
"def fphi(d):\n",
|
||||||
" return (gamma/d)*np.log(d/a)\n",
|
" return (gamma / d) * np.log(d / a)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def F(X):\n",
|
"def F(X):\n",
|
||||||
" (n,m)=np.shape(X)\n",
|
" (n, m) = np.shape(X)\n",
|
||||||
" Y=np.zeros((n,m))\n",
|
" Y = np.zeros((n, m))\n",
|
||||||
" Y[0,:]=X[1,:]\n",
|
" Y[0, :] = X[1, :]\n",
|
||||||
" Xaux=np.zeros(m+2)\n",
|
" Xaux = np.zeros(m + 2)\n",
|
||||||
" Xaux[-1]=1\n",
|
" Xaux[-1] = 1\n",
|
||||||
" Xaux[1:-1]=X[0,:]\n",
|
" Xaux[1:-1] = X[0, :]\n",
|
||||||
" Y[1,:]=fphi(Xaux[2:]-Xaux[1:-1])-fphi(Xaux[1:-1]-Xaux[0:-2])-lm*X[1,:]\n",
|
" Y[1, :] = fphi(Xaux[2:] - Xaux[1:-1]) - fphi(Xaux[1:-1] - Xaux[0:-2]) - lm * X[1, :]\n",
|
||||||
" return Y\n",
|
" return Y\n",
|
||||||
"\n",
|
"\n",
|
||||||
"h=0.0002\n",
|
|
||||||
"T=15\n",
|
|
||||||
"N=100\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"t=np.arange(0,T+h,h)\n",
|
"h = 0.0002\n",
|
||||||
"Nt=np.size(t)\n",
|
"T = 15\n",
|
||||||
"X=np.zeros((2,N,Nt))\n",
|
"N = 100\n",
|
||||||
"R0=-1+2*np.random.rand(N)\n",
|
|
||||||
"X0=np.arange(1/(N+1),1,1/(N+1))+0.1*R0*(1/(N+1))\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"X[0,:,0]=X0\n",
|
"t = np.arange(0, T + h, h)\n",
|
||||||
"X[1,:,0]=X0\n",
|
"Nt = np.size(t)\n",
|
||||||
|
"X = np.zeros((2, N, Nt))\n",
|
||||||
|
"R0 = -1 + 2 * np.random.rand(N)\n",
|
||||||
|
"X0 = np.arange(1 / (N + 1), 1, 1 / (N + 1)) + 0.1 * R0 * (1 / (N + 1))\n",
|
||||||
|
"\n",
|
||||||
|
"X[0, :, 0] = X0\n",
|
||||||
|
"X[1, :, 0] = X0\n",
|
||||||
|
"\n",
|
||||||
|
"plt.figure(1, figsize=(24, 18))\n",
|
||||||
|
"for n in range(Nt - 1):\n",
|
||||||
|
" Y = F(X[:, :, n])\n",
|
||||||
|
" X[:, :, n + 1] = X[:, :, n] + (h / 2) * Y + (h / 2) * F(X[:, :, n] + h * Y)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(1,figsize=(24,18))\n",
|
|
||||||
"for n in range(Nt-1):\n",
|
|
||||||
" Y=F(X[:,:,n])\n",
|
|
||||||
" X[:,:,n+1]=X[:,:,n]+(h/2)*Y+(h/2)*F(X[:,:,n]+h*Y)\n",
|
|
||||||
" \n",
|
|
||||||
"for i in range(N):\n",
|
"for i in range(N):\n",
|
||||||
" plt.plot(t,X[0,i,:],'k')\n",
|
" plt.plot(t, X[0, i, :], \"k\")\n",
|
||||||
"plt.xlabel('t')\n",
|
"plt.xlabel(\"t\")\n",
|
||||||
"plt.ylabel('$x_i$')\n",
|
"plt.ylabel(\"$x_i$\")\n",
|
||||||
"plt.title('position x_i des globules rouges au cours du temps')\n"
|
"plt.title(\"position x_i des globules rouges au cours du temps\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -76,14 +76,15 @@
|
|||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"## Question 1\n",
|
"## Question 1\n",
|
||||||
"def mon_schema(t0, T, y0, h, f):\n",
|
"def mon_schema(t0, T, y0, h, f):\n",
|
||||||
" t = np.arange(t0, t0 + T + h, h)\n",
|
" t = np.arange(t0, t0 + T + h, h)\n",
|
||||||
" y = 0 * t\n",
|
" y = 0 * t\n",
|
||||||
" y[0] = y0\n",
|
" y[0] = y0\n",
|
||||||
" for n in range(len(t)-1):\n",
|
" for n in range(len(t) - 1):\n",
|
||||||
" yn1 = y[n] + h * f(t[n] + h / 2, y[n] + h/2 * f(t[n], y[n]))\n",
|
" yn1 = y[n] + h * f(t[n] + h / 2, y[n] + h / 2 * f(t[n], y[n]))\n",
|
||||||
" y[n+1] = y[n] + h / 2 * (f(t[n], y[n]) + f(t[n+1], yn1))\n",
|
" y[n + 1] = y[n] + h / 2 * (f(t[n], y[n]) + f(t[n + 1], yn1))\n",
|
||||||
" return t, y"
|
" return t, y"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -140,25 +141,27 @@
|
|||||||
"## Question 2\n",
|
"## Question 2\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# f second membre de l'EDO\n",
|
"# f second membre de l'EDO\n",
|
||||||
"def f(t,y):\n",
|
"def f(t, y):\n",
|
||||||
" return y + np.sin(t) * np.power(y, 2)\n",
|
" return y + np.sin(t) * np.power(y, 2)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"# sol. exacte de (P)\n",
|
"# sol. exacte de (P)\n",
|
||||||
"def yex(t):\n",
|
"def yex(t):\n",
|
||||||
" return 1 / (1/2 * np.exp(-t) + (np.cos(t)-np.sin(t)) / 2)\n",
|
" return 1 / (1 / 2 * np.exp(-t) + (np.cos(t) - np.sin(t)) / 2)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"t0, T = 0, 0.5\n",
|
"t0, T = 0, 0.5\n",
|
||||||
"N = 100\n",
|
"N = 100\n",
|
||||||
"y0 = 1\n",
|
"y0 = 1\n",
|
||||||
"t, y_app = mon_schema(t0, T, y0, T/N, f)\n",
|
"t, y_app = mon_schema(t0, T, y0, T / N, f)\n",
|
||||||
"y_ex = yex(t)\n",
|
"y_ex = yex(t)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(1)\n",
|
"plt.figure(1)\n",
|
||||||
"plt.plot(t, y_ex, label='Solution exacte', lw=3)\n",
|
"plt.plot(t, y_ex, label=\"Solution exacte\", lw=3)\n",
|
||||||
"plt.plot(t, y_app, '+ ', label=f'Solution approchée pour N={N}')\n",
|
"plt.plot(t, y_app, \"+ \", label=f\"Solution approchée pour N={N}\")\n",
|
||||||
"plt.title('Solutions approchées pour mon_schema')\n",
|
"plt.title(\"Solutions approchées pour mon_schema\")\n",
|
||||||
"plt.xlabel(f'$t$')\n",
|
"plt.xlabel(\"$t$\")\n",
|
||||||
"plt.ylabel(f'$y$')\n",
|
"plt.ylabel(\"$y$\")\n",
|
||||||
"plt.legend(fontsize=7)"
|
"plt.legend(fontsize=7)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -212,15 +215,17 @@
|
|||||||
"# Question 3\n",
|
"# Question 3\n",
|
||||||
"plt.figure(2)\n",
|
"plt.figure(2)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for s in range(2,11):\n",
|
"for s in range(2, 11):\n",
|
||||||
" h=(1/2)/(2**s)\n",
|
" h = (1 / 2) / (2**s)\n",
|
||||||
" t, y_app = mon_schema(t0, T, y0, h, f)\n",
|
" t, y_app = mon_schema(t0, T, y0, h, f)\n",
|
||||||
" plt.plot(t, y_app, label=f'h={h}')\n",
|
" plt.plot(t, y_app, label=f\"h={h}\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.legend(fontsize=7)\n",
|
"plt.legend(fontsize=7)\n",
|
||||||
"plt.xlabel(f'$t$')\n",
|
"plt.xlabel(\"$t$\")\n",
|
||||||
"plt.ylabel('$y^n$')\n",
|
"plt.ylabel(\"$y^n$\")\n",
|
||||||
"plt.title('Solutions approchées de (P) obtenus avec mon_schema pour différentes valeurs du pas h')"
|
"plt.title(\n",
|
||||||
|
" \"Solutions approchées de (P) obtenus avec mon_schema pour différentes valeurs du pas h\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -252,23 +257,25 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"E=[]\n",
|
"E = []\n",
|
||||||
"H=[]\n",
|
"H = []\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(3)\n",
|
"plt.figure(3)\n",
|
||||||
"for s in range(2,11):\n",
|
"for s in range(2, 11):\n",
|
||||||
" h=(1/2)/(2**s)\n",
|
" h = (1 / 2) / (2**s)\n",
|
||||||
" t, y_app = mon_schema(t0, T, y0, h, f)\n",
|
" t, y_app = mon_schema(t0, T, y0, h, f)\n",
|
||||||
" y_ex = yex(t)\n",
|
" y_ex = yex(t)\n",
|
||||||
" err = np.max(np.abs(y_app - y_ex))\n",
|
" err = np.max(np.abs(y_app - y_ex))\n",
|
||||||
" plt.plot(t, np.abs(y_app - y_ex), label=f'h={h}')\n",
|
" plt.plot(t, np.abs(y_app - y_ex), label=f\"h={h}\")\n",
|
||||||
" E.append(err)\n",
|
" E.append(err)\n",
|
||||||
" H.append(h)\n",
|
" H.append(h)\n",
|
||||||
" \n",
|
"\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.xlabel(f'$t$')\n",
|
"plt.xlabel(\"$t$\")\n",
|
||||||
"plt.ylabel('$|y(t_n) - y^n|$')\n",
|
"plt.ylabel(\"$|y(t_n) - y^n|$\")\n",
|
||||||
"plt.title('différence en valeur absolue entre sol. exacte et sol. approchée par mon_schema, pour différentes valeurs du pas h')"
|
"plt.title(\n",
|
||||||
|
" \"différence en valeur absolue entre sol. exacte et sol. approchée par mon_schema, pour différentes valeurs du pas h\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -304,13 +311,13 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"H, E = np.array(H), np.array(E)\n",
|
"H, E = np.array(H), np.array(E)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.plot(T/H, E/H, label=f'$E_h / h$')\n",
|
"plt.plot(T / H, E / H, label=\"$E_h / h$\")\n",
|
||||||
"plt.plot(T/H, E/H**2, label=f'$E_h / h^2$')\n",
|
"plt.plot(T / H, E / H**2, label=\"$E_h / h^2$\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.xlabel('N')\n",
|
"plt.xlabel(\"N\")\n",
|
||||||
"plt.ylabel('Erreur globale')\n",
|
"plt.ylabel(\"Erreur globale\")\n",
|
||||||
"plt.title('Erreur globale en fonction de N')"
|
"plt.title(\"Erreur globale en fonction de N\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -344,14 +351,16 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"plt.figure(5)\n",
|
"plt.figure(5)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.plot(np.log(H), np.log(E), '+-', label='erreur')\n",
|
"plt.plot(np.log(H), np.log(E), \"+-\", label=\"erreur\")\n",
|
||||||
"plt.plot(np.log(H), np.log(H), '-', label='droite pente 1')\n",
|
"plt.plot(np.log(H), np.log(H), \"-\", label=\"droite pente 1\")\n",
|
||||||
"plt.plot(np.log(H), 2*np.log(H), '-', label='droite pente 2')\n",
|
"plt.plot(np.log(H), 2 * np.log(H), \"-\", label=\"droite pente 2\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.title('Erreur pour la méthode mon_schema en echelle logarithmique : log(E) en fonction de log(h)')\n",
|
"plt.title(\n",
|
||||||
"plt.xlabel(f'$log(h)$')\n",
|
" \"Erreur pour la méthode mon_schema en echelle logarithmique : log(E) en fonction de log(h)\"\n",
|
||||||
"plt.ylabel(f'$log(E)$')"
|
")\n",
|
||||||
|
"plt.xlabel(\"$log(h)$\")\n",
|
||||||
|
"plt.ylabel(\"$log(E)$\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -444,24 +453,26 @@
|
|||||||
" t = np.arange(t0, t0 + T + h, h)\n",
|
" t = np.arange(t0, t0 + T + h, h)\n",
|
||||||
" y = 0 * t\n",
|
" y = 0 * t\n",
|
||||||
" y[0] = y0\n",
|
" y[0] = y0\n",
|
||||||
" for n in range(len(t)-1):\n",
|
" for n in range(len(t) - 1):\n",
|
||||||
" y[n+1] = y[n] + h * f(t[n+1], y[n+1])\n",
|
" y[n + 1] = y[n] + h * f(t[n + 1], y[n + 1])\n",
|
||||||
" return t, y\n",
|
" return t, y\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def crank(t0, T, y0, h, f):\n",
|
"def crank(t0, T, y0, h, f):\n",
|
||||||
" t = np.arange(t0, t0 + T + h, h)\n",
|
" t = np.arange(t0, t0 + T + h, h)\n",
|
||||||
" y = 0 * t\n",
|
" y = 0 * t\n",
|
||||||
" y[0] = y0\n",
|
" y[0] = y0\n",
|
||||||
" for n in range(len(t)-1):\n",
|
" for n in range(len(t) - 1):\n",
|
||||||
" y[n+1] = y[n] + h/2 * (f(t[n], y[n]) + f(t[n+1], y[n+1]))\n",
|
" y[n + 1] = y[n] + h / 2 * (f(t[n], y[n]) + f(t[n + 1], y[n + 1]))\n",
|
||||||
" return t, y\n",
|
" return t, y\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def adams(t0, T, y0, h, f):\n",
|
"def adams(t0, T, y0, h, f):\n",
|
||||||
" t = np.arange(t0, t0 + T + h, h)\n",
|
" t = np.arange(t0, t0 + T + h, h)\n",
|
||||||
" y = 0 * t\n",
|
" y = 0 * t\n",
|
||||||
" y[0] = y0\n",
|
" y[0] = y0\n",
|
||||||
" for n in range(1, len(t)-1):\n",
|
" for n in range(1, len(t) - 1):\n",
|
||||||
" y[n+1] = y[n] + h/2 * (3* f(t[n], y[n]) - f(t[n-1], y[n-1]))\n",
|
" y[n + 1] = y[n] + h / 2 * (3 * f(t[n], y[n]) - f(t[n - 1], y[n - 1]))\n",
|
||||||
" return t, y"
|
" return t, y"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -474,39 +485,41 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def euler_explicite(t0, T, y0, h, f):\n",
|
"def euler_explicite(t0, T, y0, h, f):\n",
|
||||||
" N = int(T/h)\n",
|
" N = int(T / h)\n",
|
||||||
" n = len(y0)\n",
|
" n = len(y0)\n",
|
||||||
" t = np.linspace(t0, t0 + T, N+1)\n",
|
" t = np.linspace(t0, t0 + T, N + 1)\n",
|
||||||
" y = np.zeros((N+1, n))\n",
|
" y = np.zeros((N + 1, n))\n",
|
||||||
" y[0,] = y0\n",
|
" y[0,] = y0\n",
|
||||||
" for n in range(N):\n",
|
" for n in range(N):\n",
|
||||||
" y[n+1] = y[n] + h * f(t[n], y[n])\n",
|
" y[n + 1] = y[n] + h * f(t[n], y[n])\n",
|
||||||
" return t, y\n",
|
" return t, y\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def heun(t0, T, y0, h, f):\n",
|
"def heun(t0, T, y0, h, f):\n",
|
||||||
" N = int(T/h)\n",
|
" N = int(T / h)\n",
|
||||||
" n = len(y0)\n",
|
" n = len(y0)\n",
|
||||||
" t = np.linspace(t0, t0 + T, N+1)\n",
|
" t = np.linspace(t0, t0 + T, N + 1)\n",
|
||||||
" y = np.zeros((N+1, n))\n",
|
" y = np.zeros((N + 1, n))\n",
|
||||||
" y[0,] = y0\n",
|
" y[0,] = y0\n",
|
||||||
" for n in range(N):\n",
|
" for n in range(N):\n",
|
||||||
" p1 = f(t[n], y[n])\n",
|
" p1 = f(t[n], y[n])\n",
|
||||||
" p2 = f(t[n] + h, y[n] + h * p1)\n",
|
" p2 = f(t[n] + h, y[n] + h * p1)\n",
|
||||||
" y[n+1] = y[n] + h/2 * (p1 + p2)\n",
|
" y[n + 1] = y[n] + h / 2 * (p1 + p2)\n",
|
||||||
" return t, y\n",
|
" return t, y\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def runge(t0, T, y0, h, f):\n",
|
"def runge(t0, T, y0, h, f):\n",
|
||||||
" N = int(T/h)\n",
|
" N = int(T / h)\n",
|
||||||
" n = len(y0)\n",
|
" n = len(y0)\n",
|
||||||
" t = np.linspace(t0, t0 + T, N+1)\n",
|
" t = np.linspace(t0, t0 + T, N + 1)\n",
|
||||||
" y = np.zeros((N+1, n))\n",
|
" y = np.zeros((N + 1, n))\n",
|
||||||
" y[0,] = y0\n",
|
" y[0,] = y0\n",
|
||||||
" for n in range(N):\n",
|
" for n in range(N):\n",
|
||||||
" p1 = f(t[n], y[n])\n",
|
" p1 = f(t[n], y[n])\n",
|
||||||
" p2 = f(t[n] + h/2, y[n] + h/2 * p1)\n",
|
" p2 = f(t[n] + h / 2, y[n] + h / 2 * p1)\n",
|
||||||
" p3 = f(t[n] + h/2, y[n] + h/2 * p2)\n",
|
" p3 = f(t[n] + h / 2, y[n] + h / 2 * p2)\n",
|
||||||
" p4 = f(t[n] + h, y[n] + h* p3)\n",
|
" p4 = f(t[n] + h, y[n] + h * p3)\n",
|
||||||
" y[n+1] = y[n] + h/6 * (p1 + 2*p2 + 2*p3 + p4)\n",
|
" y[n + 1] = y[n] + h / 6 * (p1 + 2 * p2 + 2 * p3 + p4)\n",
|
||||||
" return t, y"
|
" return t, y"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -624,13 +637,16 @@
|
|||||||
"# Question 1\n",
|
"# Question 1\n",
|
||||||
"a, b, c = 0.1, 2, 1\n",
|
"a, b, c = 0.1, 2, 1\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"# f second membre de l'EDO\n",
|
"# f second membre de l'EDO\n",
|
||||||
"def f1(t,y):\n",
|
"def f1(t, y):\n",
|
||||||
" return c * y * (1 - y/b)\n",
|
" return c * y * (1 - y / b)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# sol. exacte de (P1)\n",
|
"# sol. exacte de (P1)\n",
|
||||||
"def yex1(t):\n",
|
"def yex1(t):\n",
|
||||||
" return b / (1 + (b-a)/a * np.exp(-c*t))\n",
|
" return b / (1 + (b - a) / a * np.exp(-c * t))\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"t0, T = 0, 15\n",
|
"t0, T = 0, 15\n",
|
||||||
"h = 0.2\n",
|
"h = 0.2\n",
|
||||||
@@ -639,25 +655,27 @@
|
|||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"for schema in [euler_explicite, heun, runge]:\n",
|
"for schema in [euler_explicite, heun, runge]:\n",
|
||||||
" t, y_app = schema(t0, T, y0, h, f1)\n",
|
" t, y_app = schema(t0, T, y0, h, f1)\n",
|
||||||
" plt.plot(t, y_app.ravel(), '+ ', label=f'Solution approchée par {schema.__name__}')\n",
|
" plt.plot(t, y_app.ravel(), \"+ \", label=f\"Solution approchée par {schema.__name__}\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"t = np.arange(t0, t0+T+h, h)\n",
|
"t = np.arange(t0, t0 + T + h, h)\n",
|
||||||
"y_ex = yex1(t)\n",
|
"y_ex = yex1(t)\n",
|
||||||
"plt.plot(t, y_ex, label='Solution exacte', lw=1)\n",
|
"plt.plot(t, y_ex, label=\"Solution exacte\", lw=1)\n",
|
||||||
"plt.title(f'Solutions approchées pour le schema {schema.__name__}')\n",
|
"plt.title(f\"Solutions approchées pour le schema {schema.__name__}\")\n",
|
||||||
"plt.xlabel(f'$t$')\n",
|
"plt.xlabel(\"$t$\")\n",
|
||||||
"plt.ylabel(f'$y$')\n",
|
"plt.ylabel(\"$y$\")\n",
|
||||||
"plt.legend(fontsize=7)\n",
|
"plt.legend(fontsize=7)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"for schema in [euler_explicite, heun, runge]: \n",
|
"for schema in [euler_explicite, heun, runge]:\n",
|
||||||
" t, y_app = schema(t0, T, y0, h, f1)\n",
|
" t, y_app = schema(t0, T, y0, h, f1)\n",
|
||||||
" plt.plot(t, np.abs(y_app.ravel() - yex1(t)), label=f'Schema {schema.__name__}')\n",
|
" plt.plot(t, np.abs(y_app.ravel() - yex1(t)), label=f\"Schema {schema.__name__}\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.xlabel(f'$t$')\n",
|
"plt.xlabel(\"$t$\")\n",
|
||||||
"plt.ylabel('$|y(t_n) - y^n|$')\n",
|
"plt.ylabel(\"$|y(t_n) - y^n|$\")\n",
|
||||||
"plt.title(f'différence en valeur absolue entre sol. exacte et sol. approchée, pour différents schemas')"
|
"plt.title(\n",
|
||||||
|
" \"différence en valeur absolue entre sol. exacte et sol. approchée, pour différents schemas\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -696,24 +714,26 @@
|
|||||||
" Z[1] = -Y[0] + np.cos(t)\n",
|
" Z[1] = -Y[0] + np.cos(t)\n",
|
||||||
" return Z\n",
|
" return Z\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def yexF(t):\n",
|
"def yexF(t):\n",
|
||||||
" return 1/2 * np.sin(t) * t + 5 * np.cos(t) + np.sin(t),\n",
|
" return (1 / 2 * np.sin(t) * t + 5 * np.cos(t) + np.sin(t),)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"t0, T = 0, 15\n",
|
"t0, T = 0, 15\n",
|
||||||
"h = 0.2\n",
|
"h = 0.2\n",
|
||||||
"Y0 = np.array([5,1])\n",
|
"Y0 = np.array([5, 1])\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"for schema in [euler_explicite, heun, runge]:\n",
|
"for schema in [euler_explicite, heun, runge]:\n",
|
||||||
" t, y_app = schema(t0, T, Y0, h, F)\n",
|
" t, y_app = schema(t0, T, Y0, h, F)\n",
|
||||||
" plt.plot(t, y_app[:,0], '+ ', label=f'Solution approchée par {schema.__name__}')\n",
|
" plt.plot(t, y_app[:, 0], \"+ \", label=f\"Solution approchée par {schema.__name__}\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"t = np.arange(t0, t0+T+h, h)\n",
|
"t = np.arange(t0, t0 + T + h, h)\n",
|
||||||
"y_ex = yexF(t)\n",
|
"y_ex = yexF(t)\n",
|
||||||
"plt.plot(t, y_ex[0], label='Solution exacte', lw=3)\n",
|
"plt.plot(t, y_ex[0], label=\"Solution exacte\", lw=3)\n",
|
||||||
"plt.title('Solutions approchées par differents schemas')\n",
|
"plt.title(\"Solutions approchées par differents schemas\")\n",
|
||||||
"plt.xlabel(f'$t$')\n",
|
"plt.xlabel(\"$t$\")\n",
|
||||||
"plt.ylabel(f'$y$')\n",
|
"plt.ylabel(\"$y$\")\n",
|
||||||
"plt.legend(fontsize=7)"
|
"plt.legend(fontsize=7)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -730,16 +750,19 @@
|
|||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
"# Question 3\n",
|
"# Question 3\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"# f second membre de l'EDO\n",
|
"# f second membre de l'EDO\n",
|
||||||
"def f3(t,y):\n",
|
"def f3(t, y):\n",
|
||||||
" return (np.cos(t) - y) / (1+t)\n",
|
" return (np.cos(t) - y) / (1 + t)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# sol. exacte de (P1)\n",
|
"# sol. exacte de (P1)\n",
|
||||||
"def yex3(t):\n",
|
"def yex3(t):\n",
|
||||||
" return (np.sin(t) - 1/4) / (1 + t)\n",
|
" return (np.sin(t) - 1 / 4) / (1 + t)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"t0, T = 0, 10\n",
|
"t0, T = 0, 10\n",
|
||||||
"y0 = np.array([-1/4])"
|
"y0 = np.array([-1 / 4])"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -793,15 +816,17 @@
|
|||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"for schema in [euler_explicite, heun, runge]:\n",
|
"for schema in [euler_explicite, heun, runge]:\n",
|
||||||
" plt.figure()\n",
|
" plt.figure()\n",
|
||||||
" for s in range(2,11):\n",
|
" for s in range(2, 11):\n",
|
||||||
" h=1/(2**s)\n",
|
" h = 1 / (2**s)\n",
|
||||||
" t, y_app = schema(t0, T, y0, h, f3)\n",
|
" t, y_app = schema(t0, T, y0, h, f3)\n",
|
||||||
" plt.plot(t, y_app, label=f'h={h}')\n",
|
" plt.plot(t, y_app, label=f\"h={h}\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" plt.legend(fontsize=7)\n",
|
" plt.legend(fontsize=7)\n",
|
||||||
" plt.xlabel(f'$t$')\n",
|
" plt.xlabel(\"$t$\")\n",
|
||||||
" plt.ylabel('$y^n$')\n",
|
" plt.ylabel(\"$y^n$\")\n",
|
||||||
" plt.title(f'Solutions approchées de (P) obtenus avec {schema.__name__} pour différentes valeurs du pas h')"
|
" plt.title(\n",
|
||||||
|
" f\"Solutions approchées de (P) obtenus avec {schema.__name__} pour différentes valeurs du pas h\"\n",
|
||||||
|
" )"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -846,22 +871,24 @@
|
|||||||
"for schema in [euler_explicite, heun, runge]:\n",
|
"for schema in [euler_explicite, heun, runge]:\n",
|
||||||
" H, E = [], []\n",
|
" H, E = [], []\n",
|
||||||
" plt.figure()\n",
|
" plt.figure()\n",
|
||||||
" for s in range(2,11):\n",
|
" for s in range(2, 11):\n",
|
||||||
" h=1/(2**s)\n",
|
" h = 1 / (2**s)\n",
|
||||||
" t, y_app = schema(t0, T, y0, h, f3)\n",
|
" t, y_app = schema(t0, T, y0, h, f3)\n",
|
||||||
" E.append(np.max(np.abs(yex3(t) - y_app.ravel())))\n",
|
" E.append(np.max(np.abs(yex3(t) - y_app.ravel())))\n",
|
||||||
" H.append(h)\n",
|
" H.append(h)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" H, E = np.array(H), np.array(E)\n",
|
" H, E = np.array(H), np.array(E)\n",
|
||||||
" plt.plot(np.log(H), np.log(E), '+-', label='erreur')\n",
|
" plt.plot(np.log(H), np.log(E), \"+-\", label=\"erreur\")\n",
|
||||||
" plt.plot(np.log(H), np.log(H), '-', label='droite pente 1')\n",
|
" plt.plot(np.log(H), np.log(H), \"-\", label=\"droite pente 1\")\n",
|
||||||
" plt.plot(np.log(H), 2*np.log(H), '-', label='droite pente 2')\n",
|
" plt.plot(np.log(H), 2 * np.log(H), \"-\", label=\"droite pente 2\")\n",
|
||||||
" plt.plot(np.log(H), 3*np.log(H), '-', label='droite pente 3')\n",
|
" plt.plot(np.log(H), 3 * np.log(H), \"-\", label=\"droite pente 3\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
" plt.legend()\n",
|
" plt.legend()\n",
|
||||||
" plt.title(f'Erreur pour la méthode {schema.__name__} en echelle logarithmique : log(E) en fonction de log(h)')\n",
|
" plt.title(\n",
|
||||||
" plt.xlabel(f'$log(h)$')\n",
|
" f\"Erreur pour la méthode {schema.__name__} en echelle logarithmique : log(E) en fonction de log(h)\"\n",
|
||||||
" plt.ylabel(f'$log(E)$')"
|
" )\n",
|
||||||
|
" plt.xlabel(\"$log(h)$\")\n",
|
||||||
|
" plt.ylabel(\"$log(E)$\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -943,19 +970,20 @@
|
|||||||
"a = 5\n",
|
"a = 5\n",
|
||||||
"t0, T = 0, 20\n",
|
"t0, T = 0, 20\n",
|
||||||
"H = [0.1, 0.05, 0.025]\n",
|
"H = [0.1, 0.05, 0.025]\n",
|
||||||
"Y0 = np.array([1/10, 1])\n",
|
"Y0 = np.array([1 / 10, 1])\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def P(t, Y):\n",
|
"def P(t, Y):\n",
|
||||||
" return np.array([Y[1], (a - Y[0]**2) * Y[1] - Y[0]])\n",
|
" return np.array([Y[1], (a - Y[0] ** 2) * Y[1] - Y[0]])\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for schema in [euler_explicite, heun, runge]:\n",
|
"for schema in [euler_explicite, heun, runge]:\n",
|
||||||
" plt.figure()\n",
|
" plt.figure()\n",
|
||||||
" for h in H:\n",
|
" for h in H:\n",
|
||||||
" t, y_app = schema(t0, T, Y0, h, P)\n",
|
" t, y_app = schema(t0, T, Y0, h, P)\n",
|
||||||
" plt.plot(t, y_app[:,0], '+ ', label=f'Solution approchée pour h={h}')\n",
|
" plt.plot(t, y_app[:, 0], \"+ \", label=f\"Solution approchée pour h={h}\")\n",
|
||||||
" plt.legend()\n",
|
" plt.legend()\n",
|
||||||
" plt.title(f'Solutions approchees pour differents pas h par {schema.__name__}')\n",
|
" plt.title(f\"Solutions approchees pour differents pas h par {schema.__name__}\")"
|
||||||
" "
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -240,22 +240,25 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def A(M):\n",
|
"def A(M):\n",
|
||||||
" return 2 * np.eye(M) - np.eye(M, k=-1) - np.eye(M, k=1)\n",
|
" return 2 * np.eye(M) - np.eye(M, k=-1) - np.eye(M, k=1)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def solution_approchée(f, M, a=0, b=1, ua=0, ub=0):\n",
|
"def solution_approchée(f, M, a=0, b=1, ua=0, ub=0):\n",
|
||||||
" X = np.linspace(a, b + 1 if b == 0 else b, M+2)\n",
|
" X = np.linspace(a, b + 1 if b == 0 else b, M + 2)\n",
|
||||||
" U = np.zeros(M+2)\n",
|
" U = np.zeros(M + 2)\n",
|
||||||
" U[0], U[-1] = ua, ub\n",
|
" U[0], U[-1] = ua, ub\n",
|
||||||
" \n",
|
"\n",
|
||||||
" h = (b-a)/(M+1)\n",
|
" h = (b - a) / (M + 1)\n",
|
||||||
"\n",
|
"\n",
|
||||||
" delta = np.zeros(M)\n",
|
" delta = np.zeros(M)\n",
|
||||||
" delta[0], delta[-1] = ua/np.power(h, 2), ub/np.power(h, 2)\n",
|
" delta[0], delta[-1] = ua / np.power(h, 2), ub / np.power(h, 2)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" U[1:-1] = np.linalg.solve(A(M), h**2 * (f(X)[1:-1] + delta))\n",
|
" U[1:-1] = np.linalg.solve(A(M), h**2 * (f(X)[1:-1] + delta))\n",
|
||||||
" return X, U"
|
" return X, U"
|
||||||
]
|
]
|
||||||
@@ -290,22 +293,25 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"M = 50\n",
|
"M = 50\n",
|
||||||
"h = 1/(M+1)\n",
|
"h = 1 / (M + 1)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def f1(x):\n",
|
"def f1(x):\n",
|
||||||
" return (2 * np.pi)**2 * np.sin(2 * np.pi * x)\n",
|
" return (2 * np.pi) ** 2 * np.sin(2 * np.pi * x)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def u1(x):\n",
|
"def u1(x):\n",
|
||||||
" return np.sin(2 * np.pi * x)\n",
|
" return np.sin(2 * np.pi * x)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"x, U_app = solution_approchée(f1, M)\n",
|
"x, U_app = solution_approchée(f1, M)\n",
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"plt.scatter(x, U_app, label=f\"$A_M U_h = h² F$\")\n",
|
"plt.scatter(x, U_app, label=\"$A_M U_h = h² F$\")\n",
|
||||||
"plt.plot(x, u1(x), label='Solution exacte', color='red')\n",
|
"plt.plot(x, u1(x), label=\"Solution exacte\", color=\"red\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.ylabel('f(x)')\n",
|
"plt.ylabel(\"f(x)\")\n",
|
||||||
"plt.xlabel('x')\n",
|
"plt.xlabel(\"x\")\n",
|
||||||
"plt.title(f\"$-u''=f(x)$\")"
|
"plt.title(\"$-u''=f(x)$\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -340,21 +346,23 @@
|
|||||||
"H, E = [], []\n",
|
"H, E = [], []\n",
|
||||||
"for k in range(2, 12):\n",
|
"for k in range(2, 12):\n",
|
||||||
" M = 2**k\n",
|
" M = 2**k\n",
|
||||||
" h = 1/(M+1)\n",
|
" h = 1 / (M + 1)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" x, U_app = solution_approchée(f1, M)\n",
|
" x, U_app = solution_approchée(f1, M)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" e = np.abs(u1(x) - U_app)\n",
|
" e = np.abs(u1(x) - U_app)\n",
|
||||||
" plt.plot(x, e, label=f'{h}')\n",
|
" plt.plot(x, e, label=f\"{h}\")\n",
|
||||||
" E.append(np.max(e))\n",
|
" E.append(np.max(e))\n",
|
||||||
" H.append(h)\n",
|
" H.append(h)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"H, E = np.array(H), np.array(E) \n",
|
"H, E = np.array(H), np.array(E)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.xlabel('$h$')\n",
|
"plt.xlabel(\"$h$\")\n",
|
||||||
"plt.ylabel('$\\max_{j=0,\\dots,M+1}|u(x_j)-u_j|$')\n",
|
"plt.ylabel(\"$\\max_{j=0,\\dots,M+1}|u(x_j)-u_j|$\")\n",
|
||||||
"plt.legend(fontsize=7)\n",
|
"plt.legend(fontsize=7)\n",
|
||||||
"plt.title('Différence en valeur absolue entre la solution exacte et la solution approchée')"
|
"plt.title(\n",
|
||||||
|
" \"Différence en valeur absolue entre la solution exacte et la solution approchée\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -387,12 +395,12 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"plt.plot(H, E/H, label=f'$E_h / h$')\n",
|
"plt.plot(H, E / H, label=\"$E_h / h$\")\n",
|
||||||
"plt.plot(H, E/H**2, label=f'$E_h / h^2$')\n",
|
"plt.plot(H, E / H**2, label=\"$E_h / h^2$\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.xlabel('$h$')\n",
|
"plt.xlabel(\"$h$\")\n",
|
||||||
"plt.ylabel('Erreur globale')\n",
|
"plt.ylabel(\"Erreur globale\")\n",
|
||||||
"plt.title('Erreur globale en fonction de $h$')"
|
"plt.title(\"Erreur globale en fonction de $h$\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -425,13 +433,15 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"plt.plot(np.log(H), np.log(E), '+-', label='erreur')\n",
|
"plt.plot(np.log(H), np.log(E), \"+-\", label=\"erreur\")\n",
|
||||||
"plt.plot(np.log(H), np.log(H), '-', label='droite pente 1')\n",
|
"plt.plot(np.log(H), np.log(H), \"-\", label=\"droite pente 1\")\n",
|
||||||
"plt.plot(np.log(H), 2*np.log(H), '-', label='droite pente 2')\n",
|
"plt.plot(np.log(H), 2 * np.log(H), \"-\", label=\"droite pente 2\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.xlabel(f'$log(h)$')\n",
|
"plt.xlabel(\"$log(h)$\")\n",
|
||||||
"plt.ylabel(f'$log(E)$')\n",
|
"plt.ylabel(\"$log(E)$\")\n",
|
||||||
"plt.title('Erreur pour la méthode mon_schema en echelle logarithmique : log(E) en fonction de log(h)')"
|
"plt.title(\n",
|
||||||
|
" \"Erreur pour la méthode mon_schema en echelle logarithmique : log(E) en fonction de log(h)\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -509,27 +519,31 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
|
"\n",
|
||||||
"%matplotlib inline\n",
|
"%matplotlib inline\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ua, ub = 1/2, 1/3\n",
|
"ua, ub = 1 / 2, 1 / 3\n",
|
||||||
"a, b = 1, 2\n",
|
"a, b = 1, 2\n",
|
||||||
"M = 49\n",
|
"M = 49\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def f2(x):\n",
|
"def f2(x):\n",
|
||||||
" return -2/np.power((x+1), 3)\n",
|
" return -2 / np.power((x + 1), 3)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def u2(x):\n",
|
"def u2(x):\n",
|
||||||
" return 1/(x+1)\n",
|
" return 1 / (x + 1)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"x, U_app = solution_approchée(f2, M, a, b, ua, ub)\n",
|
"x, U_app = solution_approchée(f2, M, a, b, ua, ub)\n",
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"plt.scatter(x, U_app, label=f\"$A_M U_h = h² F$\")\n",
|
"plt.scatter(x, U_app, label=\"$A_M U_h = h² F$\")\n",
|
||||||
"plt.plot(x, u2(x), label='Solution exacte', color='red')\n",
|
"plt.plot(x, u2(x), label=\"Solution exacte\", color=\"red\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.ylabel('f(x)')\n",
|
"plt.ylabel(\"f(x)\")\n",
|
||||||
"plt.xlabel('x')\n",
|
"plt.xlabel(\"x\")\n",
|
||||||
"plt.title(f\"$-u''=f(x)$\")"
|
"plt.title(\"$-u''=f(x)$\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -565,19 +579,21 @@
|
|||||||
"H, E = [], []\n",
|
"H, E = [], []\n",
|
||||||
"for k in range(2, 12):\n",
|
"for k in range(2, 12):\n",
|
||||||
" M = 2**k\n",
|
" M = 2**k\n",
|
||||||
" h = (b-a)/(M+1)\n",
|
" h = (b - a) / (M + 1)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" x, U_app = solution_approchée(f2, M, a, b, ua, ub)\n",
|
" x, U_app = solution_approchée(f2, M, a, b, ua, ub)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" e = np.abs(u2(x) - U_app)\n",
|
" e = np.abs(u2(x) - U_app)\n",
|
||||||
" plt.plot(x, e, label=f'{h}')\n",
|
" plt.plot(x, e, label=f\"{h}\")\n",
|
||||||
" E.append(np.max(e))\n",
|
" E.append(np.max(e))\n",
|
||||||
" H.append(h)\n",
|
" H.append(h)\n",
|
||||||
" \n",
|
"\n",
|
||||||
"plt.xlabel('$h$')\n",
|
"plt.xlabel(\"$h$\")\n",
|
||||||
"plt.ylabel('$\\max_{j=0,\\dots,M+1}|u(x_j)-u_j|$')\n",
|
"plt.ylabel(\"$\\max_{j=0,\\dots,M+1}|u(x_j)-u_j|$\")\n",
|
||||||
"plt.legend(fontsize=7)\n",
|
"plt.legend(fontsize=7)\n",
|
||||||
"plt.title('Différence en valeur absolue entre la solution exacte et la solution approchée')"
|
"plt.title(\n",
|
||||||
|
" \"Différence en valeur absolue entre la solution exacte et la solution approchée\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -609,14 +625,14 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"H, E = np.array(H), np.array(E) \n",
|
"H, E = np.array(H), np.array(E)\n",
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"plt.plot(H, E/H, label=f'$E_h / h$')\n",
|
"plt.plot(H, E / H, label=\"$E_h / h$\")\n",
|
||||||
"plt.plot(H, E/H**2, label=f'$E_h / h^2$')\n",
|
"plt.plot(H, E / H**2, label=\"$E_h / h^2$\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.xlabel('$h$')\n",
|
"plt.xlabel(\"$h$\")\n",
|
||||||
"plt.ylabel('Erreur globale')\n",
|
"plt.ylabel(\"Erreur globale\")\n",
|
||||||
"plt.title('Erreur globale en fonction de $h$')"
|
"plt.title(\"Erreur globale en fonction de $h$\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -649,13 +665,15 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"plt.plot(np.log(H), np.log(E), '+-', label='erreur')\n",
|
"plt.plot(np.log(H), np.log(E), \"+-\", label=\"erreur\")\n",
|
||||||
"plt.plot(np.log(H), np.log(H), '-', label='droite pente 1')\n",
|
"plt.plot(np.log(H), np.log(H), \"-\", label=\"droite pente 1\")\n",
|
||||||
"plt.plot(np.log(H), 2*np.log(H), '-', label='droite pente 2')\n",
|
"plt.plot(np.log(H), 2 * np.log(H), \"-\", label=\"droite pente 2\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.xlabel(f'$log(h)$')\n",
|
"plt.xlabel(\"$log(h)$\")\n",
|
||||||
"plt.ylabel(f'$log(E)$')\n",
|
"plt.ylabel(\"$log(E)$\")\n",
|
||||||
"plt.title('Erreur pour la méthode mon_schema en echelle logarithmique : log(E) en fonction de log(h)')"
|
"plt.title(\n",
|
||||||
|
" \"Erreur pour la méthode mon_schema en echelle logarithmique : log(E) en fonction de log(h)\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -732,22 +750,25 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"def An(M, h):\n",
|
"def An(M, h):\n",
|
||||||
" mat = 2*np.eye(M) - np.eye(M, k=1) - np.eye(M, k=-1)\n",
|
" mat = 2 * np.eye(M) - np.eye(M, k=1) - np.eye(M, k=-1)\n",
|
||||||
" mat[0,0] = 1\n",
|
" mat[0, 0] = 1\n",
|
||||||
" mat[-1, -1] = 1\n",
|
" mat[-1, -1] = 1\n",
|
||||||
" return mat + h**2 * np.eye(M)\n",
|
" return mat + h**2 * np.eye(M)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def f3(x):\n",
|
"def f3(x):\n",
|
||||||
" return (np.power(2 * np.pi, 2) + 1 ) * np.cos(2*np.pi * x)\n",
|
" return (np.power(2 * np.pi, 2) + 1) * np.cos(2 * np.pi * x)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def u3(x):\n",
|
"def u3(x):\n",
|
||||||
" return np.cos(2*np.pi * x)\n",
|
" return np.cos(2 * np.pi * x)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def solution_neumann(f, M, a, b):\n",
|
"def solution_neumann(f, M, a, b):\n",
|
||||||
" X = np.linspace(a, b, M+2)\n",
|
" X = np.linspace(a, b, M + 2)\n",
|
||||||
" U = np.zeros(M+2)\n",
|
" U = np.zeros(M + 2)\n",
|
||||||
" h = 1/(M+1)\n",
|
" h = 1 / (M + 1)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" U[1:-1] = np.linalg.solve(An(M, h), h**2 * f3(X[1:-1]))\n",
|
" U[1:-1] = np.linalg.solve(An(M, h), h**2 * f3(X[1:-1]))\n",
|
||||||
" U[0], U[-1] = U[1], U[-2]\n",
|
" U[0], U[-1] = U[1], U[-2]\n",
|
||||||
" return X, U\n",
|
" return X, U\n",
|
||||||
@@ -759,12 +780,14 @@
|
|||||||
"for M in [49, 99, 499]:\n",
|
"for M in [49, 99, 499]:\n",
|
||||||
" x, U_app = solution_neumann(f3, M, a, b)\n",
|
" x, U_app = solution_neumann(f3, M, a, b)\n",
|
||||||
"\n",
|
"\n",
|
||||||
" plt.scatter(x, U_app, marker='+', s=3, label=\"$h^2({A_N}_h + I_M)U = h^2F$ pour M={M}\")\n",
|
" plt.scatter(\n",
|
||||||
"plt.plot(x, u3(x), label='Solution exacte', color='red')\n",
|
" x, U_app, marker=\"+\", s=3, label=\"$h^2({A_N}_h + I_M)U = h^2F$ pour M={M}\"\n",
|
||||||
|
" )\n",
|
||||||
|
"plt.plot(x, u3(x), label=\"Solution exacte\", color=\"red\")\n",
|
||||||
"plt.legend(fontsize=8)\n",
|
"plt.legend(fontsize=8)\n",
|
||||||
"plt.ylabel('f(x)')\n",
|
"plt.ylabel(\"f(x)\")\n",
|
||||||
"plt.xlabel('x')\n",
|
"plt.xlabel(\"x\")\n",
|
||||||
"plt.title(f\"$-u''(x) + u(x)=f(x)$\")"
|
"plt.title(\"$-u''(x) + u(x)=f(x)$\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -800,19 +823,21 @@
|
|||||||
"H, E = [], []\n",
|
"H, E = [], []\n",
|
||||||
"for k in range(2, 12):\n",
|
"for k in range(2, 12):\n",
|
||||||
" M = 2**k\n",
|
" M = 2**k\n",
|
||||||
" h = (b-a)/(M+1)\n",
|
" h = (b - a) / (M + 1)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" x, U_app = solution_neumann(f3, M, a, b)\n",
|
" x, U_app = solution_neumann(f3, M, a, b)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" e = np.abs(u3(x) - U_app)\n",
|
" e = np.abs(u3(x) - U_app)\n",
|
||||||
" plt.plot(x, e, label=f'{h}')\n",
|
" plt.plot(x, e, label=f\"{h}\")\n",
|
||||||
" E.append(np.max(e))\n",
|
" E.append(np.max(e))\n",
|
||||||
" H.append(h)\n",
|
" H.append(h)\n",
|
||||||
" \n",
|
"\n",
|
||||||
"plt.xlabel('$h$')\n",
|
"plt.xlabel(\"$h$\")\n",
|
||||||
"plt.ylabel('$\\max_{j=0,\\dots,M+1}|u(x_j)-u_j|$')\n",
|
"plt.ylabel(\"$\\max_{j=0,\\dots,M+1}|u(x_j)-u_j|$\")\n",
|
||||||
"plt.legend(fontsize=7)\n",
|
"plt.legend(fontsize=7)\n",
|
||||||
"plt.title('Différence en valeur absolue entre la solution exacte et la solution approchée')"
|
"plt.title(\n",
|
||||||
|
" \"Différence en valeur absolue entre la solution exacte et la solution approchée\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -845,13 +870,15 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"plt.plot(np.log(H), np.log(E), '+-', label='erreur')\n",
|
"plt.plot(np.log(H), np.log(E), \"+-\", label=\"erreur\")\n",
|
||||||
"plt.plot(np.log(H), np.log(H), '-', label='droite pente 1')\n",
|
"plt.plot(np.log(H), np.log(H), \"-\", label=\"droite pente 1\")\n",
|
||||||
"plt.plot(np.log(H), 2*np.log(H), '-', label='droite pente 2')\n",
|
"plt.plot(np.log(H), 2 * np.log(H), \"-\", label=\"droite pente 2\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.xlabel(f'$log(h)$')\n",
|
"plt.xlabel(\"$log(h)$\")\n",
|
||||||
"plt.ylabel(f'$log(E)$')\n",
|
"plt.ylabel(\"$log(E)$\")\n",
|
||||||
"plt.title('Erreur pour la méthode mon_schema en echelle logarithmique : log(E) en fonction de log(h)')"
|
"plt.title(\n",
|
||||||
|
" \"Erreur pour la méthode mon_schema en echelle logarithmique : log(E) en fonction de log(h)\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -959,7 +986,11 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def v(x):\n",
|
"def v(x):\n",
|
||||||
" return 4*np.exp(-500*np.square(x-.8)) + np.exp(-50*np.square(x-.2))+.5*np.random.random(x.shape)"
|
" return (\n",
|
||||||
|
" 4 * np.exp(-500 * np.square(x - 0.8))\n",
|
||||||
|
" + np.exp(-50 * np.square(x - 0.2))\n",
|
||||||
|
" + 0.5 * np.random.random(x.shape)\n",
|
||||||
|
" )"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -48,10 +48,10 @@
|
|||||||
"nb_repl = 100000\n",
|
"nb_repl = 100000\n",
|
||||||
"sample = np.random.exponential(lam, nb_repl)\n",
|
"sample = np.random.exponential(lam, nb_repl)\n",
|
||||||
"intervalle = np.linspace(0, 5, 100)\n",
|
"intervalle = np.linspace(0, 5, 100)\n",
|
||||||
"plt.hist(sample, bins=intervalle, density=True, label='Echantillon')\n",
|
"plt.hist(sample, bins=intervalle, density=True, label=\"Echantillon\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"densite = stats.expon().pdf\n",
|
"densite = stats.expon().pdf\n",
|
||||||
"plt.plot(intervalle, densite(intervalle), label='Fonction densité')\n",
|
"plt.plot(intervalle, densite(intervalle), label=\"Fonction densité\")\n",
|
||||||
"plt.legend()"
|
"plt.legend()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -86,15 +86,15 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"np_repl = 10000\n",
|
"np_repl = 10000\n",
|
||||||
"sampleX, sampleY = 2*np.random.rand(np_repl)-1, 2*np.random.rand(np_repl)-1\n",
|
"sampleX, sampleY = 2 * np.random.rand(np_repl) - 1, 2 * np.random.rand(np_repl) - 1\n",
|
||||||
"\n",
|
"\n",
|
||||||
"intervalle = np.linspace(-2, 2, 100)\n",
|
"intervalle = np.linspace(-2, 2, 100)\n",
|
||||||
"plt.hist(sampleX + sampleY, bins=intervalle, density=True, label='Echantillon')\n",
|
"plt.hist(sampleX + sampleY, bins=intervalle, density=True, label=\"Echantillon\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"densite = stats.uniform(-1, 2).pdf\n",
|
"densite = stats.uniform(-1, 2).pdf\n",
|
||||||
"plt.plot(intervalle, densite(intervalle), label='Fonction densité')\n",
|
"plt.plot(intervalle, densite(intervalle), label=\"Fonction densité\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.plot(intervalle, 1/4 * np.maximum(2 - np.abs(intervalle), 0), label='Fonction')\n",
|
"plt.plot(intervalle, 1 / 4 * np.maximum(2 - np.abs(intervalle), 0), label=\"Fonction\")\n",
|
||||||
"plt.legend()"
|
"plt.legend()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -130,10 +130,22 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"lam = 1\n",
|
"lam = 1\n",
|
||||||
"nb_repl = 10000\n",
|
"nb_repl = 10000\n",
|
||||||
"sampleX, sampleY, sampleZ = np.random.exponential(lam, nb_repl), np.random.exponential(lam, nb_repl), np.random.exponential(lam, nb_repl)\n",
|
"sampleX, sampleY, sampleZ = (\n",
|
||||||
|
" np.random.exponential(lam, nb_repl),\n",
|
||||||
|
" np.random.exponential(lam, nb_repl),\n",
|
||||||
|
" np.random.exponential(lam, nb_repl),\n",
|
||||||
|
")\n",
|
||||||
"intervalle = np.linspace(-5, 5, 100)\n",
|
"intervalle = np.linspace(-5, 5, 100)\n",
|
||||||
"plt.hist(sampleX - sampleY/2, bins=intervalle, density=True, alpha=.7, label='Echantillon de X - Y/2')\n",
|
"plt.hist(\n",
|
||||||
"plt.hist(sampleZ/2, bins=intervalle, density=True, alpha=.7, label='Echantillon de Z')\n",
|
" sampleX - sampleY / 2,\n",
|
||||||
|
" bins=intervalle,\n",
|
||||||
|
" density=True,\n",
|
||||||
|
" alpha=0.7,\n",
|
||||||
|
" label=\"Echantillon de X - Y/2\",\n",
|
||||||
|
")\n",
|
||||||
|
"plt.hist(\n",
|
||||||
|
" sampleZ / 2, bins=intervalle, density=True, alpha=0.7, label=\"Echantillon de Z\"\n",
|
||||||
|
")\n",
|
||||||
"plt.legend()"
|
"plt.legend()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -157,15 +169,17 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"p = 1/2\n",
|
"p = 1 / 2\n",
|
||||||
"nb_repl = 1000\n",
|
"nb_repl = 1000\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(figsize=(18, 5))\n",
|
"plt.figure(figsize=(18, 5))\n",
|
||||||
"for i, k in enumerate([10, 100, 1000]):\n",
|
"for i, k in enumerate([10, 100, 1000]):\n",
|
||||||
" plt.subplot(1, 3, i+1)\n",
|
" plt.subplot(1, 3, i + 1)\n",
|
||||||
" sample = np.random.binomial(k, p, nb_repl)\n",
|
" sample = np.random.binomial(k, p, nb_repl)\n",
|
||||||
" intervalle = np.linspace(np.min(sample), np.max(sample), 100)\n",
|
" intervalle = np.linspace(np.min(sample), np.max(sample), 100)\n",
|
||||||
" plt.hist(sample, bins=intervalle, density=True, label=f'Echantillon de X pour n={k}')\n",
|
" plt.hist(\n",
|
||||||
|
" sample, bins=intervalle, density=True, label=f\"Echantillon de X pour n={k}\"\n",
|
||||||
|
" )\n",
|
||||||
" plt.legend()"
|
" plt.legend()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -179,7 +193,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def sample_uniforme(N):\n",
|
"def sample_uniforme(N):\n",
|
||||||
" return 2*np.random.rand(N) - 1"
|
" return 2 * np.random.rand(N) - 1"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -218,7 +232,7 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"for _ in range(nb_lgn):\n",
|
"for _ in range(nb_lgn):\n",
|
||||||
" liste_Sn.append(np.mean(sample_uniforme(nb_repl)))\n",
|
" liste_Sn.append(np.mean(sample_uniforme(nb_repl)))\n",
|
||||||
" \n",
|
"\n",
|
||||||
"nb_bins = 100\n",
|
"nb_bins = 100\n",
|
||||||
"intervalles = np.linspace(np.min(liste_Sn), np.max(liste_Sn), nb_bins)\n",
|
"intervalles = np.linspace(np.min(liste_Sn), np.max(liste_Sn), nb_bins)\n",
|
||||||
"plt.hist(liste_Sn, density=True, bins=intervalles)\n",
|
"plt.hist(liste_Sn, density=True, bins=intervalles)\n",
|
||||||
@@ -256,12 +270,14 @@
|
|||||||
"liste_Sn = []\n",
|
"liste_Sn = []\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for _ in range(nb_lgn):\n",
|
"for _ in range(nb_lgn):\n",
|
||||||
" liste_Sn.append(np.mean(np.sqrt(3*nb_repl) * np.tan(np.pi/2 * sample_uniforme(nb_repl))))\n",
|
" liste_Sn.append(\n",
|
||||||
|
" np.mean(np.sqrt(3 * nb_repl) * np.tan(np.pi / 2 * sample_uniforme(nb_repl)))\n",
|
||||||
|
" )\n",
|
||||||
"\n",
|
"\n",
|
||||||
"#nb_bins = 100\n",
|
"# nb_bins = 100\n",
|
||||||
"#intervalles = np.linspace(np.min(liste_Sn), np.max(liste_Sn), nb_bins)\n",
|
"# intervalles = np.linspace(np.min(liste_Sn), np.max(liste_Sn), nb_bins)\n",
|
||||||
"#plt.hist(liste_Sn, density=True, bins=intervalles)\n",
|
"# plt.hist(liste_Sn, density=True, bins=intervalles)\n",
|
||||||
"#plt.show()\n",
|
"# plt.show()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure()\n",
|
"plt.figure()\n",
|
||||||
"densite = stats.norm(scale=1).pdf\n",
|
"densite = stats.norm(scale=1).pdf\n",
|
||||||
|
|||||||
@@ -27,7 +27,12 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"def f(L, z):\n",
|
"def f(L, z):\n",
|
||||||
" x, y = L[0], L[1]\n",
|
" x, y = L[0], L[1]\n",
|
||||||
" return np.power(z*x, 2) + np.power(y/z, 2) - np.cos(2 * np.pi * x) - np.cos(2 * np.pi * y)"
|
" return (\n",
|
||||||
|
" np.power(z * x, 2)\n",
|
||||||
|
" + np.power(y / z, 2)\n",
|
||||||
|
" - np.cos(2 * np.pi * x)\n",
|
||||||
|
" - np.cos(2 * np.pi * y)\n",
|
||||||
|
" )"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -123,17 +128,17 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"plt.figure(figsize=(18, 5))\n",
|
"plt.figure(figsize=(18, 5))\n",
|
||||||
"for i, nb_repl in enumerate([100, 1000, 10000]):\n",
|
"for i, nb_repl in enumerate([100, 1000, 10000]):\n",
|
||||||
" plt.subplot(1, 3, i+1)\n",
|
" plt.subplot(1, 3, i + 1)\n",
|
||||||
" sample_X1 = np.random.normal(0, 1, nb_repl)\n",
|
" sample_X1 = np.random.normal(0, 1, nb_repl)\n",
|
||||||
" sample_X2 = np.random.normal(3, np.sqrt(5), nb_repl)\n",
|
" sample_X2 = np.random.normal(3, np.sqrt(5), nb_repl)\n",
|
||||||
" sample_e = np.random.normal(0, np.sqrt(1/4), nb_repl)\n",
|
" sample_e = np.random.normal(0, np.sqrt(1 / 4), nb_repl)\n",
|
||||||
" Y = 5 * sample_X1 - 4 * sample_X2 + 2 + sample_e\n",
|
" Y = 5 * sample_X1 - 4 * sample_X2 + 2 + sample_e\n",
|
||||||
"\n",
|
"\n",
|
||||||
" intervalle = np.linspace(np.min(Y), np.max(Y), 100)\n",
|
" intervalle = np.linspace(np.min(Y), np.max(Y), 100)\n",
|
||||||
" plt.hist(Y, bins=intervalle, density=True, label='Echantillon de Y')\n",
|
" plt.hist(Y, bins=intervalle, density=True, label=\"Echantillon de Y\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" densite = stats.norm(-10, np.sqrt(105.25)).pdf\n",
|
" densite = stats.norm(-10, np.sqrt(105.25)).pdf\n",
|
||||||
" plt.plot(intervalle, densite(intervalle), label='Fonction densité')\n",
|
" plt.plot(intervalle, densite(intervalle), label=\"Fonction densité\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" plt.title(f\"Graphique de la somme de gaussiennes pour N={nb_repl}\")\n",
|
" plt.title(f\"Graphique de la somme de gaussiennes pour N={nb_repl}\")\n",
|
||||||
" plt.legend()"
|
" plt.legend()"
|
||||||
@@ -151,8 +156,9 @@
|
|||||||
"def theta_hat(Y):\n",
|
"def theta_hat(Y):\n",
|
||||||
" return np.mean(Y)\n",
|
" return np.mean(Y)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def sigma_hat(Y):\n",
|
"def sigma_hat(Y):\n",
|
||||||
" return 1/nb_repl * np.sum(np.power(Y - theta_hat(Y), 2))"
|
" return 1 / nb_repl * np.sum(np.power(Y - theta_hat(Y), 2))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -166,7 +172,11 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"def log_likehood_gauss(X, Y):\n",
|
"def log_likehood_gauss(X, Y):\n",
|
||||||
" theta, sigma_2 = X[0], X[1]\n",
|
" theta, sigma_2 = X[0], X[1]\n",
|
||||||
" return 1/2*np.log(2*np.pi) + 1/2*np.log(sigma_2) + 1/(2*nb_repl*sigma_2) * np.sum(np.power(Y - theta, 2))"
|
" return (\n",
|
||||||
|
" 1 / 2 * np.log(2 * np.pi)\n",
|
||||||
|
" + 1 / 2 * np.log(sigma_2)\n",
|
||||||
|
" + 1 / (2 * nb_repl * sigma_2) * np.sum(np.power(Y - theta, 2))\n",
|
||||||
|
" )"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -191,9 +201,9 @@
|
|||||||
"nb_repl = 5000\n",
|
"nb_repl = 5000\n",
|
||||||
"sample_X1 = np.random.normal(0, 1, nb_repl)\n",
|
"sample_X1 = np.random.normal(0, 1, nb_repl)\n",
|
||||||
"sample_X2 = np.random.normal(3, np.sqrt(5), nb_repl)\n",
|
"sample_X2 = np.random.normal(3, np.sqrt(5), nb_repl)\n",
|
||||||
"sample_e = np.random.normal(0, np.sqrt(1/4), nb_repl)\n",
|
"sample_e = np.random.normal(0, np.sqrt(1 / 4), nb_repl)\n",
|
||||||
"Y = 5 * sample_X1 - 4 * sample_X2 + 2 + sample_e\n",
|
"Y = 5 * sample_X1 - 4 * sample_X2 + 2 + sample_e\n",
|
||||||
" \n",
|
"\n",
|
||||||
"mk = {\"method\": \"BFGS\", \"args\": Y}\n",
|
"mk = {\"method\": \"BFGS\", \"args\": Y}\n",
|
||||||
"res = opt.basinhopping(log_likehood_gauss, x0=(-1, 98.75), minimizer_kwargs=mk)\n",
|
"res = opt.basinhopping(log_likehood_gauss, x0=(-1, 98.75), minimizer_kwargs=mk)\n",
|
||||||
"print(res.x)\n",
|
"print(res.x)\n",
|
||||||
@@ -211,12 +221,12 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def simule(a, b, n):\n",
|
"def simule(a, b, n):\n",
|
||||||
" X = np.random.gamma(a, 1/b, n)\n",
|
" X = np.random.gamma(a, 1 / b, n)\n",
|
||||||
" intervalle = np.linspace(0, np.max(X), 100)\n",
|
" intervalle = np.linspace(0, np.max(X), 100)\n",
|
||||||
" plt.hist(X, bins=intervalle, density=True, label='Echantillon de X')\n",
|
" plt.hist(X, bins=intervalle, density=True, label=\"Echantillon de X\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" densite = stats.gamma.pdf(intervalle, a, 0, 1/b)\n",
|
" densite = stats.gamma.pdf(intervalle, a, 0, 1 / b)\n",
|
||||||
" plt.plot(intervalle, densite, label='Fonction densité Gamma(2, 1)')\n",
|
" plt.plot(intervalle, densite, label=\"Fonction densité Gamma(2, 1)\")\n",
|
||||||
" plt.legend()"
|
" plt.legend()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -254,8 +264,13 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"def log_likehood_gamma(X, sample):\n",
|
"def log_likehood_gamma(X, sample):\n",
|
||||||
" a, b = X[0], X[1]\n",
|
" a, b = X[0], X[1]\n",
|
||||||
" n = len(sample) \n",
|
" n = len(sample)\n",
|
||||||
" return -n*a*np.log(b) + n * np.log(sp.gamma(a)) - (a-1) * np.sum(np.log(sample)) + b * np.sum(sample)"
|
" return (\n",
|
||||||
|
" -n * a * np.log(b)\n",
|
||||||
|
" + n * np.log(sp.gamma(a))\n",
|
||||||
|
" - (a - 1) * np.sum(np.log(sample))\n",
|
||||||
|
" + b * np.sum(sample)\n",
|
||||||
|
" )"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -296,7 +311,7 @@
|
|||||||
"nb_repl = 1000\n",
|
"nb_repl = 1000\n",
|
||||||
"a, b = 2, 1\n",
|
"a, b = 2, 1\n",
|
||||||
"\n",
|
"\n",
|
||||||
"sample = np.random.gamma(a, 1/b, nb_repl)\n",
|
"sample = np.random.gamma(a, 1 / b, nb_repl)\n",
|
||||||
"mk = {\"method\": \"BFGS\", \"args\": sample}\n",
|
"mk = {\"method\": \"BFGS\", \"args\": sample}\n",
|
||||||
"res = opt.basinhopping(log_likehood_gamma, x0=(1, 1), minimizer_kwargs=mk)\n",
|
"res = opt.basinhopping(log_likehood_gamma, x0=(1, 1), minimizer_kwargs=mk)\n",
|
||||||
"print(res.x)"
|
"print(res.x)"
|
||||||
|
|||||||
@@ -122,7 +122,7 @@
|
|||||||
" y = np.zeros(N + 1)\n",
|
" y = np.zeros(N + 1)\n",
|
||||||
" y[0] = y0\n",
|
" y[0] = y0\n",
|
||||||
" for n in range(N):\n",
|
" for n in range(N):\n",
|
||||||
" y[n + 1] = np.power(h + np.sqrt(h ** 2 + y[n]), 2)\n",
|
" y[n + 1] = np.power(h + np.sqrt(h**2 + y[n]), 2)\n",
|
||||||
" return t, y"
|
" return t, y"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -158,7 +158,7 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"plt.scatter(t, sol_appr, label=\"Approximation with EI\")\n",
|
"plt.scatter(t, sol_appr, label=\"Approximation with EI\")\n",
|
||||||
"plt.plot(x, f_exact(x, T), label=\"Exact solution\", color=\"red\")\n",
|
"plt.plot(x, f_exact(x, T), label=\"Exact solution\", color=\"red\")\n",
|
||||||
"plt.plot(x, x ** 2, label=\"Square function\", color=\"green\")\n",
|
"plt.plot(x, x**2, label=\"Square function\", color=\"green\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
@@ -297,9 +297,9 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"sol = odeint(F, y0, t, args=(a, r))\n",
|
"sol = odeint(F, y0, t, args=(a, r))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.plot(t, sol[:, 0], label='S(t)')\n",
|
"plt.plot(t, sol[:, 0], label=\"S(t)\")\n",
|
||||||
"plt.plot(t, sol[:, 1], label='I(t)')\n",
|
"plt.plot(t, sol[:, 1], label=\"I(t)\")\n",
|
||||||
"plt.plot(t, sol[:, 2], label='R(t)')\n",
|
"plt.plot(t, sol[:, 2], label=\"R(t)\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
@@ -336,7 +336,9 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"def calculate_errors(sol_exact, sol_appr):\n",
|
"def calculate_errors(sol_exact, sol_appr):\n",
|
||||||
" return np.max(\n",
|
" return np.max(\n",
|
||||||
" np.power(np.abs(sol_appr - sol_exact), 2)[np.isfinite(np.power(np.abs(sol_appr - sol_exact), 2))]\n",
|
" np.power(np.abs(sol_appr - sol_exact), 2)[\n",
|
||||||
|
" np.isfinite(np.power(np.abs(sol_appr - sol_exact), 2))\n",
|
||||||
|
" ]\n",
|
||||||
" )\n",
|
" )\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -356,8 +358,8 @@
|
|||||||
"plt.plot(errors_EE, label=\"Euler Explicit\")\n",
|
"plt.plot(errors_EE, label=\"Euler Explicit\")\n",
|
||||||
"plt.plot(errors_H, label=\"Heun\")\n",
|
"plt.plot(errors_H, label=\"Heun\")\n",
|
||||||
"plt.plot(errors_RK4, label=\"Runge Kutta order 4\")\n",
|
"plt.plot(errors_RK4, label=\"Runge Kutta order 4\")\n",
|
||||||
"plt.yscale('log')\n",
|
"plt.yscale(\"log\")\n",
|
||||||
"plt.xscale('log')\n",
|
"plt.xscale(\"log\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
@@ -431,23 +433,23 @@
|
|||||||
"# Plot the real parts\n",
|
"# Plot the real parts\n",
|
||||||
"plt.figure(figsize=(12, 6))\n",
|
"plt.figure(figsize=(12, 6))\n",
|
||||||
"plt.subplot(1, 2, 1)\n",
|
"plt.subplot(1, 2, 1)\n",
|
||||||
"plt.plot(t, np.real(x_appr_EI), label='Numerical Solution by EI')\n",
|
"plt.plot(t, np.real(x_appr_EI), label=\"Numerical Solution by EI\")\n",
|
||||||
"plt.plot(t, np.real(x_appr_EE), label='Numerical Solution by EE')\n",
|
"plt.plot(t, np.real(x_appr_EE), label=\"Numerical Solution by EE\")\n",
|
||||||
"plt.plot(t, np.real(x_exact), label='Exact Solution', linestyle='--')\n",
|
"plt.plot(t, np.real(x_exact), label=\"Exact Solution\", linestyle=\"--\")\n",
|
||||||
"plt.xlabel('Time')\n",
|
"plt.xlabel(\"Time\")\n",
|
||||||
"plt.ylabel('Real Part')\n",
|
"plt.ylabel(\"Real Part\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.title('Real Part of the Solution')\n",
|
"plt.title(\"Real Part of the Solution\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Plot the imaginary parts\n",
|
"# Plot the imaginary parts\n",
|
||||||
"plt.subplot(1, 2, 2)\n",
|
"plt.subplot(1, 2, 2)\n",
|
||||||
"plt.plot(t, np.imag(x_appr_EI), label='Numerical Solution by EI')\n",
|
"plt.plot(t, np.imag(x_appr_EI), label=\"Numerical Solution by EI\")\n",
|
||||||
"plt.plot(t, np.imag(x_appr_EE), label='Numerical Solution by EE')\n",
|
"plt.plot(t, np.imag(x_appr_EE), label=\"Numerical Solution by EE\")\n",
|
||||||
"plt.plot(t, np.imag(x_exact), label='Exact Solution', linestyle='--')\n",
|
"plt.plot(t, np.imag(x_exact), label=\"Exact Solution\", linestyle=\"--\")\n",
|
||||||
"plt.xlabel('Time')\n",
|
"plt.xlabel(\"Time\")\n",
|
||||||
"plt.ylabel('Imaginary Part')\n",
|
"plt.ylabel(\"Imaginary Part\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.title('Imaginary Part of the Solution')\n",
|
"plt.title(\"Imaginary Part of the Solution\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
{
|
{
|
||||||
"cells": [
|
"cells": [
|
||||||
{
|
{
|
||||||
"metadata": {},
|
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"id": "c897654e0a140cbd",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Automatic Differentiation\n",
|
"# Automatic Differentiation\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -11,42 +12,18 @@
|
|||||||
"Loss function: softmax layer in $\\mathbb{R}^3$\n",
|
"Loss function: softmax layer in $\\mathbb{R}^3$\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Architecture: FC/ReLU 4-5-7-3"
|
"Architecture: FC/ReLU 4-5-7-3"
|
||||||
],
|
]
|
||||||
"id": "c897654e0a140cbd"
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 33,
|
||||||
|
"id": "70a4eb1d928b10d0",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"ExecuteTime": {
|
"ExecuteTime": {
|
||||||
"end_time": "2025-03-24T15:16:27.015669Z",
|
"end_time": "2025-03-24T15:16:27.015669Z",
|
||||||
"start_time": "2025-03-24T15:16:23.856887Z"
|
"start_time": "2025-03-24T15:16:23.856887Z"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cell_type": "code",
|
|
||||||
"source": [
|
|
||||||
"import numpy as np\n",
|
|
||||||
"from sklearn.neural_network import MLPClassifier\n",
|
|
||||||
"from sklearn.datasets import make_classification\n",
|
|
||||||
"from sklearn.model_selection import train_test_split\n",
|
|
||||||
"from sklearn.metrics import accuracy_score\n",
|
|
||||||
"\n",
|
|
||||||
"accuracies = []\n",
|
|
||||||
"\n",
|
|
||||||
"for _ in range(10):\n",
|
|
||||||
" X, y = make_classification(n_samples=1000, n_features=4, n_classes=3, n_clusters_per_class=1)\n",
|
|
||||||
"\n",
|
|
||||||
" X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
|
|
||||||
" model = MLPClassifier(hidden_layer_sizes=(5, 7), activation='relu', max_iter=10000, solver='adam')\n",
|
|
||||||
" model.fit(X_train, y_train)\n",
|
|
||||||
"\n",
|
|
||||||
" y_pred = model.predict(X_test)\n",
|
|
||||||
" accuracies.append(accuracy_score(y_test, y_pred))\n",
|
|
||||||
"\n",
|
|
||||||
"print(f'Mean Accuracy: {np.mean(accuracies) * 100:.0f}%')\n",
|
|
||||||
"print(f'STD Accuracy: {np.std(accuracies) * 100:.0f}%')\n",
|
|
||||||
"print(f\"Max accuracy: {np.max(accuracies) * 100:.0f}%\")\n",
|
|
||||||
"print(f\"Min accuracy: {np.min(accuracies) * 100:.0f}%\")"
|
|
||||||
],
|
|
||||||
"id": "70a4eb1d928b10d0",
|
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
"name": "stdout",
|
"name": "stdout",
|
||||||
@@ -59,20 +36,47 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"execution_count": 33
|
"source": [
|
||||||
|
"import numpy as np\n",
|
||||||
|
"from sklearn.neural_network import MLPClassifier\n",
|
||||||
|
"from sklearn.datasets import make_classification\n",
|
||||||
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
|
"from sklearn.metrics import accuracy_score\n",
|
||||||
|
"\n",
|
||||||
|
"accuracies = []\n",
|
||||||
|
"\n",
|
||||||
|
"for _ in range(10):\n",
|
||||||
|
" X, y = make_classification(\n",
|
||||||
|
" n_samples=1000, n_features=4, n_classes=3, n_clusters_per_class=1\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
|
" X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
|
||||||
|
" model = MLPClassifier(\n",
|
||||||
|
" hidden_layer_sizes=(5, 7), activation=\"relu\", max_iter=10000, solver=\"adam\"\n",
|
||||||
|
" )\n",
|
||||||
|
" model.fit(X_train, y_train)\n",
|
||||||
|
"\n",
|
||||||
|
" y_pred = model.predict(X_test)\n",
|
||||||
|
" accuracies.append(accuracy_score(y_test, y_pred))\n",
|
||||||
|
"\n",
|
||||||
|
"print(f\"Mean Accuracy: {np.mean(accuracies) * 100:.0f}%\")\n",
|
||||||
|
"print(f\"STD Accuracy: {np.std(accuracies) * 100:.0f}%\")\n",
|
||||||
|
"print(f\"Max accuracy: {np.max(accuracies) * 100:.0f}%\")\n",
|
||||||
|
"print(f\"Min accuracy: {np.min(accuracies) * 100:.0f}%\")"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"id": "96b6d46883ed5570",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"ExecuteTime": {
|
"ExecuteTime": {
|
||||||
"end_time": "2025-03-24T14:37:53.507776Z",
|
"end_time": "2025-03-24T14:37:53.507776Z",
|
||||||
"start_time": "2025-03-24T14:37:53.505376Z"
|
"start_time": "2025-03-24T14:37:53.505376Z"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cell_type": "code",
|
|
||||||
"source": "",
|
|
||||||
"id": "96b6d46883ed5570",
|
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"execution_count": null
|
"source": []
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
|
|||||||
@@ -51,17 +51,18 @@
|
|||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" return S0 * np.exp((mu - 0.5 * sigma**2) * t + sigma * W)\n",
|
" return S0 * np.exp((mu - 0.5 * sigma**2) * t + sigma * W)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def euler_maruyama(mu, sigma, T, N, X0=0.0):\n",
|
"def euler_maruyama(mu, sigma, T, N, X0=0.0):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Simulation d'une EDS de Black-Scholes par la méthode d'Euler-Maruyama\n",
|
" Simulation d'une EDS de Black-Scholes par la méthode d'Euler-Maruyama\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Paramètres :\n",
|
" Paramètres :\n",
|
||||||
" mu (float) : drift\n",
|
" mu (float) : drift\n",
|
||||||
" sigma (float) : volatilité\n",
|
" sigma (float) : volatilité\n",
|
||||||
" T (int) : temps final\n",
|
" T (int) : temps final\n",
|
||||||
" N (int) : nombre de pas de temps\n",
|
" N (int) : nombre de pas de temps\n",
|
||||||
" X0 (float) : valeur initiale\n",
|
" X0 (float) : valeur initiale\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Retourne :\n",
|
" Retourne :\n",
|
||||||
" t (array-like) : tableau des temps\n",
|
" t (array-like) : tableau des temps\n",
|
||||||
" X (array-like) : tableau des valeurs de l'EDS\n",
|
" X (array-like) : tableau des valeurs de l'EDS\n",
|
||||||
@@ -70,17 +71,18 @@
|
|||||||
"\n",
|
"\n",
|
||||||
" t = np.linspace(0, T, N + 1)\n",
|
" t = np.linspace(0, T, N + 1)\n",
|
||||||
" X = np.zeros(N + 1)\n",
|
" X = np.zeros(N + 1)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" X[0] = X0\n",
|
" X[0] = X0\n",
|
||||||
"\n",
|
"\n",
|
||||||
" dW = np.random.normal(0, np.sqrt(dt), N)\n",
|
" dW = np.random.normal(0, np.sqrt(dt), N)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" for i in range(N):\n",
|
" for i in range(N):\n",
|
||||||
" St = S(t[i], X[i], mu, sigma, dW[i])\n",
|
" St = S(t[i], X[i], mu, sigma, dW[i])\n",
|
||||||
" X[i + 1] = X[i] + mu * St * dt + sigma * St * dW[i]\n",
|
" X[i + 1] = X[i] + mu * St * dt + sigma * St * dW[i]\n",
|
||||||
" \n",
|
"\n",
|
||||||
" return t, X\n",
|
" return t, X\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def plot_brownien(t, X, B=None):\n",
|
"def plot_brownien(t, X, B=None):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Plot la simulation d'Euler-Maruyama\n",
|
" Plot la simulation d'Euler-Maruyama\n",
|
||||||
@@ -90,15 +92,15 @@
|
|||||||
" X (array-like) : tableau des valeurs de l'EDS\n",
|
" X (array-like) : tableau des valeurs de l'EDS\n",
|
||||||
" B (float) : barrière (optionnelle)\n",
|
" B (float) : barrière (optionnelle)\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" plt.plot(t, X, alpha=0.5, label='Euler-Maruyama')\n",
|
" plt.plot(t, X, alpha=0.5, label=\"Euler-Maruyama\")\n",
|
||||||
" plt.title('Simulation d\\'Euler-Maruyama pour une EDS')\n",
|
" plt.title(\"Simulation d'Euler-Maruyama pour une EDS\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
" if B is not None:\n",
|
" if B is not None:\n",
|
||||||
" plt.axhline(B, label='Barrière', color='red', linestyle='--')\n",
|
" plt.axhline(B, label=\"Barrière\", color=\"red\", linestyle=\"--\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
" plt.legend()\n",
|
" plt.legend()\n",
|
||||||
" plt.xlabel('Temps')\n",
|
" plt.xlabel(\"Temps\")\n",
|
||||||
" plt.ylabel('X(t)')\n",
|
" plt.ylabel(\"X(t)\")\n",
|
||||||
" plt.grid()"
|
" plt.grid()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -165,10 +167,11 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"np.random.seed(333)\n",
|
"np.random.seed(333)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def plot_convergence(S0, mu, sigma, T):\n",
|
"def plot_convergence(S0, mu, sigma, T):\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" Plot la convergence du schéma d'Euler-Maruyama\n",
|
" Plot la convergence du schéma d'Euler-Maruyama\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Paramètres :\n",
|
" Paramètres :\n",
|
||||||
" S0 (int) : valeur initiale\n",
|
" S0 (int) : valeur initiale\n",
|
||||||
" mu (float) : drift\n",
|
" mu (float) : drift\n",
|
||||||
@@ -176,26 +179,27 @@
|
|||||||
" T (int) : temps final\n",
|
" T (int) : temps final\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" errors = []\n",
|
" errors = []\n",
|
||||||
" \n",
|
"\n",
|
||||||
" for N in N_list:\n",
|
" for N in N_list:\n",
|
||||||
" dt = T / N\n",
|
" dt = T / N\n",
|
||||||
" dW = np.random.normal(0, np.sqrt(dt), N)\n",
|
" dW = np.random.normal(0, np.sqrt(dt), N)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" exact = S(T, S0, mu, sigma, dW)\n",
|
" exact = S(T, S0, mu, sigma, dW)\n",
|
||||||
" _, X = euler_maruyama(mu=mu, sigma=sigma, T=T, N=N, X0=S0)\n",
|
" _, X = euler_maruyama(mu=mu, sigma=sigma, T=T, N=N, X0=S0)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" errors.append(np.max(np.abs(X[1:] - exact)))\n",
|
" errors.append(np.max(np.abs(X[1:] - exact)))\n",
|
||||||
" \n",
|
"\n",
|
||||||
" plt.plot(np.log(h_list), np.log(errors), 'o-', label='Erreur numérique')\n",
|
" plt.plot(np.log(h_list), np.log(errors), \"o-\", label=\"Erreur numérique\")\n",
|
||||||
" plt.plot(np.log(h_list), 0.5 * np.log(h_list), '--', label='Ordre 1/2')\n",
|
" plt.plot(np.log(h_list), 0.5 * np.log(h_list), \"--\", label=\"Ordre 1/2\")\n",
|
||||||
" plt.plot(np.log(h_list), np.log(h_list), '--', label='Ordre 1')\n",
|
" plt.plot(np.log(h_list), np.log(h_list), \"--\", label=\"Ordre 1\")\n",
|
||||||
" plt.plot(np.log(h_list), 2*np.log(h_list), '--', label='Ordre 2')\n",
|
" plt.plot(np.log(h_list), 2 * np.log(h_list), \"--\", label=\"Ordre 2\")\n",
|
||||||
" plt.xlabel('log(h)')\n",
|
" plt.xlabel(\"log(h)\")\n",
|
||||||
" plt.ylabel('log(Erreur)')\n",
|
" plt.ylabel(\"log(Erreur)\")\n",
|
||||||
" plt.title('Convergence du schéma d\\'Euler-Maruyama')\n",
|
" plt.title(\"Convergence du schéma d'Euler-Maruyama\")\n",
|
||||||
" plt.legend()\n",
|
" plt.legend()\n",
|
||||||
" plt.grid(True)\n",
|
" plt.grid(True)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"plt.figure(figsize=(10, 5))\n",
|
"plt.figure(figsize=(10, 5))\n",
|
||||||
"plot_convergence(S0, r, sigma, T)\n",
|
"plot_convergence(S0, r, sigma, T)\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
@@ -269,6 +273,7 @@
|
|||||||
"plot_brownien(t, X, B=B)\n",
|
"plot_brownien(t, X, B=B)\n",
|
||||||
"plt.show()\n",
|
"plt.show()\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def is_barrier_breached(X, B):\n",
|
"def is_barrier_breached(X, B):\n",
|
||||||
" \"\"\"Renvoie True si la barrière est franchie, False sinon\n",
|
" \"\"\"Renvoie True si la barrière est franchie, False sinon\n",
|
||||||
" La barrière est franchie si X >= B\n",
|
" La barrière est franchie si X >= B\n",
|
||||||
@@ -282,7 +287,12 @@
|
|||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" return any(X >= B)\n",
|
" return any(X >= B)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"La barrière a été franchie\" if is_barrier_breached(X, B) else \"La barrière n'a pas été franchie\")"
|
"\n",
|
||||||
|
"print(\n",
|
||||||
|
" \"La barrière a été franchie\"\n",
|
||||||
|
" if is_barrier_breached(X, B)\n",
|
||||||
|
" else \"La barrière n'a pas été franchie\"\n",
|
||||||
|
")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -299,18 +309,19 @@
|
|||||||
" trajectories (list of tuples): Liste des trajectoires avec le temps et les valeurs\n",
|
" trajectories (list of tuples): Liste des trajectoires avec le temps et les valeurs\n",
|
||||||
" B (float): Valeur de la barrière\n",
|
" B (float): Valeur de la barrière\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" for (t, X) in trajectories:\n",
|
" for t, X in trajectories:\n",
|
||||||
" col = 'pink' if is_barrier_breached(X, B) else 'lime'\n",
|
" col = \"pink\" if is_barrier_breached(X, B) else \"lime\"\n",
|
||||||
" plt.plot(t, X, alpha=0.5, color=col)\n",
|
" plt.plot(t, X, alpha=0.5, color=col)\n",
|
||||||
" plt.title('Simulation d\\'Euler-Maruyama pour une EDS')\n",
|
" plt.title(\"Simulation d'Euler-Maruyama pour une EDS\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
" plt.axhline(B, label='Barrière', color='red', linestyle='--')\n",
|
" plt.axhline(B, label=\"Barrière\", color=\"red\", linestyle=\"--\")\n",
|
||||||
" \n",
|
"\n",
|
||||||
" plt.legend()\n",
|
" plt.legend()\n",
|
||||||
" plt.xlabel('Temps')\n",
|
" plt.xlabel(\"Temps\")\n",
|
||||||
" plt.ylabel('X(t)')\n",
|
" plt.ylabel(\"X(t)\")\n",
|
||||||
" plt.grid()\n",
|
" plt.grid()\n",
|
||||||
" \n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def payoff(X, B, K):\n",
|
"def payoff(X, B, K):\n",
|
||||||
" \"\"\"Calcule le payoff d'une option en fonction des trajectoires.\n",
|
" \"\"\"Calcule le payoff d'une option en fonction des trajectoires.\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -324,9 +335,10 @@
|
|||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" if not is_barrier_breached(X, B):\n",
|
" if not is_barrier_breached(X, B):\n",
|
||||||
" return max(X[-1] - K, 0)\n",
|
" return max(X[-1] - K, 0)\n",
|
||||||
" else: \n",
|
" else:\n",
|
||||||
" return 0\n",
|
" return 0\n",
|
||||||
" \n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def call_BS(x):\n",
|
"def call_BS(x):\n",
|
||||||
" \"\"\"Calcul du prix d'une option d'achat européenne selon le modèle de Black-Scholes en fonction de x.\n",
|
" \"\"\"Calcul du prix d'une option d'achat européenne selon le modèle de Black-Scholes en fonction de x.\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -336,27 +348,34 @@
|
|||||||
" Retourne:\n",
|
" Retourne:\n",
|
||||||
" float: Le prix de l'option d'achat européenne.\n",
|
" float: Le prix de l'option d'achat européenne.\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" d1 = (np.log(x/K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))\n",
|
" d1 = (np.log(x / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))\n",
|
||||||
" d2 = d1 - sigma * np.sqrt(T)\n",
|
" d2 = d1 - sigma * np.sqrt(T)\n",
|
||||||
" return x * stats.norm.cdf(d1) - K * np.exp(-r * T) * stats.norm.cdf(d2)\n",
|
" return x * stats.norm.cdf(d1) - K * np.exp(-r * T) * stats.norm.cdf(d2)\n",
|
||||||
" \n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def compute_payoff_BS():\n",
|
"def compute_payoff_BS():\n",
|
||||||
" \"\"\"Calcul du prix d'une option d'achat Up-and-Out selon le modèle de Black-Scholes en fonction de la barrière.\n",
|
" \"\"\"Calcul du prix d'une option d'achat Up-and-Out selon le modèle de Black-Scholes en fonction de la barrière.\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Retourne:\n",
|
" Retourne:\n",
|
||||||
" float: Le prix de l'option d'achat Up-and-Out.\n",
|
" float: Le prix de l'option d'achat Up-and-Out.\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
" lam = (r + 0.5 * sigma**2) / sigma**2\n",
|
" lam = (r + 0.5 * sigma**2) / sigma**2\n",
|
||||||
" return call_BS(S0) - call_BS(S0) * (S0/B)**(2 * lam) + (S0/B)**(lam - 1) * (call_BS(B**2/S0) - (S0/B)**2 * call_BS(B**2/S0))\n",
|
" return (\n",
|
||||||
" \n",
|
" call_BS(S0)\n",
|
||||||
|
" - call_BS(S0) * (S0 / B) ** (2 * lam)\n",
|
||||||
|
" + (S0 / B) ** (lam - 1)\n",
|
||||||
|
" * (call_BS(B**2 / S0) - (S0 / B) ** 2 * call_BS(B**2 / S0))\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
"def compute_payoff(trajectories, B, K):\n",
|
"def compute_payoff(trajectories, B, K):\n",
|
||||||
" \"\"\"Calcule le payoff d'une option en fonction des trajectoires.\n",
|
" \"\"\"Calcule le payoff d'une option en fonction des trajectoires.\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Paramètres:\n",
|
" Paramètres:\n",
|
||||||
" trajectories (list of tuples): Liste des trajectoires avec le temps et les valeurs.\n",
|
" trajectories (list of tuples): Liste des trajectoires avec le temps et les valeurs.\n",
|
||||||
" B (float): Valeur de la barrière.\n",
|
" B (float): Valeur de la barrière.\n",
|
||||||
" K (float): Prix d'exercice de l'option.\n",
|
" K (float): Prix d'exercice de l'option.\n",
|
||||||
" \n",
|
"\n",
|
||||||
" Retourne:\n",
|
" Retourne:\n",
|
||||||
" float: Valeur du payoff de l'option.\n",
|
" float: Valeur du payoff de l'option.\n",
|
||||||
" \"\"\"\n",
|
" \"\"\"\n",
|
||||||
@@ -390,7 +409,13 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"N_trajectories = 1000\n",
|
"N_trajectories = 1000\n",
|
||||||
"trajectories = [(t, X) for (t, X) in [euler_maruyama(mu=r, sigma=sigma, T=T, N=1000, X0=S0) for _ in range(N_trajectories)]]\n",
|
"trajectories = [\n",
|
||||||
|
" (t, X)\n",
|
||||||
|
" for (t, X) in [\n",
|
||||||
|
" euler_maruyama(mu=r, sigma=sigma, T=T, N=1000, X0=S0)\n",
|
||||||
|
" for _ in range(N_trajectories)\n",
|
||||||
|
" ]\n",
|
||||||
|
"]\n",
|
||||||
"plt.figure(figsize=(10, 6))\n",
|
"plt.figure(figsize=(10, 6))\n",
|
||||||
"plot_browniens(trajectories, B=B)\n",
|
"plot_browniens(trajectories, B=B)\n",
|
||||||
"plt.show()\n",
|
"plt.show()\n",
|
||||||
@@ -431,28 +456,35 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"np.random.seed(333)\n",
|
"np.random.seed(333)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def plot_payoff_errors():\n",
|
"def plot_payoff_errors():\n",
|
||||||
" \"\"\"Trace l'erreur de convergence du payoff actualisé en fonction de N.\"\"\"\n",
|
" \"\"\"Trace l'erreur de convergence du payoff actualisé en fonction de N.\"\"\"\n",
|
||||||
" errors = []\n",
|
" errors = []\n",
|
||||||
" \n",
|
"\n",
|
||||||
" for N in N_list:\n",
|
" for N in N_list:\n",
|
||||||
" trajectories = [(t, X) for (t, X) in [euler_maruyama(mu=r, sigma=sigma, T=T, N=N, X0=S0) for _ in range(N_trajectories)]]\n",
|
" trajectories = [\n",
|
||||||
|
" (t, X)\n",
|
||||||
|
" for (t, X) in [\n",
|
||||||
|
" euler_maruyama(mu=r, sigma=sigma, T=T, N=N, X0=S0)\n",
|
||||||
|
" for _ in range(N_trajectories)\n",
|
||||||
|
" ]\n",
|
||||||
|
" ]\n",
|
||||||
" payoff_BS = compute_payoff_BS()\n",
|
" payoff_BS = compute_payoff_BS()\n",
|
||||||
" payoffs = compute_payoff(trajectories, B, K)\n",
|
" payoffs = compute_payoff(trajectories, B, K)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" errors.append(np.max(np.abs(payoffs - payoff_BS)))\n",
|
" errors.append(np.max(np.abs(payoffs - payoff_BS)))\n",
|
||||||
" \n",
|
"\n",
|
||||||
" \n",
|
" plt.plot(np.log(N_list), np.log(errors), \"o-\", label=\"Erreur numérique\")\n",
|
||||||
" plt.plot(np.log(N_list), np.log(errors), 'o-', label='Erreur numérique')\n",
|
" plt.plot(np.log(N_list), 0.5 * np.log(N_list), \"--\", label=\"Ordre 1/2\")\n",
|
||||||
" plt.plot(np.log(N_list), 0.5 * np.log(N_list), '--', label='Ordre 1/2')\n",
|
" plt.plot(np.log(N_list), np.log(N_list), \"--\", label=\"Ordre 1\")\n",
|
||||||
" plt.plot(np.log(N_list), np.log(N_list), '--', label='Ordre 1')\n",
|
" plt.plot(np.log(N_list), 2 * np.log(N_list), \"--\", label=\"Ordre 2\")\n",
|
||||||
" plt.plot(np.log(N_list), 2*np.log(N_list), '--', label='Ordre 2')\n",
|
" plt.xlabel(\"log(h)\")\n",
|
||||||
" plt.xlabel('log(h)')\n",
|
" plt.ylabel(\"log(Erreur)\")\n",
|
||||||
" plt.ylabel('log(Erreur)')\n",
|
" plt.title(\"Convergence de l'erreur du payoff actualisé\")\n",
|
||||||
" plt.title('Convergence de l\\'erreur du payoff actualisé')\n",
|
|
||||||
" plt.legend()\n",
|
" plt.legend()\n",
|
||||||
" plt.grid(True)\n",
|
" plt.grid(True)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"plt.figure(figsize=(10, 5))\n",
|
"plt.figure(figsize=(10, 5))\n",
|
||||||
"plot_payoff_errors()\n",
|
"plot_payoff_errors()\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
|
|||||||
@@ -28,8 +28,9 @@
|
|||||||
"k = np.arange(1, 12 + 1)\n",
|
"k = np.arange(1, 12 + 1)\n",
|
||||||
"m = np.power(2, k)\n",
|
"m = np.power(2, k)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def f(x):\n",
|
"def f(x):\n",
|
||||||
"\treturn 1 / np.sqrt(x)"
|
" return 1 / np.sqrt(x)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -39,19 +40,23 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"a, b = 1, 2\n",
|
"a, b = 1, 2\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
"def compute_I(f, a, b, m):\n",
|
"def compute_I(f, a, b, m):\n",
|
||||||
" h_list = (b - a) / m\n",
|
" h_list = (b - a) / m\n",
|
||||||
" I = []\n",
|
" I = []\n",
|
||||||
" errors = []\n",
|
" errors = []\n",
|
||||||
" sol_exact = quad(f, a, b)[0]\n",
|
" sol_exact = quad(f, a, b)[0]\n",
|
||||||
" \n",
|
"\n",
|
||||||
" for h in h_list:\n",
|
" for h in h_list:\n",
|
||||||
" t = np.arange(a, b, h)\n",
|
" t = np.arange(a, b, h)\n",
|
||||||
" y = np.array([3/4 * h * f(t[i] + h/3) + h/4 * f(t[i] + h) for i in range(len(t))])\n",
|
" y = np.array(\n",
|
||||||
|
" [3 / 4 * h * f(t[i] + h / 3) + h / 4 * f(t[i] + h) for i in range(len(t))]\n",
|
||||||
|
" )\n",
|
||||||
" I_approx = np.sum(y)\n",
|
" I_approx = np.sum(y)\n",
|
||||||
" I.append(I_approx)\n",
|
" I.append(I_approx)\n",
|
||||||
" errors.append(np.abs(I_approx - sol_exact))\n",
|
" errors.append(np.abs(I_approx - sol_exact))\n",
|
||||||
" \n",
|
"\n",
|
||||||
" return I, h_list, errors"
|
" return I, h_list, errors"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -84,12 +89,12 @@
|
|||||||
"print(f\"I1 = {I1}\")\n",
|
"print(f\"I1 = {I1}\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(figsize=(10, 5))\n",
|
"plt.figure(figsize=(10, 5))\n",
|
||||||
"plt.plot(np.log(h_list), np.log(errors1), 'o-', label='Erreur numérique')\n",
|
"plt.plot(np.log(h_list), np.log(errors1), \"o-\", label=\"Erreur numérique\")\n",
|
||||||
"plt.plot(np.log(h_list), 2*np.log(h_list), '--', label='Ordre 2')\n",
|
"plt.plot(np.log(h_list), 2 * np.log(h_list), \"--\", label=\"Ordre 2\")\n",
|
||||||
"plt.plot(np.log(h_list), 4*np.log(h_list), '--', label='Ordre 4')\n",
|
"plt.plot(np.log(h_list), 4 * np.log(h_list), \"--\", label=\"Ordre 4\")\n",
|
||||||
"plt.xlabel('log(h)')\n",
|
"plt.xlabel(\"log(h)\")\n",
|
||||||
"plt.ylabel('log(Erreur)')\n",
|
"plt.ylabel(\"log(Erreur)\")\n",
|
||||||
"plt.title('Convergence de la méthode d\\'intégration')\n",
|
"plt.title(\"Convergence de la méthode d'intégration\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.grid(True)\n",
|
"plt.grid(True)\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
@@ -116,12 +121,12 @@
|
|||||||
"I2, h_list, errors2 = compute_I(f, a, b, m)\n",
|
"I2, h_list, errors2 = compute_I(f, a, b, m)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(figsize=(10, 5))\n",
|
"plt.figure(figsize=(10, 5))\n",
|
||||||
"plt.plot(np.log(h_list), np.log(errors2), label='Approximation de l\\'intégrale')\n",
|
"plt.plot(np.log(h_list), np.log(errors2), label=\"Approximation de l'intégrale\")\n",
|
||||||
"plt.plot(np.log(h_list), np.log(h_list), '--', label='h')\n",
|
"plt.plot(np.log(h_list), np.log(h_list), \"--\", label=\"h\")\n",
|
||||||
"plt.plot(np.log(h_list), 2*np.log(h_list), '--', label='h^2')\n",
|
"plt.plot(np.log(h_list), 2 * np.log(h_list), \"--\", label=\"h^2\")\n",
|
||||||
"plt.xlabel('h')\n",
|
"plt.xlabel(\"h\")\n",
|
||||||
"plt.ylabel('Approximation de l\\'intégrale')\n",
|
"plt.ylabel(\"Approximation de l'intégrale\")\n",
|
||||||
"plt.title('Approximation de l\\'intégrale par la méthode de Simpson')\n",
|
"plt.title(\"Approximation de l'intégrale par la méthode de Simpson\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
@@ -146,19 +151,19 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def RKI(f, y0, vt, tol = 1e-6, itmax = 20):\n",
|
"def RKI(f, y0, vt, tol=1e-6, itmax=20):\n",
|
||||||
"\tN, T = len(vt), vt[-1]\n",
|
" N, T = len(vt), vt[-1]\n",
|
||||||
"\tyn = np.zeros((len(y0), N))\n",
|
" yn = np.zeros((len(y0), N))\n",
|
||||||
"\tyn[:, 0] = y0\n",
|
" yn[:, 0] = y0\n",
|
||||||
"\th = T / N\n",
|
" h = T / N\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\tfor n in range(N-1):\n",
|
" for n in range(N - 1):\n",
|
||||||
"\t\tp1 = f(vt[n], yn[:, n])\n",
|
" p1 = f(vt[n], yn[:, n])\n",
|
||||||
"\t\tF1 = lambda p2: f(vt[n] + h/3, yn[:, n] + h/6 * (p1 + p2)) - p2\n",
|
" F1 = lambda p2: f(vt[n] + h / 3, yn[:, n] + h / 6 * (p1 + p2)) - p2\n",
|
||||||
"\t\tp2 = newton(F1, yn[:, n], fprime=None, tol=tol, maxiter=itmax)\n",
|
" p2 = newton(F1, yn[:, n], fprime=None, tol=tol, maxiter=itmax)\n",
|
||||||
"\t\tF2 = lambda yn1: yn[:, n] + h/4 * (3 * p2 + f(vt[n+1], yn1)) - yn1\n",
|
" F2 = lambda yn1: yn[:, n] + h / 4 * (3 * p2 + f(vt[n + 1], yn1)) - yn1\n",
|
||||||
"\t\tyn[:, n + 1] = newton(F2, yn[:, n], fprime=None, tol=tol, maxiter=itmax)\n",
|
" yn[:, n + 1] = newton(F2, yn[:, n], fprime=None, tol=tol, maxiter=itmax)\n",
|
||||||
"\treturn yn"
|
" return yn"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -194,14 +199,18 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"a, b = [0, 2]\n",
|
"a, b = [0, 2]\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def f(t, y):\n",
|
"def f(t, y):\n",
|
||||||
" return t * np.power(y, 3) - t * y\n",
|
" return t * np.power(y, 3) - t * y\n",
|
||||||
" \n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"y0 = [0.5]\n",
|
"y0 = [0.5]\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def sol_exact(t):\n",
|
"def sol_exact(t):\n",
|
||||||
" return 1 / np.sqrt(1 + 3 * np.exp(np.power(t, 2)))\n",
|
" return 1 / np.sqrt(1 + 3 * np.exp(np.power(t, 2)))\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"x_fine = np.linspace(a, b, 1000)\n",
|
"x_fine = np.linspace(a, b, 1000)\n",
|
||||||
"y_fine = sol_exact(x_fine)\n",
|
"y_fine = sol_exact(x_fine)\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -212,13 +221,13 @@
|
|||||||
"y_exact_interp = np.interp(vt, x_fine, y_fine)\n",
|
"y_exact_interp = np.interp(vt, x_fine, y_fine)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(figsize=(10, 5))\n",
|
"plt.figure(figsize=(10, 5))\n",
|
||||||
"plt.plot(x_fine, y_fine, label='Solution exacte')\n",
|
"plt.plot(x_fine, y_fine, label=\"Solution exacte\")\n",
|
||||||
"plt.scatter(vt, y, label='Solution numérique', color='red')\n",
|
"plt.scatter(vt, y, label=\"Solution numérique\", color=\"red\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.show()\n",
|
"plt.show()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"error = np.max(np.abs(y - y_exact_interp))\n",
|
"error = np.max(np.abs(y - y_exact_interp))\n",
|
||||||
"print(f\"Error with h={h}: {error}\")\n"
|
"print(f\"Error with h={h}: {error}\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -246,7 +255,7 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"k = np.arange(1, 10 + 1)\n",
|
"k = np.arange(1, 10 + 1)\n",
|
||||||
"h_list = 1/np.power(2, k)\n",
|
"h_list = 1 / np.power(2, k)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"errors = []\n",
|
"errors = []\n",
|
||||||
"for h in h_list:\n",
|
"for h in h_list:\n",
|
||||||
@@ -258,14 +267,14 @@
|
|||||||
"log_h = np.log(h_list)\n",
|
"log_h = np.log(h_list)\n",
|
||||||
"log_errors = np.log(errors)\n",
|
"log_errors = np.log(errors)\n",
|
||||||
"order = np.polyfit(log_h, log_errors, 1)[0]\n",
|
"order = np.polyfit(log_h, log_errors, 1)[0]\n",
|
||||||
" \n",
|
"\n",
|
||||||
"plt.figure(figsize=(10, 5))\n",
|
"plt.figure(figsize=(10, 5))\n",
|
||||||
"plt.plot(log_h, log_errors, 'o-', label=f'Erreur (ordre {order:.2f})')\n",
|
"plt.plot(log_h, log_errors, \"o-\", label=f\"Erreur (ordre {order:.2f})\")\n",
|
||||||
"plt.plot(log_h, log_h, '--', label='h')\n",
|
"plt.plot(log_h, log_h, \"--\", label=\"h\")\n",
|
||||||
"plt.plot(log_h, 2*log_h, '--', label='h^2')\n",
|
"plt.plot(log_h, 2 * log_h, \"--\", label=\"h^2\")\n",
|
||||||
"plt.plot(log_h, 4*log_h, '--', label='h^4')\n",
|
"plt.plot(log_h, 4 * log_h, \"--\", label=\"h^4\")\n",
|
||||||
"plt.xlabel('log(h)')\n",
|
"plt.xlabel(\"log(h)\")\n",
|
||||||
"plt.ylabel('log(error)')\n",
|
"plt.ylabel(\"log(error)\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.grid(True)\n",
|
"plt.grid(True)\n",
|
||||||
"plt.show()\n",
|
"plt.show()\n",
|
||||||
@@ -306,11 +315,14 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"def F(t, Y):\n",
|
"def F(t, Y):\n",
|
||||||
" x, y, z = Y\n",
|
" x, y, z = Y\n",
|
||||||
" return np.array([\n",
|
" return np.array(\n",
|
||||||
" 1 + np.power(x, 2) * y - (z + 1) * x,\n",
|
" [\n",
|
||||||
" x * z - np.power(x, 2) * y,\n",
|
" 1 + np.power(x, 2) * y - (z + 1) * x,\n",
|
||||||
" - x * z + 1.45\n",
|
" x * z - np.power(x, 2) * y,\n",
|
||||||
" ])\n",
|
" -x * z + 1.45,\n",
|
||||||
|
" ]\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"h = 0.025\n",
|
"h = 0.025\n",
|
||||||
"y0 = np.array([1, 1, 1])\n",
|
"y0 = np.array([1, 1, 1])\n",
|
||||||
@@ -320,20 +332,20 @@
|
|||||||
"y = RKI(F, y0, t)\n",
|
"y = RKI(F, y0, t)\n",
|
||||||
"fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))\n",
|
"fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ax1.scatter(y[0], y[1], label='Solution numérique', color='red')\n",
|
"ax1.scatter(y[0], y[1], label=\"Solution numérique\", color=\"red\")\n",
|
||||||
"ax1.plot(sol_exact[:, 0], sol_exact[:, 1], label='Solution exacte', color='blue')\n",
|
"ax1.plot(sol_exact[:, 0], sol_exact[:, 1], label=\"Solution exacte\", color=\"blue\")\n",
|
||||||
"ax1.legend()\n",
|
"ax1.legend()\n",
|
||||||
"ax1.set_title('x vs y')\n",
|
"ax1.set_title(\"x vs y\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ax2.scatter(y[1], y[2], label='Solution numérique', color='red')\n",
|
"ax2.scatter(y[1], y[2], label=\"Solution numérique\", color=\"red\")\n",
|
||||||
"ax2.plot(sol_exact[:, 1], sol_exact[:, 2], label='Solution exacte', color='blue')\n",
|
"ax2.plot(sol_exact[:, 1], sol_exact[:, 2], label=\"Solution exacte\", color=\"blue\")\n",
|
||||||
"ax2.legend()\n",
|
"ax2.legend()\n",
|
||||||
"ax2.set_title('y vs z')\n",
|
"ax2.set_title(\"y vs z\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ax3.scatter(y[0], y[2], label='Solution numérique', color='red')\n",
|
"ax3.scatter(y[0], y[2], label=\"Solution numérique\", color=\"red\")\n",
|
||||||
"ax3.plot(sol_exact[:, 0], sol_exact[:, 2], label='Solution exacte', color='blue')\n",
|
"ax3.plot(sol_exact[:, 0], sol_exact[:, 2], label=\"Solution exacte\", color=\"blue\")\n",
|
||||||
"ax3.legend()\n",
|
"ax3.legend()\n",
|
||||||
"ax3.set_title('x vs z')\n",
|
"ax3.set_title(\"x vs z\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.tight_layout()\n",
|
"plt.tight_layout()\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
@@ -357,14 +369,15 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"def R(z):\n",
|
"def R(z):\n",
|
||||||
" return (1 + 3/4 * z * (1 + z/6)/(1 - z/6)) / (1 - z/4)\n",
|
" return (1 + 3 / 4 * z * (1 + z / 6) / (1 - z / 6)) / (1 - z / 4)\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"x = np.linspace(-15, 5, 100)\n",
|
"x = np.linspace(-15, 5, 100)\n",
|
||||||
"y = np.linspace(-7.5, 7.5, 100)\n",
|
"y = np.linspace(-7.5, 7.5, 100)\n",
|
||||||
"X, Y = np.meshgrid(x, y)\n",
|
"X, Y = np.meshgrid(x, y)\n",
|
||||||
"Z = R(X + 1j*Y)\n",
|
"Z = R(X + 1j * Y)\n",
|
||||||
"plt.figure(figsize=(10, 7))\n",
|
"plt.figure(figsize=(10, 7))\n",
|
||||||
"plt.contour(X, Y, np.abs(Z), levels=[1], cmap='rainbow')\n",
|
"plt.contour(X, Y, np.abs(Z), levels=[1], cmap=\"rainbow\")\n",
|
||||||
"plt.grid()\n",
|
"plt.grid()\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -308,7 +308,6 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"import numpy as np\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"u = lambda x: np.sqrt((6 - x) ** 2 + 4)\n",
|
"u = lambda x: np.sqrt((6 - x) ** 2 + 4)\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -364,7 +363,9 @@
|
|||||||
"# Run Newton's method\n",
|
"# Run Newton's method\n",
|
||||||
"optimal_point_newton, iterations_newton = newton_method(initial_guess_newton)\n",
|
"optimal_point_newton, iterations_newton = newton_method(initial_guess_newton)\n",
|
||||||
"print(f\"Optimal point (Newton): {optimal_point_newton}\")\n",
|
"print(f\"Optimal point (Newton): {optimal_point_newton}\")\n",
|
||||||
"print(f\"Objective function value at optimal point (Newton): {objective_function(optimal_point_newton)}\")\n",
|
"print(\n",
|
||||||
|
" f\"Objective function value at optimal point (Newton): {objective_function(optimal_point_newton)}\"\n",
|
||||||
|
")\n",
|
||||||
"print(f\"Number of iterations (Newton): {iterations_newton}\")\n",
|
"print(f\"Number of iterations (Newton): {iterations_newton}\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Initial interval for dichotomy method\n",
|
"# Initial interval for dichotomy method\n",
|
||||||
@@ -373,7 +374,9 @@
|
|||||||
"# Run dichotomy method\n",
|
"# Run dichotomy method\n",
|
||||||
"optimal_point_dichotomy, iterations_dichotomy = dichotomy_method(aL, aR)\n",
|
"optimal_point_dichotomy, iterations_dichotomy = dichotomy_method(aL, aR)\n",
|
||||||
"print(f\"Optimal point (Dichotomy): {optimal_point_dichotomy}\")\n",
|
"print(f\"Optimal point (Dichotomy): {optimal_point_dichotomy}\")\n",
|
||||||
"print(f\"Objective function value at optimal point (Dichotomy): {objective_function(optimal_point_dichotomy)}\")\n",
|
"print(\n",
|
||||||
|
" f\"Objective function value at optimal point (Dichotomy): {objective_function(optimal_point_dichotomy)}\"\n",
|
||||||
|
")\n",
|
||||||
"print(f\"Number of iterations (Dichotomy): {iterations_dichotomy}\")"
|
"print(f\"Number of iterations (Dichotomy): {iterations_dichotomy}\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -564,9 +567,7 @@
|
|||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": []
|
||||||
"\n"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
|
|||||||
@@ -42,20 +42,24 @@
|
|||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def generate_thetas(n):\n",
|
"def generate_thetas(n):\n",
|
||||||
" random_steps = np.random.random(n)\n",
|
" random_steps = np.random.random(n)\n",
|
||||||
" return np.concatenate(([0], np.cumsum(random_steps / np.sum(random_steps) * (2*np.pi))))\n",
|
" return np.concatenate(\n",
|
||||||
|
" ([0], np.cumsum(random_steps / np.sum(random_steps) * (2 * np.pi)))\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"n = 4\n",
|
"n = 4\n",
|
||||||
"thetas = generate_thetas(n)\n",
|
"thetas = generate_thetas(n)\n",
|
||||||
"thetas_inf = np.linspace(0, 2*np.pi, 1000)\n",
|
"thetas_inf = np.linspace(0, 2 * np.pi, 1000)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(figsize=(7, 7))\n",
|
"plt.figure(figsize=(7, 7))\n",
|
||||||
"plt.plot(np.cos(thetas), np.sin(thetas), label='polygon')\n",
|
"plt.plot(np.cos(thetas), np.sin(thetas), label=\"polygon\")\n",
|
||||||
"plt.scatter(np.cos(thetas), np.sin(thetas), color='red', label='vertices')\n",
|
"plt.scatter(np.cos(thetas), np.sin(thetas), color=\"red\", label=\"vertices\")\n",
|
||||||
"plt.plot(np.cos(thetas_inf), np.sin(thetas_inf), 'k--', label='unit circle', alpha=0.5)\n",
|
"plt.plot(np.cos(thetas_inf), np.sin(thetas_inf), \"k--\", label=\"unit circle\", alpha=0.5)\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.title(f'Polygon with {n} sides')\n",
|
"plt.title(f\"Polygon with {n} sides\")\n",
|
||||||
"plt.grid(True)\n",
|
"plt.grid(True)\n",
|
||||||
"plt.xlim(-1.1, 1.1)\n",
|
"plt.xlim(-1.1, 1.1)\n",
|
||||||
"plt.ylim(-1.1, 1.1)\n",
|
"plt.ylim(-1.1, 1.1)\n",
|
||||||
@@ -207,58 +211,61 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"from cProfile import label\n",
|
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"from scipy.optimize import minimize\n",
|
"from scipy.optimize import minimize\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def polygon_perimeter(theta, n):\n",
|
"def polygon_perimeter(theta, n):\n",
|
||||||
" points = np.array([[np.cos(t), np.sin(t)] for t in theta])\n",
|
" points = np.array([[np.cos(t), np.sin(t)] for t in theta])\n",
|
||||||
" perimeter = 0\n",
|
" perimeter = 0\n",
|
||||||
" for i in range(n-1):\n",
|
" for i in range(n - 1):\n",
|
||||||
" perimeter += np.sqrt(np.sum((points[i+1] - points[i])**2))\n",
|
" perimeter += np.sqrt(np.sum((points[i + 1] - points[i]) ** 2))\n",
|
||||||
" perimeter += np.sqrt(np.sum((points[0] - points[-1])**2))\n",
|
" perimeter += np.sqrt(np.sum((points[0] - points[-1]) ** 2))\n",
|
||||||
" return -perimeter\n",
|
" return -perimeter\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def constraint_increasing(theta):\n",
|
"def constraint_increasing(theta):\n",
|
||||||
" return np.array([theta[i+1] - theta[i] for i in range(len(theta)-1)])\n",
|
" return np.array([theta[i + 1] - theta[i] for i in range(len(theta) - 1)])\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"def optimize_polygon(n):\n",
|
"def optimize_polygon(n):\n",
|
||||||
" theta0 = generate_thetas(n)\n",
|
" theta0 = generate_thetas(n)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" constraints = [\n",
|
" constraints = [\n",
|
||||||
" {'type': 'ineq', 'fun': constraint_increasing},\n",
|
" {\"type\": \"ineq\", \"fun\": constraint_increasing},\n",
|
||||||
" {'type': 'eq', 'fun': lambda x: x[0]},\n",
|
" {\"type\": \"eq\", \"fun\": lambda x: x[0]},\n",
|
||||||
" {'type': 'ineq', 'fun': lambda x: 2*np.pi - x[-1]}\n",
|
" {\"type\": \"ineq\", \"fun\": lambda x: 2 * np.pi - x[-1]},\n",
|
||||||
" ]\n",
|
" ]\n",
|
||||||
"\n",
|
"\n",
|
||||||
" result = minimize(\n",
|
" result = minimize(\n",
|
||||||
" lambda x: polygon_perimeter(x, n),\n",
|
" lambda x: polygon_perimeter(x, n),\n",
|
||||||
" theta0,\n",
|
" theta0,\n",
|
||||||
" constraints=constraints,\n",
|
" constraints=constraints,\n",
|
||||||
" method='SLSQP'\n",
|
" method=\"SLSQP\",\n",
|
||||||
" )\n",
|
" )\n",
|
||||||
" \n",
|
"\n",
|
||||||
" return result.x\n",
|
" return result.x\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def plot_perimeter(n):\n",
|
"def plot_perimeter(n):\n",
|
||||||
" optimal_angles = optimize_polygon(n + 1)\n",
|
" optimal_angles = optimize_polygon(n + 1)\n",
|
||||||
" plt.figure(figsize=(7, 7))\n",
|
" plt.figure(figsize=(7, 7))\n",
|
||||||
" t = np.linspace(0, 2*np.pi, 100)\n",
|
" t = np.linspace(0, 2 * np.pi, 100)\n",
|
||||||
" plt.plot(np.cos(t), np.sin(t), 'k--', alpha=0.5, label='unit circle')\n",
|
" plt.plot(np.cos(t), np.sin(t), \"k--\", alpha=0.5, label=\"unit circle\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" points = np.array([[np.cos(t), np.sin(t)] for t in optimal_angles])\n",
|
" points = np.array([[np.cos(t), np.sin(t)] for t in optimal_angles])\n",
|
||||||
" points = np.vstack([points, points[0]])\n",
|
" points = np.vstack([points, points[0]])\n",
|
||||||
" plt.plot(points[:, 0], points[:, 1], 'b-', linewidth=2, label='optimal polygon')\n",
|
" plt.plot(points[:, 0], points[:, 1], \"b-\", linewidth=2, label=\"optimal polygon\")\n",
|
||||||
" plt.scatter(points[:-1, 0], points[:-1, 1], color='red', label='vertices')\n",
|
" plt.scatter(points[:-1, 0], points[:-1, 1], color=\"red\", label=\"vertices\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" plt.legend()\n",
|
" plt.legend()\n",
|
||||||
" plt.axis('equal')\n",
|
" plt.axis(\"equal\")\n",
|
||||||
" plt.grid(True)\n",
|
" plt.grid(True)\n",
|
||||||
" plt.title(f'Optimal {n}-sided Polygon Inscribed in Unit Circle')\n",
|
" plt.title(f\"Optimal {n}-sided Polygon Inscribed in Unit Circle\")\n",
|
||||||
" plt.xlabel('x')\n",
|
" plt.xlabel(\"x\")\n",
|
||||||
" plt.ylabel('y')\n",
|
" plt.ylabel(\"y\")\n",
|
||||||
" plt.axis('equal')\n",
|
" plt.axis(\"equal\")\n",
|
||||||
" plt.grid(True)\n",
|
" plt.grid(True)\n",
|
||||||
" plt.show()\n",
|
" plt.show()\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -266,6 +273,7 @@
|
|||||||
" print(f\"Maximum perimeter: {-polygon_perimeter(optimal_angles, n)}\")\n",
|
" print(f\"Maximum perimeter: {-polygon_perimeter(optimal_angles, n)}\")\n",
|
||||||
" print(f\"2 * pi = {2 * np.pi}\")\n",
|
" print(f\"2 * pi = {2 * np.pi}\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"for n in np.arange(3, 10, 1):\n",
|
"for n in np.arange(3, 10, 1):\n",
|
||||||
" plot_perimeter(n)"
|
" plot_perimeter(n)"
|
||||||
]
|
]
|
||||||
@@ -316,9 +324,11 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"x0 = np.array([2, -1, 3, 0, -5])\n",
|
"x0 = np.array([2, -1, 3, 0, -5])\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def K(x):\n",
|
"def K(x):\n",
|
||||||
" return np.minimum(x, 0)\n",
|
" return np.minimum(x, 0)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"print(f\"Initial point: {x0}\")\n",
|
"print(f\"Initial point: {x0}\")\n",
|
||||||
"print(f\"Projection of x0 onto K: {K(x0)}\")"
|
"print(f\"Projection of x0 onto K: {K(x0)}\")"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
{
|
{
|
||||||
"cells": [
|
"cells": [
|
||||||
{
|
{
|
||||||
"metadata": {},
|
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
"id": "81049114d821d00e",
|
||||||
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# Project - Portfolio Management\n",
|
"# Project - Portfolio Management\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -11,52 +12,36 @@
|
|||||||
"### Time period studied from 2017-01-01 to 2018-01-01\n",
|
"### Time period studied from 2017-01-01 to 2018-01-01\n",
|
||||||
"\n",
|
"\n",
|
||||||
"### Risk-free rate: 2%"
|
"### Risk-free rate: 2%"
|
||||||
],
|
]
|
||||||
"id": "81049114d821d00e"
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
|
"execution_count": 51,
|
||||||
"id": "initial_id",
|
"id": "initial_id",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"collapsed": true,
|
|
||||||
"ExecuteTime": {
|
"ExecuteTime": {
|
||||||
"end_time": "2024-11-25T13:43:46.298758Z",
|
"end_time": "2024-11-25T13:43:46.298758Z",
|
||||||
"start_time": "2024-11-25T13:43:46.293696Z"
|
"start_time": "2024-11-25T13:43:46.293696Z"
|
||||||
}
|
},
|
||||||
|
"collapsed": true
|
||||||
},
|
},
|
||||||
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import yfinance as yf\n",
|
"import yfinance as yf\n",
|
||||||
"import pandas as pd\n",
|
"import pandas as pd\n",
|
||||||
"import numpy as np"
|
"import numpy as np"
|
||||||
],
|
]
|
||||||
"outputs": [],
|
|
||||||
"execution_count": 51
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 52,
|
||||||
|
"id": "9f9fc36832c97e0",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"ExecuteTime": {
|
"ExecuteTime": {
|
||||||
"end_time": "2024-11-25T13:43:47.318911Z",
|
"end_time": "2024-11-25T13:43:47.318911Z",
|
||||||
"start_time": "2024-11-25T13:43:47.198820Z"
|
"start_time": "2024-11-25T13:43:47.198820Z"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cell_type": "code",
|
|
||||||
"source": [
|
|
||||||
"# Data Extraction\n",
|
|
||||||
"Tickers = [\"^RUT\", \"^IXIC\", \"^GSPC\", \"XWD.TO\"]\n",
|
|
||||||
"start_input = \"2017-01-01\"\n",
|
|
||||||
"end_input = \"2018-01-01\"\n",
|
|
||||||
"S = pd.DataFrame()\n",
|
|
||||||
"for t in Tickers:\n",
|
|
||||||
" S[t] = yf.Tickers(t).history(start=start_input, end=end_input)[\"Close\"]\n",
|
|
||||||
"\n",
|
|
||||||
"S = S.interpolate(method=\"pad\")\n",
|
|
||||||
"\n",
|
|
||||||
"# Show the first five and last five values extracted\n",
|
|
||||||
"display(S.head())\n",
|
|
||||||
"display(S.tail())\n",
|
|
||||||
"print(S.shape)"
|
|
||||||
],
|
|
||||||
"id": "9f9fc36832c97e0",
|
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
"name": "stderr",
|
"name": "stderr",
|
||||||
@@ -72,15 +57,6 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"data": {
|
"data": {
|
||||||
"text/plain": [
|
|
||||||
" ^RUT ^IXIC ^GSPC XWD.TO\n",
|
|
||||||
"Date \n",
|
|
||||||
"2017-01-03 00:00:00+00:00 1365.489990 5429.080078 2257.830078 38.499630\n",
|
|
||||||
"2017-01-04 00:00:00+00:00 1387.949951 5477.000000 2270.750000 38.553375\n",
|
|
||||||
"2017-01-05 00:00:00+00:00 1371.939941 5487.939941 2269.000000 38.481716\n",
|
|
||||||
"2017-01-06 00:00:00+00:00 1367.280029 5521.060059 2276.979980 38.517544\n",
|
|
||||||
"2017-01-09 00:00:00+00:00 1357.489990 5531.819824 2268.899902 38.383186"
|
|
||||||
],
|
|
||||||
"text/html": [
|
"text/html": [
|
||||||
"<div>\n",
|
"<div>\n",
|
||||||
"<style scoped>\n",
|
"<style scoped>\n",
|
||||||
@@ -152,6 +128,15 @@
|
|||||||
" </tbody>\n",
|
" </tbody>\n",
|
||||||
"</table>\n",
|
"</table>\n",
|
||||||
"</div>"
|
"</div>"
|
||||||
|
],
|
||||||
|
"text/plain": [
|
||||||
|
" ^RUT ^IXIC ^GSPC XWD.TO\n",
|
||||||
|
"Date \n",
|
||||||
|
"2017-01-03 00:00:00+00:00 1365.489990 5429.080078 2257.830078 38.499630\n",
|
||||||
|
"2017-01-04 00:00:00+00:00 1387.949951 5477.000000 2270.750000 38.553375\n",
|
||||||
|
"2017-01-05 00:00:00+00:00 1371.939941 5487.939941 2269.000000 38.481716\n",
|
||||||
|
"2017-01-06 00:00:00+00:00 1367.280029 5521.060059 2276.979980 38.517544\n",
|
||||||
|
"2017-01-09 00:00:00+00:00 1357.489990 5531.819824 2268.899902 38.383186"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -159,15 +144,6 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"data": {
|
"data": {
|
||||||
"text/plain": [
|
|
||||||
" ^RUT ^IXIC ^GSPC XWD.TO\n",
|
|
||||||
"Date \n",
|
|
||||||
"2017-12-22 00:00:00+00:00 1542.930054 6959.959961 2683.340088 44.323349\n",
|
|
||||||
"2017-12-26 00:00:00+00:00 1544.229980 6936.250000 2680.500000 44.323349\n",
|
|
||||||
"2017-12-27 00:00:00+00:00 1543.939941 6939.339844 2682.620117 44.052303\n",
|
|
||||||
"2017-12-28 00:00:00+00:00 1548.930054 6950.160156 2687.540039 43.857414\n",
|
|
||||||
"2017-12-29 00:00:00+00:00 1535.510010 6903.390137 2673.610107 43.784576"
|
|
||||||
],
|
|
||||||
"text/html": [
|
"text/html": [
|
||||||
"<div>\n",
|
"<div>\n",
|
||||||
"<style scoped>\n",
|
"<style scoped>\n",
|
||||||
@@ -239,6 +215,15 @@
|
|||||||
" </tbody>\n",
|
" </tbody>\n",
|
||||||
"</table>\n",
|
"</table>\n",
|
||||||
"</div>"
|
"</div>"
|
||||||
|
],
|
||||||
|
"text/plain": [
|
||||||
|
" ^RUT ^IXIC ^GSPC XWD.TO\n",
|
||||||
|
"Date \n",
|
||||||
|
"2017-12-22 00:00:00+00:00 1542.930054 6959.959961 2683.340088 44.323349\n",
|
||||||
|
"2017-12-26 00:00:00+00:00 1544.229980 6936.250000 2680.500000 44.323349\n",
|
||||||
|
"2017-12-27 00:00:00+00:00 1543.939941 6939.339844 2682.620117 44.052303\n",
|
||||||
|
"2017-12-28 00:00:00+00:00 1548.930054 6950.160156 2687.540039 43.857414\n",
|
||||||
|
"2017-12-29 00:00:00+00:00 1535.510010 6903.390137 2673.610107 43.784576"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -252,63 +237,69 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"execution_count": 52
|
"source": [
|
||||||
|
"# Data Extraction\n",
|
||||||
|
"Tickers = [\"^RUT\", \"^IXIC\", \"^GSPC\", \"XWD.TO\"]\n",
|
||||||
|
"start_input = \"2017-01-01\"\n",
|
||||||
|
"end_input = \"2018-01-01\"\n",
|
||||||
|
"S = pd.DataFrame()\n",
|
||||||
|
"for t in Tickers:\n",
|
||||||
|
" S[t] = yf.Tickers(t).history(start=start_input, end=end_input)[\"Close\"]\n",
|
||||||
|
"\n",
|
||||||
|
"S = S.interpolate(method=\"pad\")\n",
|
||||||
|
"\n",
|
||||||
|
"# Show the first five and last five values extracted\n",
|
||||||
|
"display(S.head())\n",
|
||||||
|
"display(S.tail())\n",
|
||||||
|
"print(S.shape)"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 53,
|
||||||
|
"id": "53483cf3a925a4db",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"ExecuteTime": {
|
"ExecuteTime": {
|
||||||
"end_time": "2024-11-25T13:43:50.080380Z",
|
"end_time": "2024-11-25T13:43:50.080380Z",
|
||||||
"start_time": "2024-11-25T13:43:50.073119Z"
|
"start_time": "2024-11-25T13:43:50.073119Z"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cell_type": "code",
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"R = S / S.shift() - 1\n",
|
"R = S / S.shift() - 1\n",
|
||||||
"R = R[1:]\n",
|
"R = R[1:]\n",
|
||||||
"mean_d = R.mean()\n",
|
"mean_d = R.mean()\n",
|
||||||
"covar_d = R.cov()\n",
|
"covar_d = R.cov()\n",
|
||||||
"corr = R.corr()"
|
"corr = R.corr()"
|
||||||
],
|
]
|
||||||
"id": "53483cf3a925a4db",
|
|
||||||
"outputs": [],
|
|
||||||
"execution_count": 53
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 54,
|
||||||
|
"id": "c327ed5967b1f442",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"ExecuteTime": {
|
"ExecuteTime": {
|
||||||
"end_time": "2024-11-25T13:43:50.965092Z",
|
"end_time": "2024-11-25T13:43:50.965092Z",
|
||||||
"start_time": "2024-11-25T13:43:50.961969Z"
|
"start_time": "2024-11-25T13:43:50.961969Z"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cell_type": "code",
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"mean = mean_d * 252\n",
|
"mean = mean_d * 252\n",
|
||||||
"covar = covar_d * 252\n",
|
"covar = covar_d * 252\n",
|
||||||
"std = np.sqrt(np.diag(covar))"
|
"std = np.sqrt(np.diag(covar))"
|
||||||
],
|
]
|
||||||
"id": "c327ed5967b1f442",
|
|
||||||
"outputs": [],
|
|
||||||
"execution_count": 54
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 55,
|
||||||
|
"id": "6bc6a850bf06cc9d",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"ExecuteTime": {
|
"ExecuteTime": {
|
||||||
"end_time": "2024-11-25T13:43:51.701725Z",
|
"end_time": "2024-11-25T13:43:51.701725Z",
|
||||||
"start_time": "2024-11-25T13:43:51.695020Z"
|
"start_time": "2024-11-25T13:43:51.695020Z"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cell_type": "code",
|
|
||||||
"source": [
|
|
||||||
"print(\"Mean:\\n\")\n",
|
|
||||||
"print(mean)\n",
|
|
||||||
"print(\"\\nCovariance:\\n\")\n",
|
|
||||||
"print(covar)\n",
|
|
||||||
"print(\"\\nStandard Deviation:\\n\")\n",
|
|
||||||
"print(std)\n",
|
|
||||||
"print(\"\\nCorrelation:\\n\")\n",
|
|
||||||
"print(corr)"
|
|
||||||
],
|
|
||||||
"id": "6bc6a850bf06cc9d",
|
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
"name": "stdout",
|
"name": "stdout",
|
||||||
@@ -344,22 +335,34 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"execution_count": 55
|
"source": [
|
||||||
|
"print(\"Mean:\\n\")\n",
|
||||||
|
"print(mean)\n",
|
||||||
|
"print(\"\\nCovariance:\\n\")\n",
|
||||||
|
"print(covar)\n",
|
||||||
|
"print(\"\\nStandard Deviation:\\n\")\n",
|
||||||
|
"print(std)\n",
|
||||||
|
"print(\"\\nCorrelation:\\n\")\n",
|
||||||
|
"print(corr)"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"metadata": {},
|
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"source": "# Question 1",
|
"id": "fc4bec874f710f7c",
|
||||||
"id": "fc4bec874f710f7c"
|
"metadata": {},
|
||||||
|
"source": "# Question 1"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 56,
|
||||||
|
"id": "780c9cca6e0ed2d3",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"ExecuteTime": {
|
"ExecuteTime": {
|
||||||
"end_time": "2024-11-25T13:43:53.113423Z",
|
"end_time": "2024-11-25T13:43:53.113423Z",
|
||||||
"start_time": "2024-11-25T13:43:53.109514Z"
|
"start_time": "2024-11-25T13:43:53.109514Z"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cell_type": "code",
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"r = 0.02\n",
|
"r = 0.02\n",
|
||||||
"d = len(Tickers)\n",
|
"d = len(Tickers)\n",
|
||||||
@@ -369,32 +372,18 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"a = vec1.T.dot(inv_sigma).dot(vec1)\n",
|
"a = vec1.T.dot(inv_sigma).dot(vec1)\n",
|
||||||
"b = mean.T.dot(inv_sigma).dot(vec1)"
|
"b = mean.T.dot(inv_sigma).dot(vec1)"
|
||||||
],
|
]
|
||||||
"id": "780c9cca6e0ed2d3",
|
|
||||||
"outputs": [],
|
|
||||||
"execution_count": 56
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 57,
|
||||||
|
"id": "81c956f147c68070",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"ExecuteTime": {
|
"ExecuteTime": {
|
||||||
"end_time": "2024-11-25T13:43:54.545400Z",
|
"end_time": "2024-11-25T13:43:54.545400Z",
|
||||||
"start_time": "2024-11-25T13:43:54.541579Z"
|
"start_time": "2024-11-25T13:43:54.541579Z"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cell_type": "code",
|
|
||||||
"source": [
|
|
||||||
"# Tangent portfolio\n",
|
|
||||||
"pi_T = inv_sigma.dot(mean - r * vec1) / (b - r * a)\n",
|
|
||||||
"sd_T = np.sqrt(pi_T.T.dot(sigma).dot(pi_T)) # Variance\n",
|
|
||||||
"m_T = pi_T.T.dot(mean) # expected return\n",
|
|
||||||
"\n",
|
|
||||||
"print(f\"Expected return m_T: {m_T}\")\n",
|
|
||||||
"print(f\"Standard deviation sd_T: {sd_T}\")\n",
|
|
||||||
"print(f\"Allocation pi_T: {pi_T}\")\n",
|
|
||||||
"print(\n",
|
|
||||||
" f\"We can verify that the allocation is possible as the sum of the allocations for the different indices is {sum(pi_T)}, that is very close to 1\")"
|
|
||||||
],
|
|
||||||
"id": "81c956f147c68070",
|
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
"name": "stdout",
|
"name": "stdout",
|
||||||
@@ -407,32 +396,36 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"execution_count": 57
|
"source": [
|
||||||
|
"# Tangent portfolio\n",
|
||||||
|
"pi_T = inv_sigma.dot(mean - r * vec1) / (b - r * a)\n",
|
||||||
|
"sd_T = np.sqrt(pi_T.T.dot(sigma).dot(pi_T)) # Variance\n",
|
||||||
|
"m_T = pi_T.T.dot(mean) # expected return\n",
|
||||||
|
"\n",
|
||||||
|
"print(f\"Expected return m_T: {m_T}\")\n",
|
||||||
|
"print(f\"Standard deviation sd_T: {sd_T}\")\n",
|
||||||
|
"print(f\"Allocation pi_T: {pi_T}\")\n",
|
||||||
|
"print(\n",
|
||||||
|
" f\"We can verify that the allocation is possible as the sum of the allocations for the different indices is {sum(pi_T)}, that is very close to 1\"\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"metadata": {},
|
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"source": "# Question 2",
|
"id": "2e121c2dfb946f3c",
|
||||||
"id": "2e121c2dfb946f3c"
|
"metadata": {},
|
||||||
|
"source": "# Question 2"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 58,
|
||||||
|
"id": "c169808384ca1112",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"ExecuteTime": {
|
"ExecuteTime": {
|
||||||
"end_time": "2024-11-25T13:43:59.797115Z",
|
"end_time": "2024-11-25T13:43:59.797115Z",
|
||||||
"start_time": "2024-11-25T13:43:59.792462Z"
|
"start_time": "2024-11-25T13:43:59.792462Z"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cell_type": "code",
|
|
||||||
"source": [
|
|
||||||
"for i in range(len(std)):\n",
|
|
||||||
" print(f\"The annualized volatilities of the index {Tickers[i]} is {std[i]}\")\n",
|
|
||||||
" print(f\"The annualized expected returns of the index {Tickers[i]} is {mean[Tickers[i]]}\")\n",
|
|
||||||
" print(\"\")\n",
|
|
||||||
"\n",
|
|
||||||
"print(f\"The annualized volatility of the Tangent Portfolio is {sd_T * np.sqrt(252)}\")\n",
|
|
||||||
"print(f\"The annualized expected return of the Tangent Portfolio is {m_T * 252}\")"
|
|
||||||
],
|
|
||||||
"id": "c169808384ca1112",
|
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
"name": "stdout",
|
"name": "stdout",
|
||||||
@@ -455,29 +448,34 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"execution_count": 58
|
"source": [
|
||||||
|
"for i in range(len(std)):\n",
|
||||||
|
" print(f\"The annualized volatilities of the index {Tickers[i]} is {std[i]}\")\n",
|
||||||
|
" print(\n",
|
||||||
|
" f\"The annualized expected returns of the index {Tickers[i]} is {mean[Tickers[i]]}\"\n",
|
||||||
|
" )\n",
|
||||||
|
" print(\"\")\n",
|
||||||
|
"\n",
|
||||||
|
"print(f\"The annualized volatility of the Tangent Portfolio is {sd_T * np.sqrt(252)}\")\n",
|
||||||
|
"print(f\"The annualized expected return of the Tangent Portfolio is {m_T * 252}\")"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"metadata": {},
|
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"source": "# Question 3",
|
"id": "af8d29ecdbf2ae1",
|
||||||
"id": "af8d29ecdbf2ae1"
|
"metadata": {},
|
||||||
|
"source": "# Question 3"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 59,
|
||||||
|
"id": "2e0215ab7904906a",
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"ExecuteTime": {
|
"ExecuteTime": {
|
||||||
"end_time": "2024-11-25T13:44:01.393591Z",
|
"end_time": "2024-11-25T13:44:01.393591Z",
|
||||||
"start_time": "2024-11-25T13:44:01.388830Z"
|
"start_time": "2024-11-25T13:44:01.388830Z"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"cell_type": "code",
|
|
||||||
"source": [
|
|
||||||
"print(\"sharpe ratio of the Tangent portfolio :\", (m_T - r) / sd_T)\n",
|
|
||||||
"\n",
|
|
||||||
"for i in range(4):\n",
|
|
||||||
" print(f\"the sharpe ratio of the index {Tickers[i]} is {(mean[Tickers[i]] - r) / std[i]}\")"
|
|
||||||
],
|
|
||||||
"id": "2e0215ab7904906a",
|
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
"name": "stdout",
|
"name": "stdout",
|
||||||
@@ -491,7 +489,14 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"execution_count": 59
|
"source": [
|
||||||
|
"print(\"sharpe ratio of the Tangent portfolio :\", (m_T - r) / sd_T)\n",
|
||||||
|
"\n",
|
||||||
|
"for i in range(4):\n",
|
||||||
|
" print(\n",
|
||||||
|
" f\"the sharpe ratio of the index {Tickers[i]} is {(mean[Tickers[i]] - r) / std[i]}\"\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -43,7 +43,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"import warnings\n",
|
"import warnings\n",
|
||||||
"\n",
|
"\n",
|
||||||
"warnings.filterwarnings('ignore')"
|
"warnings.filterwarnings(\"ignore\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -434,7 +434,7 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import pandas as pd # dataframes are in pandas \n",
|
"import pandas as pd # dataframes are in pandas\n",
|
||||||
"import matplotlib.pyplot as plt\n",
|
"import matplotlib.pyplot as plt\n",
|
||||||
"\n",
|
"\n",
|
||||||
"hitters = pd.read_csv(\"data/Hitters.csv\", index_col=\"Name\")\n",
|
"hitters = pd.read_csv(\"data/Hitters.csv\", index_col=\"Name\")\n",
|
||||||
@@ -895,9 +895,13 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# Hint for Question (4) :\n",
|
"# Hint for Question (4) :\n",
|
||||||
"ex = pd.DataFrame(dict(nom=['Alice', 'Nicolas', 'Jean'],\n",
|
"ex = pd.DataFrame(\n",
|
||||||
" age=[19, np.NaN, np.NaN],\n",
|
" dict(\n",
|
||||||
" exam=[15, 14, np.NaN]))\n",
|
" nom=[\"Alice\", \"Nicolas\", \"Jean\"],\n",
|
||||||
|
" age=[19, np.NaN, np.NaN],\n",
|
||||||
|
" exam=[15, 14, np.NaN],\n",
|
||||||
|
" )\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print(\"data : \\n\", ex)\n",
|
"print(\"data : \\n\", ex)\n",
|
||||||
"print(\"First result : \\n\", ex.isnull())\n",
|
"print(\"First result : \\n\", ex.isnull())\n",
|
||||||
@@ -1080,10 +1084,10 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# We remove the players for whom Salary is missing\n",
|
"# We remove the players for whom Salary is missing\n",
|
||||||
"hitters.dropna(subset=['Salary'], inplace=True)\n",
|
"hitters.dropna(subset=[\"Salary\"], inplace=True)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"X = hitters.select_dtypes(include=int)\n",
|
"X = hitters.select_dtypes(include=int)\n",
|
||||||
"Y = hitters['Salary']\n",
|
"Y = hitters[\"Salary\"]\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# check-point\n",
|
"# check-point\n",
|
||||||
"print(Y.isnull().sum()) # should be 0\n",
|
"print(Y.isnull().sum()) # should be 0\n",
|
||||||
@@ -1109,7 +1113,7 @@
|
|||||||
},
|
},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"#Answer for Exercise 4\n",
|
"# Answer for Exercise 4\n",
|
||||||
"from sklearn.model_selection import train_test_split\n",
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Xtrain, Xtest, Ytrain, Ytest = train_test_split(X, Y, test_size=0.3, random_state=42)"
|
"Xtrain, Xtest, Ytrain, Ytest = train_test_split(X, Y, test_size=0.3, random_state=42)"
|
||||||
@@ -1697,8 +1701,8 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"#the values of alphas chosen by defaults are also on a logarithmic scale\n",
|
"# the values of alphas chosen by defaults are also on a logarithmic scale\n",
|
||||||
"plt.plot(np.log10(alphas_lasso), '.')"
|
"plt.plot(np.log10(alphas_lasso), \".\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1735,8 +1739,8 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"fig, ax = plt.subplots(figsize=(8, 6))\n",
|
"fig, ax = plt.subplots(figsize=(8, 6))\n",
|
||||||
"ax.plot(np.log10(alphas_lasso), coefs_lasso)\n",
|
"ax.plot(np.log10(alphas_lasso), coefs_lasso)\n",
|
||||||
"ax.set_xlabel('log10(alpha)')\n",
|
"ax.set_xlabel(\"log10(alpha)\")\n",
|
||||||
"ax.set_ylabel('Lasso coefficients')"
|
"ax.set_ylabel(\"Lasso coefficients\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1792,7 +1796,7 @@
|
|||||||
"print(\"1.\\n\", ind)\n",
|
"print(\"1.\\n\", ind)\n",
|
||||||
"print(\"2.\\n\", ind == 0)\n",
|
"print(\"2.\\n\", ind == 0)\n",
|
||||||
"print(\"3. Le nombre de 0 de chaque colonne est :\\n \", (ind == 0).sum(axis=0))\n",
|
"print(\"3. Le nombre de 0 de chaque colonne est :\\n \", (ind == 0).sum(axis=0))\n",
|
||||||
"print(\"4. Le nombre de 0 de chaque ligne est : \\n\", (ind == 0).sum(axis=1))\n"
|
"print(\"4. Le nombre de 0 de chaque ligne est : \\n\", (ind == 0).sum(axis=1))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -2294,18 +2298,19 @@
|
|||||||
"from sklearn.linear_model import LinearRegression\n",
|
"from sklearn.linear_model import LinearRegression\n",
|
||||||
"\n",
|
"\n",
|
||||||
"linReg = LinearRegression()\n",
|
"linReg = LinearRegression()\n",
|
||||||
"linReg.fit(Xtrain,\n",
|
"linReg.fit(\n",
|
||||||
" Ytrain) # no need to scale for OLS if you just want to predict (unless the solver works best with scaled data)\n",
|
" Xtrain, Ytrain\n",
|
||||||
|
") # no need to scale for OLS if you just want to predict (unless the solver works best with scaled data)\n",
|
||||||
"# the predictions should not be different with or without standardization (could differ only owing to numerical problems)\n",
|
"# the predictions should not be different with or without standardization (could differ only owing to numerical problems)\n",
|
||||||
"hatY_LinReg = linReg.predict(Xtest)\n",
|
"hatY_LinReg = linReg.predict(Xtest)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"fig, ax = plt.subplots()\n",
|
"fig, ax = plt.subplots()\n",
|
||||||
"ax.scatter(Ytest, hatY_LinReg, s=5)\n",
|
"ax.scatter(Ytest, hatY_LinReg, s=5)\n",
|
||||||
"ax.plot([0, 1], [0, 1], transform=ax.transAxes, ls='--', c='gray')\n",
|
"ax.plot([0, 1], [0, 1], transform=ax.transAxes, ls=\"--\", c=\"gray\")\n",
|
||||||
"ax.set_xlabel('Ytest')\n",
|
"ax.set_xlabel(\"Ytest\")\n",
|
||||||
"ax.set_ylabel('hatY')\n",
|
"ax.set_ylabel(\"hatY\")\n",
|
||||||
"ax.set_title('Predicted vs true salaries for OLS estimator')\n",
|
"ax.set_title(\"Predicted vs true salaries for OLS estimator\")\n",
|
||||||
"ax.axis('square')"
|
"ax.axis(\"square\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -2355,11 +2360,11 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"fig, ax = plt.subplots()\n",
|
"fig, ax = plt.subplots()\n",
|
||||||
"ax.scatter(Ytest, hatY_ridge, s=5)\n",
|
"ax.scatter(Ytest, hatY_ridge, s=5)\n",
|
||||||
"ax.plot([0, 1], [0, 1], transform=ax.transAxes, ls='--', c='gray')\n",
|
"ax.plot([0, 1], [0, 1], transform=ax.transAxes, ls=\"--\", c=\"gray\")\n",
|
||||||
"ax.set_xlabel('Ytest')\n",
|
"ax.set_xlabel(\"Ytest\")\n",
|
||||||
"ax.set_ylabel('hatY')\n",
|
"ax.set_ylabel(\"hatY\")\n",
|
||||||
"ax.set_title('Predicted vs true salaries for Ridge estimator')\n",
|
"ax.set_title(\"Predicted vs true salaries for Ridge estimator\")\n",
|
||||||
"ax.axis('square')"
|
"ax.axis(\"square\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -2408,11 +2413,11 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"fig, ax = plt.subplots()\n",
|
"fig, ax = plt.subplots()\n",
|
||||||
"ax.scatter(Ytest, hatY_lasso, s=5)\n",
|
"ax.scatter(Ytest, hatY_lasso, s=5)\n",
|
||||||
"ax.plot([0, 1], [0, 1], transform=ax.transAxes, ls='--', c='gray')\n",
|
"ax.plot([0, 1], [0, 1], transform=ax.transAxes, ls=\"--\", c=\"gray\")\n",
|
||||||
"ax.set_xlabel('Ytest')\n",
|
"ax.set_xlabel(\"Ytest\")\n",
|
||||||
"ax.set_ylabel('hatY')\n",
|
"ax.set_ylabel(\"hatY\")\n",
|
||||||
"ax.set_title('Predicted vs true salaries for Ridge estimator')\n",
|
"ax.set_title(\"Predicted vs true salaries for Ridge estimator\")\n",
|
||||||
"ax.axis('square')"
|
"ax.axis(\"square\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -2445,7 +2450,7 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from sklearn.linear_model import LassoLarsIC\n",
|
"from sklearn.linear_model import LassoLarsIC\n",
|
||||||
"\n",
|
"\n",
|
||||||
"lassoBIC = LassoLarsIC(criterion='bic')\n",
|
"lassoBIC = LassoLarsIC(criterion=\"bic\")\n",
|
||||||
"lassoBIC.fit(XtrainScaled, Ytrain)\n",
|
"lassoBIC.fit(XtrainScaled, Ytrain)\n",
|
||||||
"print(\"best alpha chosen by BIC criterion :\", lassoBIC.alpha_)\n",
|
"print(\"best alpha chosen by BIC criterion :\", lassoBIC.alpha_)\n",
|
||||||
"print(\"best alpha chosen by CV :\", lassoCV.alpha_)\n",
|
"print(\"best alpha chosen by CV :\", lassoCV.alpha_)\n",
|
||||||
@@ -2499,11 +2504,11 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"fig, ax = plt.subplots()\n",
|
"fig, ax = plt.subplots()\n",
|
||||||
"ax.scatter(Ytest, hatY_BIC, s=5)\n",
|
"ax.scatter(Ytest, hatY_BIC, s=5)\n",
|
||||||
"ax.plot([0, 1], [0, 1], transform=ax.transAxes, ls='--', c='gray')\n",
|
"ax.plot([0, 1], [0, 1], transform=ax.transAxes, ls=\"--\", c=\"gray\")\n",
|
||||||
"ax.set_xlabel('Ytest')\n",
|
"ax.set_xlabel(\"Ytest\")\n",
|
||||||
"ax.set_ylabel('hatY')\n",
|
"ax.set_ylabel(\"hatY\")\n",
|
||||||
"ax.set_title('Predicted vs true salaries for LassoBIC estimator')\n",
|
"ax.set_title(\"Predicted vs true salaries for LassoBIC estimator\")\n",
|
||||||
"ax.axis('square')"
|
"ax.axis(\"square\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -2539,7 +2544,9 @@
|
|||||||
"from sklearn.metrics import mean_squared_error\n",
|
"from sklearn.metrics import mean_squared_error\n",
|
||||||
"\n",
|
"\n",
|
||||||
"MSEs = []\n",
|
"MSEs = []\n",
|
||||||
"for name, estimator in zip([\"LassoCV\", \"LassoBIC\", \"RidgeCV\", \"OLS\"], [lassoCV, lassoBIC, ridgeCV, linReg]):\n",
|
"for name, estimator in zip(\n",
|
||||||
|
" [\"LassoCV\", \"LassoBIC\", \"RidgeCV\", \"OLS\"], [lassoCV, lassoBIC, ridgeCV, linReg]\n",
|
||||||
|
"):\n",
|
||||||
" y_pred = estimator.predict(Xtest)\n",
|
" y_pred = estimator.predict(Xtest)\n",
|
||||||
" MSE = mean_squared_error(Ytest, y_pred)\n",
|
" MSE = mean_squared_error(Ytest, y_pred)\n",
|
||||||
" print(f\"MSE for {name} : {MSE}\")\n",
|
" print(f\"MSE for {name} : {MSE}\")\n",
|
||||||
@@ -2584,10 +2591,12 @@
|
|||||||
"ols_errors = np.abs(Ytest - linReg.predict(Xtest))\n",
|
"ols_errors = np.abs(Ytest - linReg.predict(Xtest))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"fig, ax = plt.subplots(figsize=(10, 6))\n",
|
"fig, ax = plt.subplots(figsize=(10, 6))\n",
|
||||||
"ax.boxplot([ridge_cv_errors, lasso_cv_errors, lasso_bic_errors, ols_errors],\n",
|
"ax.boxplot(\n",
|
||||||
" labels=['RidgeCV', 'LassoCV', 'LassoBIC', 'OLS'])\n",
|
" [ridge_cv_errors, lasso_cv_errors, lasso_bic_errors, ols_errors],\n",
|
||||||
"ax.set_title('Boxplot of Absolute Errors')\n",
|
" labels=[\"RidgeCV\", \"LassoCV\", \"LassoBIC\", \"OLS\"],\n",
|
||||||
"ax.set_ylabel('Absolute Error')\n",
|
")\n",
|
||||||
|
"ax.set_title(\"Boxplot of Absolute Errors\")\n",
|
||||||
|
"ax.set_ylabel(\"Absolute Error\")\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -32,7 +32,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import pandas as pd \n",
|
"import pandas as pd\n",
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"import matplotlib.pyplot as plt"
|
"import matplotlib.pyplot as plt"
|
||||||
]
|
]
|
||||||
@@ -226,7 +226,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"sms = pd.read_csv(\"data/spam.csv\", encoding='latin')\n",
|
"sms = pd.read_csv(\"data/spam.csv\", encoding=\"latin\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"sms.head()"
|
"sms.head()"
|
||||||
]
|
]
|
||||||
@@ -244,7 +244,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"sms.rename(columns={'v1':'Label', 'v2':'Text'}, inplace=True)"
|
"sms.rename(columns={\"v1\": \"Label\", \"v2\": \"Text\"}, inplace=True)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -644,7 +644,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"sms['Labelnum']=sms['Label'].map({'ham':0,'spam':1})\n",
|
"sms[\"Labelnum\"] = sms[\"Label\"].map({\"ham\": 0, \"spam\": 1})\n",
|
||||||
"\n",
|
"\n",
|
||||||
"sms.head()"
|
"sms.head()"
|
||||||
]
|
]
|
||||||
@@ -674,13 +674,13 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# Hint 1 for Exercise 1 \n",
|
"# Hint 1 for Exercise 1\n",
|
||||||
"a=np.array([0,1,1,1,0])\n",
|
"a = np.array([0, 1, 1, 1, 0])\n",
|
||||||
"print (len(a))\n",
|
"print(len(a))\n",
|
||||||
"print (a[a==0])\n",
|
"print(a[a == 0])\n",
|
||||||
"print (len(a[a==0]))\n",
|
"print(len(a[a == 0]))\n",
|
||||||
"print (a[a==1])\n",
|
"print(a[a == 1])\n",
|
||||||
"print (len(a[a==1]))"
|
"print(len(a[a == 1]))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -881,8 +881,8 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# Hint 2 for Exercise 1 \n",
|
"# Hint 2 for Exercise 1\n",
|
||||||
"sms[sms.Labelnum==0].head()"
|
"sms[sms.Labelnum == 0].head()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1083,8 +1083,8 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# Hint 3 for Exercise 1 \n",
|
"# Hint 3 for Exercise 1\n",
|
||||||
"sms[sms.Labelnum==1].head()"
|
"sms[sms.Labelnum == 1].head()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1104,8 +1104,8 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"print(len(sms))\n",
|
"print(len(sms))\n",
|
||||||
"print(sms[sms.Label == 'ham'].shape)\n",
|
"print(sms[sms.Label == \"ham\"].shape)\n",
|
||||||
"print(sms[sms.Label == 'spam'].shape)"
|
"print(sms[sms.Label == \"spam\"].shape)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1136,8 +1136,8 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# Hint 1 for Exercise 2\n",
|
"# Hint 1 for Exercise 2\n",
|
||||||
"print (sms.loc[0, 'Text']) \n",
|
"print(sms.loc[0, \"Text\"])\n",
|
||||||
"print (\"--> The length of the first sms is\", len(sms.loc[0, 'Text']))"
|
"print(\"--> The length of the first sms is\", len(sms.loc[0, \"Text\"]))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1160,10 +1160,13 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"plt.figure(figsize=(10, 6))\n",
|
"plt.figure(figsize=(10, 6))\n",
|
||||||
"plt.hist(sms.loc[:, 'Text'].apply(len), bins='stone',)\n",
|
"plt.hist(\n",
|
||||||
"plt.title('Histogram of SMS Lengths')\n",
|
" sms.loc[:, \"Text\"].apply(len),\n",
|
||||||
"plt.xlabel('Length')\t\n",
|
" bins=\"stone\",\n",
|
||||||
"plt.ylabel('Frequency')\n",
|
")\n",
|
||||||
|
"plt.title(\"Histogram of SMS Lengths\")\n",
|
||||||
|
"plt.xlabel(\"Length\")\n",
|
||||||
|
"plt.ylabel(\"Frequency\")\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -1222,30 +1225,41 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"Example = pd.DataFrame([['iphone gratuit iphone gratuit',1],['mille vert gratuit',0],\n",
|
"Example = pd.DataFrame(\n",
|
||||||
" ['iphone mille euro',0],['argent gratuit euro gratuit',1]],\n",
|
" [\n",
|
||||||
" columns=['sms', 'label'])\n",
|
" [\"iphone gratuit iphone gratuit\", 1],\n",
|
||||||
|
" [\"mille vert gratuit\", 0],\n",
|
||||||
|
" [\"iphone mille euro\", 0],\n",
|
||||||
|
" [\"argent gratuit euro gratuit\", 1],\n",
|
||||||
|
" ],\n",
|
||||||
|
" columns=[\"sms\", \"label\"],\n",
|
||||||
|
")\n",
|
||||||
"vec = CountVectorizer()\n",
|
"vec = CountVectorizer()\n",
|
||||||
"X = vec.fit_transform(Example.sms)\n",
|
"X = vec.fit_transform(Example.sms)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# 1. Displaying the vocabulary\n",
|
"# 1. Displaying the vocabulary\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print (\"1. The vocabulary of Example is \", vec.vocabulary_)\n",
|
"print(\"1. The vocabulary of Example is \", vec.vocabulary_)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# 1 bis :\n",
|
"# 1 bis :\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print('The vocabulary arranged in alphabetical order : ', sorted(list(vec.vocabulary_.keys())))\n",
|
"print(\n",
|
||||||
|
" \"The vocabulary arranged in alphabetical order : \",\n",
|
||||||
|
" sorted(list(vec.vocabulary_.keys())),\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# 2. Displaying the vectors : \n",
|
"# 2. Displaying the vectors :\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print (\"2. The vectors corresponding to the sms are : \\n\", X.toarray())# X.toarray because \n",
|
"print(\n",
|
||||||
"# X is a \"sparse\" matrix. \n",
|
" \"2. The vectors corresponding to the sms are : \\n\", X.toarray()\n",
|
||||||
|
") # X.toarray because\n",
|
||||||
|
"# X is a \"sparse\" matrix.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# 3. For a new data x_0=\"iphone gratuit\", \n",
|
"# 3. For a new data x_0=\"iphone gratuit\",\n",
|
||||||
"# you must also transform x_0 into a numerical vector before predicting. \n",
|
"# you must also transform x_0 into a numerical vector before predicting.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"vec_x_0=vec.transform(['iphone gratuit']).toarray() # \n",
|
"vec_x_0 = vec.transform([\"iphone gratuit\"]).toarray() #\n",
|
||||||
"print (\"3. The numerical vector corresponding to (x_0=iphone gratuit) is \\n\", vec_x_0 )"
|
"print(\"3. The numerical vector corresponding to (x_0=iphone gratuit) is \\n\", vec_x_0)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1267,7 +1281,7 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"#'sparse' version (without \"to_array\")\n",
|
"#'sparse' version (without \"to_array\")\n",
|
||||||
"v = vec.transform(['iphone iphone gratuit'])\n",
|
"v = vec.transform([\"iphone iphone gratuit\"])\n",
|
||||||
"v"
|
"v"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -1309,8 +1323,8 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# \"(0,2) 1\" means : the element in row 0 and column 2 is equal to 1. \n",
|
"# \"(0,2) 1\" means : the element in row 0 and column 2 is equal to 1.\n",
|
||||||
"# \"(0,3) 2\" means : the element in row 0 and column 3 is equal to 2. \n",
|
"# \"(0,3) 2\" means : the element in row 0 and column 3 is equal to 2.\n",
|
||||||
"print(v)"
|
"print(v)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -1340,8 +1354,8 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"vec_x_1 = vec.transform(['iphone vert gratuit']).toarray()\n",
|
"vec_x_1 = vec.transform([\"iphone vert gratuit\"]).toarray()\n",
|
||||||
"vec_x_2 = vec.transform(['iphone rouge gratuit']).toarray()\n",
|
"vec_x_2 = vec.transform([\"iphone rouge gratuit\"]).toarray()\n",
|
||||||
"print(vec_x_1)\n",
|
"print(vec_x_1)\n",
|
||||||
"print(vec_x_2)"
|
"print(vec_x_2)"
|
||||||
]
|
]
|
||||||
@@ -1372,8 +1386,8 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"vectorizer = CountVectorizer()\n",
|
"vectorizer = CountVectorizer()\n",
|
||||||
"X = vectorizer.fit_transform(sms['Text'])\n",
|
"X = vectorizer.fit_transform(sms[\"Text\"])\n",
|
||||||
"y = sms['Labelnum']"
|
"y = sms[\"Labelnum\"]"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1400,10 +1414,12 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"from sklearn.model_selection import train_test_split\n",
|
"from sklearn.model_selection import train_test_split\n",
|
||||||
"\n",
|
"\n",
|
||||||
"X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.30,random_state=50)\n",
|
"X_train, X_test, y_train, y_test = train_test_split(\n",
|
||||||
|
" X, y, test_size=0.30, random_state=50\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print (\"size of the training set: \", X_train.shape[0])\n",
|
"print(\"size of the training set: \", X_train.shape[0])\n",
|
||||||
"print (\"size of the test set :\", X_test.shape[0])"
|
"print(\"size of the test set :\", X_test.shape[0])"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1906,7 +1922,7 @@
|
|||||||
"from sklearn.metrics import accuracy_score\n",
|
"from sklearn.metrics import accuracy_score\n",
|
||||||
"\n",
|
"\n",
|
||||||
"y_pred = sms_bayes.predict(X_test)\n",
|
"y_pred = sms_bayes.predict(X_test)\n",
|
||||||
"print (\"The accuracy score on the test set is \", accuracy_score(y_test, y_pred))"
|
"print(\"The accuracy score on the test set is \", accuracy_score(y_test, y_pred))"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1969,10 +1985,17 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"my_sms = vectorizer.transform(['free trial!', 'Iphone 15 is now free', 'I want coffee', 'I want to buy a new iphone'])\n",
|
"my_sms = vectorizer.transform(\n",
|
||||||
|
" [\n",
|
||||||
|
" \"free trial!\",\n",
|
||||||
|
" \"Iphone 15 is now free\",\n",
|
||||||
|
" \"I want coffee\",\n",
|
||||||
|
" \"I want to buy a new iphone\",\n",
|
||||||
|
" ]\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"pred_my_sms = sms_bayes.predict(my_sms)\n",
|
"pred_my_sms = sms_bayes.predict(my_sms)\n",
|
||||||
"print (pred_my_sms)"
|
"print(pred_my_sms)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1999,7 +2022,7 @@
|
|||||||
"from sklearn.naive_bayes import BernoulliNB\n",
|
"from sklearn.naive_bayes import BernoulliNB\n",
|
||||||
"\n",
|
"\n",
|
||||||
"# Load the MNIST dataset\n",
|
"# Load the MNIST dataset\n",
|
||||||
"mnist = fetch_openml('mnist_784', version=1, parser='auto')\n",
|
"mnist = fetch_openml(\"mnist_784\", version=1, parser=\"auto\")\n",
|
||||||
"X, y = mnist.data, mnist.target"
|
"X, y = mnist.data, mnist.target"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -2036,7 +2059,9 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"X_copy = (X.copy() >= 127).astype(int)\n",
|
"X_copy = (X.copy() >= 127).astype(int)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"X_train, X_test, y_train, y_test = train_test_split(X_copy, y, test_size=0.25, random_state=42)\n",
|
"X_train, X_test, y_train, y_test = train_test_split(\n",
|
||||||
|
" X_copy, y, test_size=0.25, random_state=42\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"ber_bayes = BernoulliNB()\n",
|
"ber_bayes = BernoulliNB()\n",
|
||||||
"ber_bayes.fit(X_train, y_train)\n",
|
"ber_bayes.fit(X_train, y_train)\n",
|
||||||
@@ -2059,6 +2084,7 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from keras.datasets import cifar10\n",
|
"from keras.datasets import cifar10\n",
|
||||||
|
"\n",
|
||||||
"(x_train, y_train), (x_test, y_test) = cifar10.load_data()"
|
"(x_train, y_train), (x_test, y_test) = cifar10.load_data()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -2077,7 +2103,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"# reminder : the output is an RGB image 32 x 32 \n",
|
"# reminder : the output is an RGB image 32 x 32\n",
|
||||||
"print(x_train.shape)\n",
|
"print(x_train.shape)\n",
|
||||||
"print(y_train.shape)"
|
"print(y_train.shape)"
|
||||||
]
|
]
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -46,23 +46,23 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"np.random.seed(12)\n",
|
"np.random.seed(12)\n",
|
||||||
"num_observations=400\n",
|
"num_observations = 400\n",
|
||||||
"\n",
|
"\n",
|
||||||
"center1=[0,0]\n",
|
"center1 = [0, 0]\n",
|
||||||
"center2=[1,4]\n",
|
"center2 = [1, 4]\n",
|
||||||
"center3=[-3,2]\n",
|
"center3 = [-3, 2]\n",
|
||||||
"\n",
|
"\n",
|
||||||
"x1=np.random.multivariate_normal(center1,[[1,0],[0,1]], num_observations)\n",
|
"x1 = np.random.multivariate_normal(center1, [[1, 0], [0, 1]], num_observations)\n",
|
||||||
"x2=np.random.multivariate_normal(center2,[[1,0],[0,1]], num_observations)\n",
|
"x2 = np.random.multivariate_normal(center2, [[1, 0], [0, 1]], num_observations)\n",
|
||||||
"x3=np.random.multivariate_normal(center3,[[1,0],[0,1]], num_observations)\n",
|
"x3 = np.random.multivariate_normal(center3, [[1, 0], [0, 1]], num_observations)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"X= np.vstack((x1, x2, x3)).astype(np.float32)\n",
|
"X = np.vstack((x1, x2, x3)).astype(np.float32)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(figsize=(8,6))\n",
|
"plt.figure(figsize=(8, 6))\n",
|
||||||
"plt.plot(X[:,0], X[:,1],\".b\",alpha=0.2)\n",
|
"plt.plot(X[:, 0], X[:, 1], \".b\", alpha=0.2)\n",
|
||||||
"plt.plot(center1[0], center1[1], '.', color='red', markersize=10)\n",
|
"plt.plot(center1[0], center1[1], \".\", color=\"red\", markersize=10)\n",
|
||||||
"plt.plot(center2[0], center2[1], '.', color='red', markersize=10)\n",
|
"plt.plot(center2[0], center2[1], \".\", color=\"red\", markersize=10)\n",
|
||||||
"plt.plot(center3[0], center3[1], '.', color='red', markersize=10)\n",
|
"plt.plot(center3[0], center3[1], \".\", color=\"red\", markersize=10)\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -540,10 +540,12 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"plt.figure(figsize=(8,6))\n",
|
"plt.figure(figsize=(8, 6))\n",
|
||||||
"plt.plot(X[:,0], X[:,1],\".b\",alpha=0.2)\n",
|
"plt.plot(X[:, 0], X[:, 1], \".b\", alpha=0.2)\n",
|
||||||
"for center in kmeans1.cluster_centers_:\n",
|
"for center in kmeans1.cluster_centers_:\n",
|
||||||
" plt.plot(center[0], center[1], '.', color='red', markersize=10, label='Cluster center')\n",
|
" plt.plot(\n",
|
||||||
|
" center[0], center[1], \".\", color=\"red\", markersize=10, label=\"Cluster center\"\n",
|
||||||
|
" )\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
@@ -585,11 +587,11 @@
|
|||||||
"# Hint: An example for plotting the Voronoi partition\n",
|
"# Hint: An example for plotting the Voronoi partition\n",
|
||||||
"from scipy.spatial import Voronoi, voronoi_plot_2d\n",
|
"from scipy.spatial import Voronoi, voronoi_plot_2d\n",
|
||||||
"\n",
|
"\n",
|
||||||
"points_generer_voronoi = np.array([[0,0],[1,4],[-3,2]])\n",
|
"points_generer_voronoi = np.array([[0, 0], [1, 4], [-3, 2]])\n",
|
||||||
"\n",
|
"\n",
|
||||||
"vor = Voronoi(points_generer_voronoi)\n",
|
"vor = Voronoi(points_generer_voronoi)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"fig, ax = plt.subplots(1,1,figsize=(4,4)) \n",
|
"fig, ax = plt.subplots(1, 1, figsize=(4, 4))\n",
|
||||||
"\n",
|
"\n",
|
||||||
"fig = voronoi_plot_2d(vor, ax=ax, show_vertices=False)"
|
"fig = voronoi_plot_2d(vor, ax=ax, show_vertices=False)"
|
||||||
]
|
]
|
||||||
@@ -614,14 +616,16 @@
|
|||||||
"# Answer for Exercise 3\n",
|
"# Answer for Exercise 3\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"fig, ax = plt.subplots(1,1,figsize=(8,6)) \n",
|
"fig, ax = plt.subplots(1, 1, figsize=(8, 6))\n",
|
||||||
"plt.plot(X[:,0], X[:,1], \".b\", alpha=0.2)\n",
|
"plt.plot(X[:, 0], X[:, 1], \".b\", alpha=0.2)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"vor = Voronoi(kmeans1.cluster_centers_)\n",
|
"vor = Voronoi(kmeans1.cluster_centers_)\n",
|
||||||
"fig = voronoi_plot_2d(vor, ax=ax, show_vertices=False)\n",
|
"fig = voronoi_plot_2d(vor, ax=ax, show_vertices=False)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for center in kmeans1.cluster_centers_:\n",
|
"for center in kmeans1.cluster_centers_:\n",
|
||||||
" plt.plot(center[0], center[1], '.', color='red', markersize=10, label='Cluster center')\n",
|
" plt.plot(\n",
|
||||||
|
" center[0], center[1], \".\", color=\"red\", markersize=10, label=\"Cluster center\"\n",
|
||||||
|
" )\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.show()"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
@@ -1233,10 +1237,10 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"print (\"1:\", compress_model.labels_)\n",
|
"print(\"1:\", compress_model.labels_)\n",
|
||||||
"print (\"2:\", compress_model.labels_.shape)\n",
|
"print(\"2:\", compress_model.labels_.shape)\n",
|
||||||
"print (\"3:\", compress_model.cluster_centers_)\n",
|
"print(\"3:\", compress_model.cluster_centers_)\n",
|
||||||
"print (\"4:\", compress_model.cluster_centers_.shape)"
|
"print(\"4:\", compress_model.cluster_centers_.shape)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1275,13 +1279,13 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"color_new=np.zeros_like(colors)\n",
|
"color_new = np.zeros_like(colors)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"labels=compress_model.labels_\n",
|
"labels = compress_model.labels_\n",
|
||||||
"centers=compress_model.cluster_centers_\n",
|
"centers = compress_model.cluster_centers_\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for i in range(len(colors)):\n",
|
"for i in range(len(colors)):\n",
|
||||||
" color_new[i]= centers[labels[i]]"
|
" color_new[i] = centers[labels[i]]"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1336,11 +1340,12 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"import matplotlib.image as mpimg\n",
|
"import matplotlib.image as mpimg\n",
|
||||||
|
"\n",
|
||||||
"mpimg.imsave(\"assets/zelda_new.png\", zelda_new)\n",
|
"mpimg.imsave(\"assets/zelda_new.png\", zelda_new)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(figsize=(8, 6))\n",
|
"plt.figure(figsize=(8, 6))\n",
|
||||||
"plt.imshow(zelda_new)\n",
|
"plt.imshow(zelda_new)\n",
|
||||||
"plt.show()\n"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1363,13 +1368,13 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"import os\n",
|
"import os\n",
|
||||||
"\n",
|
"\n",
|
||||||
"size_new=os.path.getsize('assets/zelda_new.png')\n",
|
"size_new = os.path.getsize(\"assets/zelda_new.png\")\n",
|
||||||
"size_old=os.path.getsize('assets/zelda.png')\n",
|
"size_old = os.path.getsize(\"assets/zelda.png\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print (\"The original size is \", size_old, \"bytes.\")\n",
|
"print(\"The original size is \", size_old, \"bytes.\")\n",
|
||||||
"print (\"The compressed size is \", size_new, \"bytes.\")\n",
|
"print(\"The compressed size is \", size_new, \"bytes.\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"print (f\"The compression factor is {size_old/size_new : .3f}\")"
|
"print(f\"The compression factor is {size_old / size_new: .3f}\")"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1407,8 +1412,8 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"partiel=plt.imread(\"assets/partiel.png\")\n",
|
"partiel = plt.imread(\"assets/partiel.png\")\n",
|
||||||
"plt.figure(figsize = (20,10))\n",
|
"plt.figure(figsize=(20, 10))\n",
|
||||||
"plt.imshow(partiel)"
|
"plt.imshow(partiel)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -1426,7 +1431,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"print (partiel.shape)"
|
"print(partiel.shape)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1472,23 +1477,23 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"partiel_new=np.zeros_like(partiel)\n",
|
"partiel_new = np.zeros_like(partiel)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"noir_rgb=np.array([0,0,0])\n",
|
"noir_rgb = np.array([0, 0, 0])\n",
|
||||||
"blanc_rgb=np.array([1,1,1])\n",
|
"blanc_rgb = np.array([1, 1, 1])\n",
|
||||||
|
"\n",
|
||||||
|
"epsilon = 0.5 # threshold\n",
|
||||||
"\n",
|
"\n",
|
||||||
"epsilon=0.5 # threshold\n",
|
|
||||||
" \n",
|
|
||||||
"distances = np.linalg.norm(partiel - noir_rgb, axis=2)\n",
|
"distances = np.linalg.norm(partiel - noir_rgb, axis=2)\n",
|
||||||
"partiel_new = np.zeros_like(partiel)\n",
|
"partiel_new = np.zeros_like(partiel)\n",
|
||||||
"partiel_new[distances <= epsilon] = noir_rgb\n",
|
"partiel_new[distances <= epsilon] = noir_rgb\n",
|
||||||
"partiel_new[distances > epsilon] = blanc_rgb\n",
|
"partiel_new[distances > epsilon] = blanc_rgb\n",
|
||||||
" \n",
|
"\n",
|
||||||
"mpimg.imsave(\"assets/partiel_new.png\", partiel_new)\n",
|
"mpimg.imsave(\"assets/partiel_new.png\", partiel_new)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"plt.figure(figsize=(20,10))\n",
|
"plt.figure(figsize=(20, 10))\n",
|
||||||
"plt.imshow(partiel_new)\n",
|
"plt.imshow(partiel_new)\n",
|
||||||
"plt.show()\n"
|
"plt.show()"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -1531,16 +1536,20 @@
|
|||||||
"mnist = tf.keras.datasets.mnist\n",
|
"mnist = tf.keras.datasets.mnist\n",
|
||||||
"(X_train, y_train), (X_test, y_test) = mnist.load_data()\n",
|
"(X_train, y_train), (X_test, y_test) = mnist.load_data()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"X_train = X_train.reshape(-1, 28*28)\n",
|
"X_train = X_train.reshape(-1, 28 * 28)\n",
|
||||||
"\n",
|
"\n",
|
||||||
"kmeans2 = KMeans(n_clusters=10)\n",
|
"kmeans2 = KMeans(n_clusters=10)\n",
|
||||||
"clusters = kmeans2.fit_predict(X_train)\n",
|
"clusters = kmeans2.fit_predict(X_train)\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"\n",
|
||||||
"def map_clusters_to_labels(clusters, true_labels):\n",
|
"def map_clusters_to_labels(clusters, true_labels):\n",
|
||||||
" return np.array([mode(true_labels[clusters == i], keepdims=True).mode[0] for i in range(10)])\n",
|
" return np.array(\n",
|
||||||
|
" [mode(true_labels[clusters == i], keepdims=True).mode[0] for i in range(10)]\n",
|
||||||
|
" )\n",
|
||||||
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"cluster_to_label = map_clusters_to_labels(clusters, y_train)\n",
|
"cluster_to_label = map_clusters_to_labels(clusters, y_train)\n",
|
||||||
"print(\"Cluster to label mapping:\", cluster_to_label)\n"
|
"print(\"Cluster to label mapping:\", cluster_to_label)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"import numpy as np \n",
|
"import numpy as np\n",
|
||||||
"import pandas as pd\n",
|
"import pandas as pd\n",
|
||||||
"import tensorflow as tf\n",
|
"import tensorflow as tf\n",
|
||||||
"import matplotlib.pyplot as plt"
|
"import matplotlib.pyplot as plt"
|
||||||
@@ -178,16 +178,21 @@
|
|||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"def build_model():\n",
|
"def build_model():\n",
|
||||||
" model = tf.keras.models.Sequential([\n",
|
" model = tf.keras.models.Sequential(\n",
|
||||||
" tf.keras.layers.Dense(16, activation='relu', input_shape=(X.shape[1],), kernel_regularizer=tf.keras.regularizers.l2(0.01)),\n",
|
" [\n",
|
||||||
" tf.keras.layers.Dense(8, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01)),\n",
|
" tf.keras.layers.Dense(\n",
|
||||||
" tf.keras.layers.Dense(1, activation='sigmoid')\n",
|
" 16,\n",
|
||||||
" ])\n",
|
" activation=\"relu\",\n",
|
||||||
" model.compile(\n",
|
" input_shape=(X.shape[1],),\n",
|
||||||
" optimizer='adam',\n",
|
" kernel_regularizer=tf.keras.regularizers.l2(0.01),\n",
|
||||||
" loss='binary_crossentropy',\n",
|
" ),\n",
|
||||||
" metrics=['accuracy']\n",
|
" tf.keras.layers.Dense(\n",
|
||||||
|
" 8, activation=\"relu\", kernel_regularizer=tf.keras.regularizers.l2(0.01)\n",
|
||||||
|
" ),\n",
|
||||||
|
" tf.keras.layers.Dense(1, activation=\"sigmoid\"),\n",
|
||||||
|
" ]\n",
|
||||||
" )\n",
|
" )\n",
|
||||||
|
" model.compile(optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\n",
|
||||||
" return model"
|
" return model"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -291,10 +296,7 @@
|
|||||||
"histories = []\n",
|
"histories = []\n",
|
||||||
"\n",
|
"\n",
|
||||||
"early_stopping = EarlyStopping(\n",
|
"early_stopping = EarlyStopping(\n",
|
||||||
" monitor='val_loss',\n",
|
" monitor=\"val_loss\", patience=10, restore_best_weights=True, verbose=1\n",
|
||||||
" patience=10,\n",
|
|
||||||
" restore_best_weights=True,\n",
|
|
||||||
" verbose=1\n",
|
|
||||||
")\n",
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for fold, (train_idx, val_idx) in enumerate(skf.split(X, y), 1):\n",
|
"for fold, (train_idx, val_idx) in enumerate(skf.split(X, y), 1):\n",
|
||||||
@@ -305,29 +307,28 @@
|
|||||||
" scaler = StandardScaler()\n",
|
" scaler = StandardScaler()\n",
|
||||||
" X_train_scaled = scaler.fit_transform(X_train)\n",
|
" X_train_scaled = scaler.fit_transform(X_train)\n",
|
||||||
" X_val_scaled = scaler.transform(X_val)\n",
|
" X_val_scaled = scaler.transform(X_val)\n",
|
||||||
" \n",
|
"\n",
|
||||||
" model = build_model()\n",
|
" model = build_model()\n",
|
||||||
"\n",
|
"\n",
|
||||||
" model.compile(\n",
|
" model.compile(optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"f1_score\"])\n",
|
||||||
" optimizer='adam',\n",
|
|
||||||
" loss='binary_crossentropy',\n",
|
|
||||||
" metrics=[\"f1_score\"]\n",
|
|
||||||
" )\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
" # EarlyStopping\n",
|
" # EarlyStopping\n",
|
||||||
" callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)\n",
|
" callback = tf.keras.callbacks.EarlyStopping(\n",
|
||||||
|
" monitor=\"val_loss\", patience=10, restore_best_weights=True\n",
|
||||||
|
" )\n",
|
||||||
"\n",
|
"\n",
|
||||||
" # Entraînement\n",
|
" # Entraînement\n",
|
||||||
" history = model.fit(\n",
|
" history = model.fit(\n",
|
||||||
" X_train_scaled, y_train,\n",
|
" X_train_scaled,\n",
|
||||||
|
" y_train,\n",
|
||||||
" epochs=50,\n",
|
" epochs=50,\n",
|
||||||
" batch_size=8,\n",
|
" batch_size=8,\n",
|
||||||
" validation_data=(X_val_scaled, y_val),\n",
|
" validation_data=(X_val_scaled, y_val),\n",
|
||||||
" callbacks=[callback],\n",
|
" callbacks=[callback],\n",
|
||||||
" verbose=0,\n",
|
" verbose=0,\n",
|
||||||
" class_weight={0: 1.0, 1: 2.0}\n",
|
" class_weight={0: 1.0, 1: 2.0},\n",
|
||||||
" )\n",
|
" )\n",
|
||||||
" \n",
|
"\n",
|
||||||
" histories.append(history.history)\n",
|
" histories.append(history.history)\n",
|
||||||
"\n",
|
"\n",
|
||||||
" # Prédiction & F1\n",
|
" # Prédiction & F1\n",
|
||||||
@@ -360,9 +361,9 @@
|
|||||||
"axes = axes.flatten() # Flatten to easily iterate\n",
|
"axes = axes.flatten() # Flatten to easily iterate\n",
|
||||||
"\n",
|
"\n",
|
||||||
"for i, (hist, ax) in enumerate(zip(histories, axes)):\n",
|
"for i, (hist, ax) in enumerate(zip(histories, axes)):\n",
|
||||||
" ax.plot(hist['loss'], label='Train loss', alpha=0.6)\n",
|
" ax.plot(hist[\"loss\"], label=\"Train loss\", alpha=0.6)\n",
|
||||||
" ax.plot(hist['val_loss'], label='Val loss', linestyle='--', alpha=0.6)\n",
|
" ax.plot(hist[\"val_loss\"], label=\"Val loss\", linestyle=\"--\", alpha=0.6)\n",
|
||||||
" ax.set_title(f\"Fold {i+1}\")\n",
|
" ax.set_title(f\"Fold {i + 1}\")\n",
|
||||||
" ax.set_xlabel(\"Epochs\")\n",
|
" ax.set_xlabel(\"Epochs\")\n",
|
||||||
" if i % 2 == 0:\n",
|
" if i % 2 == 0:\n",
|
||||||
" ax.set_ylabel(\"Binary Crossentropy\")\n",
|
" ax.set_ylabel(\"Binary Crossentropy\")\n",
|
||||||
@@ -436,7 +437,9 @@
|
|||||||
"import tensorflow as tf\n",
|
"import tensorflow as tf\n",
|
||||||
"import numpy as np\n",
|
"import numpy as np\n",
|
||||||
"\n",
|
"\n",
|
||||||
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n",
|
"X_train, X_test, y_train, y_test = train_test_split(\n",
|
||||||
|
" X, y, test_size=0.2, random_state=42, stratify=y\n",
|
||||||
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"scaler = StandardScaler()\n",
|
"scaler = StandardScaler()\n",
|
||||||
"X_train_scaled = scaler.fit_transform(X_train)\n",
|
"X_train_scaled = scaler.fit_transform(X_train)\n",
|
||||||
@@ -444,21 +447,21 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"model = build_model()\n",
|
"model = build_model()\n",
|
||||||
"\n",
|
"\n",
|
||||||
"model.compile(\n",
|
"model.compile(optimizer=\"adam\", loss=\"binary_crossentropy\")\n",
|
||||||
" optimizer='adam',\n",
|
"\n",
|
||||||
" loss='binary_crossentropy'\n",
|
"callback = tf.keras.callbacks.EarlyStopping(\n",
|
||||||
|
" monitor=\"val_loss\", patience=10, restore_best_weights=True\n",
|
||||||
")\n",
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)\n",
|
|
||||||
"\n",
|
|
||||||
"history = model.fit(\n",
|
"history = model.fit(\n",
|
||||||
" X_train_scaled, y_train,\n",
|
" X_train_scaled,\n",
|
||||||
|
" y_train,\n",
|
||||||
" epochs=50,\n",
|
" epochs=50,\n",
|
||||||
" batch_size=8,\n",
|
" batch_size=8,\n",
|
||||||
" validation_split=0.2,\n",
|
" validation_split=0.2,\n",
|
||||||
" callbacks=[callback],\n",
|
" callbacks=[callback],\n",
|
||||||
" verbose=0,\n",
|
" verbose=0,\n",
|
||||||
" class_weight={0: 1.0, 1: 2.0}\n",
|
" class_weight={0: 1.0, 1: 2.0},\n",
|
||||||
")\n",
|
")\n",
|
||||||
"\n",
|
"\n",
|
||||||
"\n",
|
"\n",
|
||||||
@@ -486,11 +489,11 @@
|
|||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"plt.figure(figsize=(8, 5))\n",
|
"plt.figure(figsize=(8, 5))\n",
|
||||||
"plt.plot(history.history['loss'], label='Loss (train)')\n",
|
"plt.plot(history.history[\"loss\"], label=\"Loss (train)\")\n",
|
||||||
"plt.plot(history.history['val_loss'], label='Loss (val)', linestyle='--')\n",
|
"plt.plot(history.history[\"val_loss\"], label=\"Loss (val)\", linestyle=\"--\")\n",
|
||||||
"plt.xlabel('Epochs')\n",
|
"plt.xlabel(\"Epochs\")\n",
|
||||||
"plt.ylabel('Binary Cross-Entropy Loss')\n",
|
"plt.ylabel(\"Binary Cross-Entropy Loss\")\n",
|
||||||
"plt.title('Courbe d\\'apprentissage')\n",
|
"plt.title(\"Courbe d'apprentissage\")\n",
|
||||||
"plt.legend()\n",
|
"plt.legend()\n",
|
||||||
"plt.grid(True)\n",
|
"plt.grid(True)\n",
|
||||||
"plt.tight_layout()\n",
|
"plt.tight_layout()\n",
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ dependencies = [
|
|||||||
"opencv-python>=4.11.0.86",
|
"opencv-python>=4.11.0.86",
|
||||||
"pandas>=2.2.3",
|
"pandas>=2.2.3",
|
||||||
"scikit-learn>=1.6.1",
|
"scikit-learn>=1.6.1",
|
||||||
"tensorflow==2.19.0",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[dependency-groups]
|
[dependency-groups]
|
||||||
@@ -19,3 +18,55 @@ dev = [
|
|||||||
"ipykernel>=6.29.5",
|
"ipykernel>=6.29.5",
|
||||||
"uv>=0.6.16",
|
"uv>=0.6.16",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
# Activer les règles de linting courantes
|
||||||
|
select = [
|
||||||
|
"E", # pycodestyle errors
|
||||||
|
"W", # pycodestyle warnings
|
||||||
|
"F", # Pyflakes
|
||||||
|
"I", # isort
|
||||||
|
"B", # flake8-bugbear
|
||||||
|
"C4", # flake8-comprehensions
|
||||||
|
"UP", # pyupgrade
|
||||||
|
]
|
||||||
|
|
||||||
|
# Désactiver certaines règles
|
||||||
|
ignore = [
|
||||||
|
"E501", # line too long, géré par le formatter
|
||||||
|
]
|
||||||
|
|
||||||
|
# Longueur de ligne
|
||||||
|
line-length = 88
|
||||||
|
|
||||||
|
# Exclure certains fichiers ou répertoires
|
||||||
|
exclude = [
|
||||||
|
".bzr",
|
||||||
|
".direnv",
|
||||||
|
".eggs",
|
||||||
|
".git",
|
||||||
|
".hg",
|
||||||
|
".mypy_cache",
|
||||||
|
".nox",
|
||||||
|
".pants.d",
|
||||||
|
".pytype",
|
||||||
|
".ruff_cache",
|
||||||
|
".svn",
|
||||||
|
".tox",
|
||||||
|
".venv",
|
||||||
|
"__pypackages__",
|
||||||
|
"_build",
|
||||||
|
"buck-out",
|
||||||
|
"build",
|
||||||
|
"dist",
|
||||||
|
"node_modules",
|
||||||
|
"venv",
|
||||||
|
]
|
||||||
|
|
||||||
|
# Permettre à Ruff de corriger automatiquement certaines erreurs
|
||||||
|
fixable = ["ALL"]
|
||||||
|
unfixable = []
|
||||||
|
|
||||||
|
# Formatage des imports
|
||||||
|
[isort]
|
||||||
|
known-third-party = ["pydantic", "django"]
|
||||||
|
|||||||
Reference in New Issue
Block a user