teaching:progappchim:numpy_simple

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentes Révision précédente
Prochaine révision
Révision précédente
Prochaine révisionLes deux révisions suivantes
teaching:progappchim:numpy_simple [2014/02/10 14:35] – [Manipulation de polynômes] villersdteaching:progappchim:numpy_simple [2018/10/31 09:17] – [Références] villersd
Ligne 9: Ligne 9:
 ===== Tableaux numériques ===== ===== Tableaux numériques =====
 On convertit facilement des listes Python en tableau numpy. Essayez ceci : On convertit facilement des listes Python en tableau numpy. Essayez ceci :
-<sxh python;>+<code python>
 import numpy as np import numpy as np
-a=np.array([[1,2],[3,4]]) +a = np.array([[1,2],[3,4]]) 
-print a +print(a) 
-print a.dtype +print(a.dtype) 
-</sxh>+</code>
 Sortie : Sortie :
 <code> <code>
Ligne 27: Ligne 27:
 Vous pouvez consulter [[http://wiki.scipy.org/Numpy_Example_List|cette page]] pour consulter d'autres fonctionnalités, ou [[http://wiki.scipy.org/Numpy_Example_List_With_Doc|celle-ci]], plus documentée. Vous pouvez consulter [[http://wiki.scipy.org/Numpy_Example_List|cette page]] pour consulter d'autres fonctionnalités, ou [[http://wiki.scipy.org/Numpy_Example_List_With_Doc|celle-ci]], plus documentée.
 </note> </note>
-<sxh python; title : arrays_01.py>+<code python arrays_01.py>
 #! /usr/bin/env python #! /usr/bin/env python
 # -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
Ligne 35: Ligne 35:
 import numpy as np import numpy as np
  
-a=np.array(((1,2),(3,4)))   # on peut créer un "array" à partir d'un tuple+a = np.array(((1,2),(3,4)))   # on peut créer un "array" à partir d'un tuple
 # afficher a, le nombre de dimensions, les dimensions, le type de donnée # afficher a, le nombre de dimensions, les dimensions, le type de donnée
-print a, a.ndim, a.shape, a.dtype+print(a, a.ndim, a.shape, a.dtype)
 # avec des "floats" : # avec des "floats" :
-b= np.array( +b = np.array([ 
-    [[1.1, 2.2, 3.3, 4.4],+    [1.1, 2.2, 3.3, 4.4],
     [5.5, 6.6, 7.7, 8.8],     [5.5, 6.6, 7.7, 8.8],
-    [9.9, 0.2, 1.3, 2.4]]) +    [9.9, 0.2, 1.3, 2.4]
-print b, b.ndim, b.shape, b.dtype+    ]) 
 +print(b, b.ndim, b.shape, b.dtype)
 # un tableau de zéros # un tableau de zéros
-c=np.zeros((4,2)) +c = np.zeros((4,2)) 
-print c, c.ndim, c.shape, c.dtype+print(c, c.ndim, c.shape, c.dtype)
 # un tableau tridimensionnel de 1 "complexe" # un tableau tridimensionnel de 1 "complexe"
-d=np.ones((2,3,4),dtype=complex) +d = np.ones((2,3,4),dtype=complex) 
-print d, d.ndim, d.shape, d.dtype+print(d, d.ndim, d.shape, d.dtype)
 # un tableau avec arange, et ensuite reshape # un tableau avec arange, et ensuite reshape
-e1= np.arange(1,36,1) +e1 = np.arange(1,36,1) 
-e=np.reshape(e1,(5,7)) +e = np.reshape(e1,(5,7)) 
-print e, e.ndim, e.shape, e.dtype +print(e, e.ndim, e.shape, e.dtype) 
-f=np.random.rand(3,3) +f = np.random.rand(3,3) 
-print f, f.ndim, f.shape, f.dtype+print(f, f.ndim, f.shape, f.dtype)
 # utilisation de linspace pour imposer le nombre d'éléments générés : # utilisation de linspace pour imposer le nombre d'éléments générés :
-g=np.linspace(0.,np.pi,11) +g = np.linspace(0.,np.pi,11) 
-print g, g.ndim, g.shape, g.dtype +print(g, g.ndim, g.shape, g.dtype) 
-</sxh>+</code>
  
 Quelques manipulations élémentaires : Quelques manipulations élémentaires :
-<sxh python; title : arrays_02.py>+<code python arrays_02.py>
 #! /usr/bin/env python #! /usr/bin/env python
 # -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
Ligne 70: Ligne 71:
 import numpy as np import numpy as np
  
-a=np.array([[1,2],[3,4]]) +a = np.array([[1,2],[3,4]]) 
-b=np.array([[1,1],[1,1]]) +b = np.array([[1,1],[1,1]]) 
-c=a+b # addition terme à terme +c = a + b # addition terme à terme 
-print c, c.ndim, c.shape, c.dtype +print(c, c.ndim, c.shape, c.dtype) 
-d=a*b # multiplication terme à terme +d =a * b # multiplication terme à terme 
-print d, d.ndim, d.shape, d.dtype +print(d, d.ndim, d.shape, d.dtype) 
-e=np.dot(a,b) # multiplication matricielle +e = np.dot(a,b) # multiplication matricielle 
-print e, e.ndim, e.shape, e.dtype +print(e, e.ndim, e.shape, e.dtype) 
-f=np.sin(np.pi*0.5*a) # fonction mathématique et adaptation automatique du type +f = np.sin(np.pi*0.5*a) # fonction mathématique et adaptation automatique du type 
-print f, f.ndim, f.shape, f.dtype +print(f, f.ndim, f.shape, f.dtype) 
-g=np.transpose(a) # transposition +g = np.transpose(a) # transposition 
-print g, g.ndim, g.shape, g.dtype +print(g, g.ndim, g.shape, g.dtype) 
-print np.sum(a),np.min(a), np.max(a)  # somme des éléments, minimum, maximum +print(np.sum(a),np.min(a), np.max(a))  # somme des éléments, minimum, maximum 
-</sxh>+</code>
  
 ==== Fonctions mathématiques principales : ==== ==== Fonctions mathématiques principales : ====
Ligne 93: Ligne 94:
  
 ==== Autres fonctions ==== ==== Autres fonctions ====
-  * min et max rendent le minimum et le maximum, argmin et argmax rendent les indices de ce éléments dans un tableau 1D (consulter la documentation pour les dimensions supérieures. +  * //min// et //max// rendent le minimum et le maximum, argmin et argmax rendent les indices de ce éléments dans un tableau 1D (consulter la [[http://docs.scipy.org/doc/numpy/reference/routines.ma.html#minimum-maximum|documentation]] pour les dimensions supérieures)
-  * sorted : tri +  * //sorted// : tri 
-  * clip : cliping permettant d'éliminer des valeurs inférieures à une borne minimale donnée ou supérieures à une borne maximale +  * //clip// : cliping permettant d'éliminer des valeurs inférieures à une borne minimale donnée ou supérieures à une borne maximale 
-  * unique : élimine les "doublons"+  * //unique// : élimine les "doublons"
   * fonctions booléennes, pour des conditions, ou pour filtrer suivant des conditions (voir la documentation)   * fonctions booléennes, pour des conditions, ou pour filtrer suivant des conditions (voir la documentation)
 +  * //[[http://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html|copy]]// : copie d'un tableau (pour éviter les modifications lors d'utilisation directe ou par référence) 
 +  * //.tolist()// : convertit un tableau numpy en liste standard de python
  
 ===== Algèbre linéaire ===== ===== Algèbre linéaire =====
-<sxh python; title : simple_linear_system.py>+<code python simple_linear_system.py>
 #! /usr/bin/env python #! /usr/bin/env python
 # -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
 """ """
 Solve a system of simultaneous equation in two variables of the form Solve a system of simultaneous equation in two variables of the form
-    2*x + 7*y=17. +    2 * x + 7 * y = 17. 
-    3*x - 5*y=-21.+    3 * x - 5 * y = -21.
  
 reference : http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html reference : http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html
Ligne 116: Ligne 118:
 a = np.array([[2.,7.],[3.,-5.]])  # coefs matrice   a = np.array([[2.,7.],[3.,-5.]])  # coefs matrice  
 b = np.array([[17.],[-21.]])   # independent coef vector b = np.array([[17.],[-21.]])   # independent coef vector
-print np.linalg.solve(a,b)  # solution +print(np.linalg.solve(a,b))  # solution 
-</sxh>+</code>
  
 Quelques possibilités supplémentaires : Quelques possibilités supplémentaires :
-<sxh python; title : arrays_linalg_03.py>+<code python arrays_linalg_03.py>
 #! /usr/bin/env python #! /usr/bin/env python
 # -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
Ligne 128: Ligne 130:
 import numpy as np import numpy as np
  
-a=np.array([[1,2],[3,4]]) +a = np.array([[1,2],[3,4]]) 
-print a, a.ndim, a.shape, a.dtype +print(a, a.ndim, a.shape, a.dtype) 
-b=np.linalg.inv(a)  # matrice inverse +b = np.linalg.inv(a)  # matrice inverse 
-print b, b.ndim, b.shape, b.dtype+print(b, b.ndim, b.shape, b.dtype)
 unit = np.eye(2)  # matrice unitaire unit = np.eye(2)  # matrice unitaire
-print unit, unit.ndim, unit.shape, unit.dtype+print(unit, unit.ndim, unit.shape, unit.dtype)
 v = np.array([[10.], [14.]])  # vecteur colonne v = np.array([[10.], [14.]])  # vecteur colonne
-x1=np.dot(b,v)  # multiplication de l'inverse de a par v +x1 = np.dot(b,v)  # multiplication de l'inverse de a par v 
-x2=np.linalg.solve(a,v) # solution du système linéaire de coefficients+x2 = np.linalg.solve(a,v) # solution du système linéaire de coefficients
 # des inconnues a et de coefficients indépendants b # des inconnues a et de coefficients indépendants b
 # les deux techniques donnent évidemment le même résultat ! # les deux techniques donnent évidemment le même résultat !
-print x1, x1.ndim, x1.shape, x1.dtype +print(x1, x1.ndim, x1.shape, x1.dtype) 
-print x2, x2.ndim, x2.shape, x2.dtype+print(x2, x2.ndim, x2.shape, x2.dtype)
 # valeurs propres et vecteurs propres de matrices : # valeurs propres et vecteurs propres de matrices :
-d=np.array([[1,1],[-1,1]]) +d = np.array([[1,1],[-1,1]]) 
-print np.linalg.eig(d) +print(np.linalg.eig(d)
-</sxh>+</code>
  
 Numpy dispose aussi d'une classe particulière de "arrays" pour des matrices. Numpy dispose aussi d'une classe particulière de "arrays" pour des matrices.
Ligne 154: Ligne 156:
  
 ===== Statistiques élémentaires ===== ===== Statistiques élémentaires =====
-<sxh python; title : arrays_stats_elem_04.py>+<code python arrays_stats_elem_04.py>
 #! /usr/bin/env python #! /usr/bin/env python
 # -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
Ligne 162: Ligne 164:
 import numpy as np import numpy as np
  
-a=np.array([1.,2.,3.5,5.,6.,7.,7.4,7.8,8.2,8.4,8.5,9.,10.2,12.5]) +a = np.array([1.,2.,3.5,5.,6.,7.,7.4,7.8,8.2,8.4,8.5,9.,10.2,12.5]) 
-print a, a.ndim, a.shape, a.dtype +print(a, a.ndim, a.shape, a.dtype) 
-print "médiane = ",np.median(a) +print("médiane = ",np.median(a)
-print "moyenne = ",np.mean(a) +print("moyenne = ",np.mean(a)
-print "variance = ",np.var(a) +print("variance = ",np.var(a)
-print "Écart-type = ",np.std(a) +print("Écart-type = ",np.std(a)
-</sxh>+</code>
  
 +==== Références complémentaires ====
 +  * [[http://www.pybloggers.com/2017/03/how-to-do-descriptives-statistics-in-python-using-numpy/|How to do Descriptives Statistics in Python using Numpy]]
 ===== Itérations sur les tableaux ===== ===== Itérations sur les tableaux =====
-<sxh python; title : arrays_iteration_05.py>+<code python arrays_iteration_05.py>
 #! /usr/bin/env python #! /usr/bin/env python
 # -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
Ligne 179: Ligne 183:
 import numpy as np import numpy as np
  
-a=np.array([1.,2.,3.5,5.,6.,7.,7.4,7.8,8.2,8.4,8.5,9.,10.2,12.5])+a = np.array([1.,2.,3.5,5.,6.,7.,7.4,7.8,8.2,8.4,8.5,9.,10.2,12.5])
 for x in a: for x in a:
-    print x+    print(x)
 # l'itération sur un tableau multdimensionnel se fait sur un premier niveau de sous-listes # l'itération sur un tableau multdimensionnel se fait sur un premier niveau de sous-listes
-b= np.array( +b = np.array([ 
-    [[1.1, 2.2, 3.3, 4.4],+    [1.1, 2.2, 3.3, 4.4],
     [5.5, 6.6, 7.7, 8.8],     [5.5, 6.6, 7.7, 8.8],
-    [9.9, 0.2, 1.3, 2.4]])+    [9.9, 0.2, 1.3, 2.4]
 +    ])
 for x in b: for x in b:
-    print x+    print(x)
     for y in x:     for y in x:
-        print y,", ",+        print(y,", ",)
     print     print
-</sxh>+</code>
  
 ===== Manipulation de polynômes ===== ===== Manipulation de polynômes =====
-<note warning>Une nouvelle bibliothèque [[http://docs.scipy.org/doc/numpy-1.8.0/reference/routines.polynomials.package.html|polynomial]] devrait remplacer l'ancien "poly1d"</note>+<note warning>Une nouvelle bibliothèque [[http://docs.scipy.org/doc/numpy/reference/routines.polynomials.package.html|polynomial]] devrait remplacer l'ancien "poly1d" 
 + 
 +**poly1d & polynomial ordonnent les coefficients en sens inverses !!!**</note>
 <sxh python; title : arrays_polynomes_06.py> <sxh python; title : arrays_polynomes_06.py>
 #! /usr/bin/env python #! /usr/bin/env python
Ligne 204: Ligne 211:
 import numpy as np import numpy as np
  
-# les coefficients du polynômes sont donnés par ordre décroissance des dégrés+# les coefficients du polynômes sont donnés par ordre décroissance des degrés dans poly1d
 a=np.poly1d([1.,2.,3.,4.]) # = x³ + 2x² + 3x +4 a=np.poly1d([1.,2.,3.,4.]) # = x³ + 2x² + 3x +4
  
Ligne 236: Ligne 243:
 </sxh> </sxh>
  
-Autres fonctions : voir [[http://docs.scipy.org/doc/numpy-1.8.0/reference/routines.polynomials.html|ici]]+Autres fonctions : voir [[http://docs.scipy.org/doc/numpy/reference/routines.polynomials.html|ici]]
  
 L'ordre des coefficients peut facilement être inversé par un slice avec les paramètres [::-1] L'ordre des coefficients peut facilement être inversé par un slice avec les paramètres [::-1]
  
 ===== Transformées de Fourier ===== ===== Transformées de Fourier =====
-À compléter ...+Le module de [[http://docs.scipy.org/doc/numpy/reference/routines.fft.html|transformée de Fourier discrète]] de numpy comprend de nombreuses variantes, et les transformées peuvent aussi être effectuées via le [[http://docs.scipy.org/doc/scipy/reference/fftpack.html|module équivalent fftpack de Scipy]]. 
 + 
 +<code python fonctions-FT-04.py> 
 +#!/usr/bin/env python 
 +#-*- coding: utf-8 -*- 
 +# graphes de fonctions et des transformées de Fourier, utilisant numpy 
 +# et matplotlib pour les graphes 
 + 
 +import numpy as np    # directive d'importation standard de numpy 
 +from numpy import fft   # importation spécifique du module fft de numpy 
 +import matplotlib.pyplot as plt 
 +#from scipy import fftpack  # directive d'importation standard du module équivalent de scipy 
 +# https://docs.scipy.org/doc/scipy-0.15.1/reference/api.html#guidelines-for-importing-functions-from-scipy 
 +#from pylab import *  # directive d'importation alternative en mode "pylab" --> supprimer les plt., fft., 
 + 
 +def f1(t): 
 +    f = np.sin(np.pi*2.*t) 
 +    return f 
 + 
 +def f2(t): 
 +    f = np.exp(-t/2.)*np.cos(np.pi*2.*t) 
 +    return f 
 + 
 +def f3(t): 
 +    f = (4./np.pi)*(np.sin(np.pi*2.*t)+np.sin(np.pi*6.*t)/3.+np.sin(np.pi*10.*t)/5.+np.sin(np.pi*14.*t)/7.+np.sin(np.pi*18.*t)/9.) 
 +    return f 
 + 
 +# une TF peut se faire via : 
 +# fft.fft() du fait de la directive from numpy import fft 
 +# , ou np.fft.fft() du fait de import numpy as np 
 +# , ou fftpack.fft(y1) si on utilise le module de scipy 
 +x = np.arange(0.0,10.0,0.025) 
 +y1 = f1(x) 
 +z1 = fft.fft(y1)   
 +w1 = np.abs(z1[:len(z1)//2]) 
 +y2 = f2(x) 
 +z2 = fft.fft(y2) 
 +w2 = np.abs(z2[:len(z2)//2]) 
 +y3 = f3(x) 
 +z3 = fft.fft(y3) 
 +w3 = np.abs(z3[:len(z3)//2]) 
 + 
 +# doc subplot : http://matplotlib.org/api/pyplot_api.html?highlight=subplot#matplotlib.pyplot.subplot 
 +plt.subplot(3,2,1)   # sous-graphes en 3 lignes et 2 colonnes, graphe 1 
 +plt.title('Fonctions'
 +plt.plot(x,y1) 
 +plt.xlabel("t/s"
 +plt.ylabel("A(t)"
 + 
 +plt.subplot(3,2,2)   # sous-graphes en 3 lignes et 2 colonnes, graphe 2 
 +plt.title(u'Transformées de Fourier'
 +plt.plot(w1) 
 +plt.xlabel("f/Hz"
 +plt.ylabel("A(f)"
 + 
 +plt.subplot(3,2,3)   # sous-graphes en 3 lignes et 2 colonnes, graphe 3 
 +plt.plot(x,y2) 
 +plt.xlabel("t/s"
 +plt.ylabel("A(t)"
 + 
 +plt.subplot(3,2,4)   # sous-graphes en 3 lignes et 2 colonnes, graphe 4 
 +plt.plot(w2) 
 +plt.xlabel("f/Hz"
 +plt.ylabel("A(f)"
 + 
 +plt.subplot(3,2,5)   # sous-graphes en 3 lignes et 2 colonnes, graphe 5 
 +plt.plot(x,y3) 
 +plt.xlabel("t/s"
 +plt.ylabel("A(t)"
 + 
 +plt.subplot(3,2,6)   # sous-graphes en 3 lignes et 2 colonnes, graphe 6 
 +plt.plot(w3) 
 +plt.xlabel("f/Hz"
 +plt.ylabel("A(f)"
 + 
 +plt.savefig('fonctions-fft.png'
 +plt.show() 
 +</code> 
 + 
 +Figure obtenue : 
 + 
 +{{ :teaching:progappchim:fonctions-ft-04.png |}} 
 + 
 +===== Avantages de numpy ===== 
 +L'utilisation de la librairie nump permet souvent d'améliorer les performances par rapport à un code numérique écrit en "pure Python". Voici un exemple : 
 + 
 +{{gh>https://github.com/didiervillers/python_programs/blob/master/direct_pi_multirun-timeit.py}}
  
 ===== Références ===== ===== Références =====
  
   * [[http://www.numpy.org/|Site officiel]]   * [[http://www.numpy.org/|Site officiel]]
-  * [[http://docs.scipy.org/doc/numpy-1.8.0/reference/index.html|NumPy reference]]+  * [[http://docs.scipy.org/doc/numpy/reference/|NumPy reference]]
   * [[http://fr.wikipedia.org/wiki/NumPy|Page Wikipédia]]   * [[http://fr.wikipedia.org/wiki/NumPy|Page Wikipédia]]
   * [[http://csc.ucdavis.edu/~chaos/courses/nlp/Software/NumPyBook.pdf|Guide to NumPy]]   * [[http://csc.ucdavis.edu/~chaos/courses/nlp/Software/NumPyBook.pdf|Guide to NumPy]]
-  * [[http://www.loria.fr/~rougier/teaching/numpy/numpy.html|Tutoriel via l'exemple du jeu de la vie]]+  * [[http://www.loria.fr/~rougier/teaching/numpy/numpy.html|Tutoriel via l'exemple du jeu de la vie]] (+ [[https://github.com/rougier/numpy-tutorial|ici]])
   * [[http://wiki.scipy.org/Tentative_NumPy_Tutorial]]   * [[http://wiki.scipy.org/Tentative_NumPy_Tutorial]]
 +  * [[http://math.mad.free.fr/wordpress/wp-content/uploads/intronumpy.pdf|Introduction à Numpy, Scipy et Matplotlib]]
 +  * [[http://scipy-lectures.github.io/intro/numpy/index.html|NumPy: creating and manipulating numerical data]], de Emmanuelle Gouillart, Didrik Pinte, Gaël Varoquaux, and Pauli Virtanen
 +  * [[http://ipython-books.github.io/featured-01/|Getting the Best Performance out of NumPy]]
 +  * [[https://medium.com/towards-data-science/two-cool-features-of-python-numpy-mutating-by-slicing-and-broadcasting-3b0b86e8b4c7|Two cool features of Python NumPy: Mutating by slicing and Broadcasting]]
 +  * [[https://www.machinelearningplus.com/numpy-tutorial-part1-array-python-examples/|Numpy Tutorial Part 1: Introduction to Arrays]]
 +  * [[https://www.machinelearningplus.com/101-numpy-exercises-python/|101 NumPy Exercises for Data Analysis]]
 +  * [[https://towardsdatascience.com/numpy-python-made-efficient-f82a2d84b6f7|Numpy — Python made efficient]]
  
  • teaching/progappchim/numpy_simple.txt
  • Dernière modification : 2023/03/07 13:05
  • de villersd