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 [2015/03/05 13:14] villersdteaching:progappchim:numpy_simple [2020/12/27 10:45] – [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 25: Ligne 25:
 Les fonctions arange et shape sont bien pratiques pour générer des nombres en séquences et réarranger des listes de nombres. La fonction linspace est utile parce qu'elle impose exactement le nombre de valeurs crées ente un minimum et un maximum. Les fonctions arange et shape sont bien pratiques pour générer des nombres en séquences et réarranger des listes de nombres. La fonction linspace est utile parce qu'elle impose exactement le nombre de valeurs crées ente un minimum et un maximum.
  
-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 [[https://docs.scipy.org/doc/numpy/|cette page]] pour consulter d'autres fonctionnalités, ou [[https://scipy.github.io/old-wiki/pages/Numpy_Example_List|cette ancienne documentation]].
 </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 99: Ligne 100:
   * 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)   * //[[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 =====
Ligne 198: Ligne 203:
  
 **poly1d & polynomial ordonnent les coefficients en sens inverses !!!**</note> **poly1d & polynomial ordonnent les coefficients en sens inverses !!!**</note>
-<sxh python; title : arrays_polynomes_06.py>+<code python arrays_polynomes_06.py>
 #! /usr/bin/env python #! /usr/bin/env python
 # -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
Ligne 205: Ligne 210:
 """ """
 import numpy as np import numpy as np
 +from numpy.polynomial import Polynomial as P
  
-# les coefficients du polynômes sont donnés par ordre décroissance des degrés dans poly1d +# les coefficients du polynômes sont donnés par ordre décroissance des dégrés 
-a=np.poly1d([1.,2.,3.,4.]) # = x³ + 2x² + 3x +4+a = P([4., 3., 2., 1.]) # = x³ + 2x² + 3x + 4
  
-print "polynôme : \n",a, type(a)+print("polynôme : \n", a, type(a))
 # les coefficients de a : # les coefficients de a :
-print "coefficients : ",a.coeffs+print("coefficients : ", a.coef)
 # les racines de a : # les racines de a :
-print "racines : ",a.roots+print("racines : ", a.roots())
 # l'ordre du polynôme : # l'ordre du polynôme :
-print "ordre : ",a.order+print("ordre : ", a.degree())
 # évaluations sur un vecteur # évaluations sur un vecteur
-x=np.linspace(0,2.,21) +x = np.linspace(0, 2., 21) 
-print "x = ",x +print("x = ", x) 
-print "évaluation en x : ",np.polyval(a,x)+print("évaluation en x : ", a(x))
 # dérivation # dérivation
-print "dérivée : \n",np.polyder(a)+print("dérivée : \n", a.deriv(1)) 
 +print("dérivée seconde : \n", a.deriv(2)) 
 +print("dérivée troisième : \n", a.deriv(3)) 
 +print("dérivée quatrième : \n", a.deriv(4))
 # intégration # intégration
-print "intégrale : \n",np.polyint(a)+print("intégrale : \n", a.integ(1))
 # création d'un polynôme par ses racines # création d'un polynôme par ses racines
-b=a.roots +b = a.roots() 
-c=np.poly1d(b,True+c = P.fromroots(b) 
-print "Polynômes recrées par les racines :\n", c+print("Polynômes recrées par les racines :\n", c
 +#
 # fitting polynomial # fitting polynomial
-xd=np.array([0.,1.,2.,3.,4.,5.]) +
-yd1=np.array([0.05,0.99,3.95, 9.17,15.86,24.93]) +# utilisation de poly1d (ancienne librairie) 
-pfit=np.poly1d(np.polyfit(xd,yd1,2)) +#  
-print "fit d'une parabole (polynôme d'ordre 2) sur ces x et y :" +# numpy.polyfit (poly1d) : 
-print xd +# https://docs.scipy.org/doc/numpy/reference/routines.polynomials.poly1d.html 
-print yd1 +# https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html 
-print "polynôme de fit : \n",pfit +
-</sxh>+xd = np.array([0., 1., 2., 3., 4., 5.]) 
 +yd = np.array([0.05, 0.99, 3.95, 9.17, 15.86, 24.93]) 
 +pfit = np.poly1d(np.polyfit(xd, yd, 2)) 
 +print("fit d'une parabole (polynôme d'ordre 2) sur ces x et y :") 
 +print(xd) 
 +print(yd) 
 +print("polynôme de fit : \n", pfit
 +
 +# "Unfortunately, np.polynomial.polynomial.polyfit returns the coefficients 
 +# in the opposite order of that for np.polyfit and np.polyval" 
 +# → https://stackoverflow.com/questions/18767523/fitting-data-with-numpy 
 +
 +################################################## 
 +# Ajouter les fits utilisant numpy.polynomial... # 
 +################################################## 
 +
 +# numpy.polynomial.polynomial.Polynomial.fit : 
 +# https://docs.scipy.org/doc/numpy/reference/routines.polynomials.html 
 +# https://docs.scipy.org/doc/numpy/reference/routines.polynomials.package.html 
 +# https://docs.scipy.org/doc/numpy/reference/routines.polynomials.classes.html 
 +# https://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.Polynomial.fit.html 
 +
 +# numpy.polynomial.polynomial.polyfit : 
 +# https://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.polynomial.polyfit.html 
 +# 
 +</code>
  
 Autres fonctions : voir [[http://docs.scipy.org/doc/numpy/reference/routines.polynomials.html|ici]] Autres fonctions : voir [[http://docs.scipy.org/doc/numpy/reference/routines.polynomials.html|ici]]
Ligne 245: Ligne 280:
 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]]. 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]].
  
-<sxh python; title : fonctions-FT-04.py>+<code python fonctions-FT-04.py>
 #!/usr/bin/env python #!/usr/bin/env python
 #-*- coding: utf-8 -*- #-*- coding: utf-8 -*-
Ligne 276: Ligne 311:
 x = np.arange(0.0,10.0,0.025) x = np.arange(0.0,10.0,0.025)
 y1 = f1(x) y1 = f1(x)
-z1=fft.fft(y1)   +z1 = fft.fft(y1)   
-w1 = np.abs(z1[:len(z1)/2])+w1 = np.abs(z1[:len(z1)//2])
 y2 = f2(x) y2 = f2(x)
-z2=fft.fft(y2) +z2 = fft.fft(y2) 
-w2 = np.abs(z2[:len(z2)/2])+w2 = np.abs(z2[:len(z2)//2])
 y3 = f3(x) y3 = f3(x)
-z3=fft.fft(y3) +z3 = fft.fft(y3) 
-w3 = np.abs(z3[:len(z3)/2])+w3 = np.abs(z3[:len(z3)//2])
  
 # doc subplot : http://matplotlib.org/api/pyplot_api.html?highlight=subplot#matplotlib.pyplot.subplot # doc subplot : http://matplotlib.org/api/pyplot_api.html?highlight=subplot#matplotlib.pyplot.subplot
Ligne 320: Ligne 355:
 plt.savefig('fonctions-fft.png') plt.savefig('fonctions-fft.png')
 plt.show() plt.show()
-</sxh>+</code>
  
 Figure obtenue : Figure obtenue :
Ligne 326: Ligne 361:
 {{ :teaching:progappchim:fonctions-ft-04.png |}} {{ :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 =====
Ligne 333: Ligne 372:
   * [[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://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]]
 +  * [[https://www.nature.com/articles/s41586-020-2649-2|Array programming with NumPy]] Harris, C.R., Millman, K.J., van der Walt, S.J. et al., Nature 585, 357–362 (2020) DOI: 10.1038/s41586-020-2649-2
 +  * [[https://medium.com/better-programming/numpy-illustrated-the-visual-guide-to-numpy-3b1d4976de1d|NumPy Illustrated: The Visual Guide to NumPy]]
  
  • teaching/progappchim/numpy_simple.txt
  • Dernière modification : 2023/03/07 13:05
  • de villersd