python pour le calcul scientifique - maths.cnam.frmaths.cnam.fr/img/pdf/python_cs_cle8b562b.pdf ·...
Post on 02-Aug-2018
234 Views
Preview:
TRANSCRIPT
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Python pour le calcul scientifique
O. Wilk
Calcul scientifique/Math/Cnam
2016
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Introduction
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Introduction
Un langage libre et portable sur n’importe quelsystème (Windows, Mac, Linux)
permettant de relier des mondes et des langagesdifférents :
réseausystème visualisation
C Java VTK
calcul Python Cuda, OpenCL
Fortran GTK web
entrée/sortie IHM
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Introduction1989 : Guido van Rossum développe Python,1991 : Python est publié,1994 : premières applications scientifiques.
Un langage qui sort du lot :Programming Web Position Position PositionLanguage Rate Jan 2011 Jan 2006 Jan 1996Java 18 % 1 1 5C 16 % 2 2 1C++ 9 % 3 3 2PHP 8 % 4 4 -Python 6 % 5 8 22C# 6 % 6 7 -(Visual) Basic 6 % 7 5 3Objective-C 3 % 8 44 -Perl 3 % 9 6 6Ruby 2 % 10 20 -Lisp 1 % 13 14 13Ada 1 % 20 17 12
Classement TIOBE / moteurs de recherche du web.
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Introduction
(Seuls 3 langages progressent : Python, Objective-C : langage phare du
développement pour Mac OS X, C# roi des langages .NET pour Microsoft)
Python élu langage de l’année 2010 par TIOBE.
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
IntroductionPourquoi Python s’impose-t-il ?
Pour sa lisibilité,
rien a déclarer, gestion automatique de la mémoire,
orienté "objet", interprété et partiellement compilé (alternative àMatlab, Scilab, Octave, ... mais pas simplement),
même si ce n’est pas le plus rapide, on peut l’interfacer avec d’autreslangages plus performants : facile à interfacer avec le Fortran (f2py),le C (swig, boost), Cuda et OpenCL (pycuda, pyopencl), ...
Des librairies déjà très optimisées et un grand choix de bibliothèques,
d’autres langages accessibles par python : Jython ⇒ Java,
une plateforme très "communautaire".
Python permet d’intégrer facilement des codes de calculexistants (Fortran, C, ...), de les rendre accessibles(MacroCommandes, Gui), de traiter graphiquement leursrésultats et de poursuivre leurs développements ...
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Introduction
Un grand choix de bibliothèques et de logiciels ouverts,permettant de faire du :
web (Zope, Plone, Django, ...), bases de données(MySQL, Oracle, ...), réseaux (PyRO, ...), Gui (Gtk, Qt,WxWidgets, ...), graphique (gnuplot, matplotlib, VTK,MayaVi, ...), calcul scientifique ( E.F. (FiPy, Getfem, ...),systèmes Dynamiques (SimPy), ...), mathématiques(Sage), statistiques (MDP), bioinformatique(BioPython, MMTK, ...), ...
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Des bases
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Pour commencer (1/2)Choisir son interface, son environnement deprogrammation :
python,idle, ipython (complétion automatique, ...),bpython, spyder, jupyter (notebook), ...des environnement de dév. : eclipse+PyDev, ...
Savoir chercher de l’information :
sous le prompt python : help(), help(nom d’unevariable, d’une fonction ou d’un package), ...sous le prompt ipython : help() ounom-package.nom-fonction?,sur la toile : docs.python.org, www.python.org/,pypi.python.org/, ...
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Pour commencer (2/2)
Respecter quelques règles :
commencer en tout début de ligne (le décalage "4espaces" sert pour les test et les boucles),éviter les tabulations n’étant pas constituéesd’espace d’un caractère.
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Commentaires, chaines de caractères (1/2)CodePython.py
# −∗− coding : u t f 8 −∗−# Met t re un commentaire dans l e code pythonpr in t " A f f i c h e r un commentaire durant l ’ exé cu t i on . "
# ======================================================# Une chaine de carac t è res avec passage à l a l i g n e
chaine = " " " Le feu n ’ a p lus de fuméequand i l es t devenu flamme .
D j a l a l a l−Din Rumi " " "
pr in t chainepr in t " pour t r a i t e r une chaine de carac t è res : "pr in t " chaine . f i nd , chaine . replace , chaine . s p l i t , . . . "
# ======================================================# Transformer un nombre en chaine de carac t è res
a = 12345 ; b = −6789.01 ; c = 1.01e−6
pr in t " " " A jou te r une chaine de carac t è res " " " +st r ( a )+ " " "pu is une aut re " " " +st r ( b)+ " " " e t l a de rn i è re " " " +st r ( c )+ " " " . " " "
# ======================================================# A f f i c h e r en formatant , a t t e n t i o n aux er reu rs é ven tue l l es
pr in t " format s : %s %s %s " % ( st r ( a ) , st r ( b ) , st r ( c ) )pr in t " format f : %12.2 f %12.2 f %12.2 f " % ( a , b , c )pr in t " format d : %6d %6d %6d " % ( a , b , c )pr in t " format e : %12.3e %12.3e %12.3e " % ( a , b , c )
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Commentaires, chaines de caractères (2/2)
[wilk@localhost ∼]$ python CodePython.py
A f f i c h e r un commentaire durant l ’ exé cu t i on .
Le feu n ’ a p lus de fuméequand i l es t devenu flamme .
D j a l a l a l−Din Rumi
pour t r a i t e r une chaine de carac t è res :chaine . f i nd , chaine . replace , chaine . s p l i t , . . .
A jou te r une chaine de carac t è res 12345 puis une aut re −6789.01et l a de rn i è re 1.01e−06.
format s : 12345 −6789.01 1.01e−06
format f : 12345.00 −6789.01 0.00format d : 12345 −6789 0format e : 1.234e+04 −6.789e+03 1.010e−06
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Listes (... dico.)CodePython.py
# −∗− coding : u t f 8 −∗−pr in t " Cré a t i on d ’ une ’ L i s t e ’ "a = [1 , 3.14 , " t o t o " ]pr in t apr in t " On r écupère l e second " , a [ 1 ] # l a numé r a t o t i o n commence à 0pr in t " l e de rn ie r " , a[−1]pr in t " l es compo . 0 e t 1 " , a [ 0 : 2 ]
pr in t " On enlève l a composante 1 "a [ 1 : 2 ] = [ ]pr in t a
pr in t " longeur de l a l i s t e " , len ( a )
pr in t " On a jou te un é l ément "a . append ( " t i t i " )pr in t a
[wilk@localhost ∼]$ python CodePython.py
Cré a t i on d ’ une ’ L i s te ’[ 1 , 3 .14 , ’ to to ’ ]On r écupère l e second 3.14
l e de rn ie r t o t oles compo . 0 e t 1 [1 , 3 .14 ]
On enlève l a composante 1[1 , ’ to to ’ ]
longeur de l a l i s t e 2On a jou te un é l ément
[ 1 , ’ to to ’ , ’ t i t i ’ ]
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Types et opérationsCodePython.py
# −∗− coding : Ut f8 −∗−
pr in t " Quelques opera t ions "pr in t " 1 .+2 . , 1.−2. , 1 .∗2 . , 1 . / 2 . , 2∗∗2"pr in t 1 .+2 . , 1.−2. , 1 .∗2 . , 1 . / 2 . , 2∗∗2
pr in t " Un complexe : "a = complex ( 1 . 1 , 2 . 2 )pr in t a . rea l , a . imag , type ( a )
b = i n t ( a . r e a l ) ; c = f l o a t ( b ) # Conversion . . .
import math
pr in t " Pi = %.60 f " % ( math . p i )
[wilk@localhost ∼]$ python CodePython.py
Quelques opera t ions1 .+2 . , 1.−2. , 1 .∗2 . , 1 . / 2 . , 2∗∗2
3.0 −1.0 2.0 0.5 4
Un complexe :1.1 2.2 <type ’ complex ’ >
Pi = 3.141592653589793115997963468544185161590576171875000000000000
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Tests et boucles (1/3)CodePython.py
# −∗− coding : u t f 8 −∗−# i f
i f ( 0 == 1 ) :# i l f a u t i nden te r pour que Python sache que l ’ on est dans l e t e s tpr in t " "pr in t " On s o r t ! "q u i t ( )
else :pr in t " "pr in t " t e s t s : (0 < 1) " , (0 < 1) , type ( ( 0 == 1 ) )pr in t " t e s t s : (0 > 1) " , (0 > 1)pr in t " t e s t s : (0 == 1) and (1 == 1) " , (0 == 1) and (1 == 1)pr in t " t e s t s : (0 == 1) or (1 == 1) " , (0 == 1) or (1 == 1)# l a f i n de l ’ i n d e n t a t i o n marque l a f i n du t e s t
pr in t " On cont inue hors du t e s t "
[wilk@localhost ∼]$ python CodePython.py
t e s t s : (0 < 1) True <type ’ bool ’ >t e s t s : (0 > 1) Falset e s t s : (0 == 1) and (1 == 1) Falset e s t s : (0 == 1) or (1 == 1) True
On cont inue hors du t e s t
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Tests et boucles (2/3)CodePython.py
# −∗− coding : u t f 8 −∗−# whi le
i = 0while i < 3 :
pr in t ii = i + 1
while 1:t ry :
x = f l o a t ( raw_input ( " Frapper au c l a v i e r un nombre. . . ( au t re chose vous fe ra recommencer ) : " ) )break
except ValueError :pr in t " Ce n ’ es t pas c o r r e c t ! Recommencez . . . "
pr in t x
[wilk@localhost ∼]$ python CodePython.py
012
Frapper au c l a v i e r un nombre ( aut re chose vous fe ra recommencer ) : azer tyCe n ’ es t pas c o r r e c t ! Recommencez . . .Frapper au c l a v i e r un nombre ( aut re chose vous fe ra recommencer ) : 123.1
123.1
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Tests et boucles (3/3)
CodePython.py
# −∗− coding : u t f 8 −∗−# f o r
for i in xrange ( 0 ,5 ) :pr in t i
pr in t [ j for j in xrange ( 0 , 5 ) ]
[wilk@localhost ∼]$ python CodePython.py
01234
[0 , 1 , 2 , 3 , 4 ]
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Entrée - Sortie (1/5)
CodePython.py (PAS SOUS JUPYTER)
# −∗− coding : u t f 8 −∗−# Récupé r e r des arguments en en t r ée
import sys # On importe un package# i l va nous s e r v i r a r écupé r e r des arguments d ’ en t r ée . . .
L i s t e = sys . argv # On r écupère les arguments d ’ en t r ée# python CeFich ier . py arg1 arg2 . . .
pr in t " "pr in t " Les arguments sont dans l a l i s t e su ivante : " , L i s t epr in t [ L i s t e [ j ] for j in xrange (0 , len ( L i s t e ) ) ] , type ( L i s t e )
[wilk@localhost ∼]$ python CodePython.py 1 2
Les arguments sont dans l a l i s t e su ivante : [ ’ 2 a_In_Out . py ’ , ’ 1 ’ , ’ 2 ’ ][ ’ 2 a_In_Out . py ’ , ’ 1 ’ , ’ 2 ’ ] <type ’ l i s t ’ >
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Entrée - Sortie (2/5)
CodePython.py (PAS SOUS JUPYTER)
# −∗− coding : u t f 8 −∗−# Récupé r e r des arguments en cours d ’ exé cu t i on
# Un nombre
x = input ( " Frapper au c l a v i e r un nombre : " )
pr in t x , type ( x )
# Une chaine de carac t è res
pr in t " "a = raw_input ( " Frapper au c l a v i e r une chaine de carac t è res ( sans ’ ’ ) : " )pr in t a , a [ 0 : 3 ] , a [ 1 : 3 ] , type ( a )
[wilk@localhost ∼]$ python CodePython.py 1 2
Frapper au c l a v i e r un nombre : 123.1123.1 <type ’ f l o a t ’ >
Frapper au c l a v i e r une chaine de carac t è res ( sans ’ ’ ) : azer tyazer ty aze ze <type ’ s t r ’ >
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Entrée - Sortie (3/5)CodePython.py
# −∗− coding : u t f 8 −∗−
pr in t " Ouverture du f i c h i e r en e c r i t u r e "
f = open ( ’ tmp . dat ’ , ’w ’ )
pr in t " On é c r i t dans l e f i c h i e r ( avec des sauts de l i g n e s ) "
x = 1.1 ; y = 2
f . w r i t e ( st r ( x ) )f . w r i t e ( st r ( y ) )f . w r i t e ( ’ \ n ’ )f . w r i t e ( st r ( x ) )f . w r i t e ( ’ \ n ’ )f . w r i t e ( st r ( y ) )
pr in t " On ferme l e f i c h i e r "
f . c lose ( )
[wilk@localhost ∼]$ cat tmp.dat
1.121.12
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Entrée - Sortie (4/5)CodePython.py
# −∗− coding : u t f 8 −∗−pr in t " D i f f é rentes maniè res de l i r e "pr in t " V1"f = open ( ’ tmp . dat ’ , ’ r ’ )pr in t " " , f . read ( )f . c lose ( )pr in t " V2"f = open ( ’ tmp . dat ’ , ’ r ’ )pr in t " 1 " , f . r ead l i ne ( )pr in t " 2 " , f . r ead l i ne ( )f . c lose ( )pr in t " V3"f = open ( ’ tmp . dat ’ , ’ r ’ )pr in t " " , f . r ead l i nes ( )f . c lose ( )
[wilk@localhost ∼]$ python CodePython.py
D i f f é rentes maniè res de l i r eV1
1.121.12
V21 1.12
2 1.1
V3[ ’ 1 . 1 2 \ n ’ , ’ 1 . 1 \ n ’ , ’ 2 ’ ]
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Entrée - Sortie (5/5)CodePython.py
# −∗− coding : u t f 8 −∗−# L i r e un f i c h i e r a s c i i contenant une matr ice :# v o i r auss i ’ load ’ , ’ save ’ , ’ savez ’
import numpy as np
a = np . l o a d t x t ( ’ mat . dat ’ , d e l i m i t e r = ’ , ’ )
pr in t type ( a ) , a . shape , a . s i zepr in t " "pr in t a
[wilk@localhost ∼]$ cat mat.dat
# commentaire1 , 2 , 34 , 5 , 67 , 8 , 9
[wilk@localhost ∼]$ python CodePython.py
<type ’numpy . ndarray ’ > (3 , 3) 9
[ [ 1 . 2 . 3 . ][ 4 . 5 . 6 . ][ 7 . 8 . 9 . ] ]
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Fonctions (1/2)CodePython.py
# −∗− coding : Ut f8 −∗−# Une f o n c t i o n dans l e corps du s c r i p t . . .def Fibonacc i ( n ) :
a , b = 0 , 1for i in xrange ( n ) : a , b = b , a+breturn b
pr in t [ F ibonacc i ( i ) for i in xrange ( 1 , 1 0 ) ]
# impor te r une f o n c t i o n qu i n ’ es t pas dans l e même r é p e r t o i r eimport syssys . path . append ( " Bib_Perso " ) # On a jou te l e l e chemin du r é p e r t o i r eimport Fibonacci_2
pr in t [ F ibonacci_2 . Fibonacci_2 ( i ) for i in xrange ( 1 , 1 0 ) ]
[wilk@localhost ∼]$ cat Bib_Perso/Fibonacci2.py
def Fibonacci_2 ( n ) :" " " I l es t poss ib le de documenter les f o n c t i o n setc . . . " " "a , b = 0 , 1for i in xrange ( n ) : a , b = b , a+breturn b
[wilk@localhost ∼]$ python CodePython.py
[1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55][ 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55]
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Fonctions (2/2)CodePython.py
# −∗− coding : Ut f8 −∗−# Fonct ion à p l u s i e u r s v a r i a b l e s i n e t outdef t e s t ( a , b ) :
c = a + bd = a ∗ b
return c , d
a = 2.0 ; b = 1.0
[ c , d ] = t e s t ( a , b )
pr in t a , b , c , d
# exé cu te r des f on c t i on s d ’ aut res l o g i c i e l s# ( hors python , sous s h e l l un ix / l i n u x par ex )import os
os . system ( ’pwd ’ )
[wilk@localhost ∼]$ python CodePython.py
2.0 1.0 3.0 2.0
/ home / w i l k / Bureau / Python / Expose_LaTeX / Python_tests_LaTeX
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Pour le Calcul Scientifique
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Numpy, Scipy et Matplotlib
Numpy : Un package incontournable pourcommencer à faire du calcul scientifique sousPython,Scipy : un ensemble d’extensions permettant decompléter Numpy,Matplotlib : le package permettant de faire desvisualisations 2D (mais pas que ...) de très hautequalité, facilement et avec de très bonnesperformances.
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Numpy
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Numpy (1/6) : des tableaux.
[wilk@localhost ∼]$ python
>>> import numpy as np
>>> a = np . ar ray ( [ ( 1 . 5 , 2 , 3 ) , (4 ,5 ,6 ) ] , dtype = ’ f l o a t 3 2 ’ )>>> pr in t a[ [ 1.5 2 . 3 . ][ 4 . 5 . 6 . ] ]
>>> a . shape , a . s ize , a . dtype(2 , 3 ) , 6 , dtype ( ’ f l o a t 3 2 ’ )>>> type ( a )<type ’ numpy . ndarray ’>
>>> b = np . zeros ( ( 2 , 3 ) , dtype = ’ f l o a t 3 2 ’ )>>> bar ray ( [ [ 0 . , 0 . , 0 . ] ,
[ 0 . , 0 . , 0 . ] ] , dtype= f l o a t 3 2 )
>>> b = np . ones ( ( 2 , 3 ) , dtype = ’ f l o a t 3 2 ’ )>>> bar ray ( [ [ 1 . , 1 . , 1 . ] ,
[ 1 . , 1 . , 1 . ] ] , dtype= f l o a t 3 2 )
Qq. types : int32, int64, float32, float64, complex64, complex128, ...
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Numpy (1/6) : des tableaux (suite).
[wilk@localhost ∼]$ python
>>> import numpy as np
>>> np . arange ( 0 , 1 , 0.1 )ar ray ( [ 0 . , 0 .1 , 0 .2 , 0 .3 , 0 .4 , 0 .5 , 0 .6 , 0 .7 , 0 .8 , 0 . 9 ] )
>>> np . l i nspace ( 0 , 1 , 11 )ar ray ( [ 0 . , 0 .1 , 0 .2 , 0 .3 , 0 .4 , 0 .5 , 0 .6 , 0 .7 , 0 .8 , 0 .9 , 1 . ] )
>>> x = np . l i nspace ( 0 , np . p i , 10 )
>>> np . s in ( x )ar ray ( [ 0.00000000e+00 , 3.42020143e−01, 6.42787610e−01,
8.66025404e−01, 9.84807753e−01, 9.84807753e−01,8.66025404e−01, 6.42787610e−01, 3.42020143e−01,1.22464680e−16])
>>> np . s in ( np . p i ) # à comparer à l a de rn i è re va leur obtenue précédemment1.2246467991473532e−16
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Numpy (2/6) : des opérations.
[wilk@localhost ∼]$ python
>>> import numpy as np
>>> a = np . ar ray ( [ ( 1 . 5 , 2 , 3 ) , (4 ,5 ,6 ) ] , dtype = ’ f l o a t 3 2 ’ )
>>> c = np . ones ( ( 2 , 3 ) , dtype = ’ f l o a t 3 2 ’ )>>> car ray ( [ [ 1 . , 1 . , 1 . ] ,
[ 1 . , 1 . , 1 . ] ] , dtype= f l o a t 3 2 )
>>> a∗c # p r o d u i t terme à termear ray ( [ [ 1 .5 , 2 . , 3 . ] ,
[ 4 . , 5 . , 6 . ] ] , dtype= f l o a t 3 2 )
>>> np . dot ( a , c ) # p r o d u i t en t re 2 matr icesTraceback ( most recent c a l l l a s t ) :
F i l e "<s td in > " , l i n e 1 , in <module>ValueError : matr ices are not a l igned>>> np . transpose ( a )ar ray ( [ [ 1 .5 , 4 . ] ,
[ 2 . , 5 . ] ,[ 3 . , 6 . ] ] , dtype= f l o a t 3 2 )
>>> np . dot ( np . t ranspose ( a ) , c )ar ray ( [ [ 5 .5 , 5 .5 , 5 . 5 ] ,
[ 7 . , 7 . , 7 . ] ,[ 9 . , 9 . , 9 . ] ] , dtype= f l o a t 3 2 )
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Numpy (3/6) : des fonctions.
[wilk@localhost ∼]$ python
>>> import numpy as np
>>> a = np . ar ray ( [ ( 1 . 5 , 2 , 3 ) , (4 ,5 ,6 ) ] , dtype= ’ f l o a t 3 2 ’ )
>>> np .sum( a ) # ou a . sum ( )21.5>>> np . min ( a ) # ou a . min ( )1.5>>> np .max( a ) # ou a .max ( )6.0>>> np . mean( a ) # ou a . mean ( )3.5833333333333335>>> np . median ( a ) # ou a . median ( )3.5
>>> x = np . ar ray ( [ 30 ,20 ,10 ] )>>> index = np . a rgso r t ( x )>>> x [ index ]ar ray ( [ 1 0 , 20 , 30 ] )
et aussi : np.exp, np.log, np.log10, np.sqrt, np.sin, np.cos, np.tan, np.arcsin, np.arccos, np.arctan,
np.sign ...
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Numpy (3/6) : des fonctions (suite).[wilk@localhost ∼]$ python
Array Creat ionarange , array , copy , empty , empty_l ike , eye , f r o m f i l e , f romfunc t ion ,i d e n t i t y , l inspace , logspace , mgrid , ogr id , ones , ones_l ike , r , zeros ,ze ros_ l i ke
Conversionsastype , a t l e a s t 1d , a t l e a s t 2d , a t l e a s t 3d , mat
Manipu la t ionsar ray s p l i t , column stack , concatenate , diagonal , d s p l i t , dstack , h s p l i t ,hstack , item , newaxis , rave l , repeat , reshape , res ize , squeeze , swapaxes ,take , transpose , v s p l i t , vs tack
Questionsa l l , any , nonzero , where
Order ingargmax , argmin , a rgsor t , max, min , ptp , searchsorted , s o r t
Operat ionschoose , compress , cumprod , cumsum, inner , f i l l , imag , prod , put , putmask ,rea l , sum
Basic S t a t i s t i c scov , mean , std , var
Basic L inear Algebracross , dot , outer , svd , vdot
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Numpy (4/6) : des affectations (attention).
[wilk@localhost ∼]$ python
>>> import numpy as np
>>> x = np . ar ray ( [ 30 ,20 ,10 ] )
>>> y = x>>> y is xTrue>>> y [ 1 ] = 22>>> xar ray ( [ 1 0 , 22 , 30 ] )
>>> z = y . copy ( )>>> z is yFalse>>> z [ 1 ] = 20
>>> yar ray ( [ 1 0 , 22 , 30 ] )>>> zar ray ( [ 1 0 , 20 , 30 ] )
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Numpy (5/6) : des extractions.
[wilk@localhost ∼]$ python
>>> import numpy as np
>>> a = np . ar ray ( [ ( 1 . 5 , 2 , 3 , 4 ) , ( 4 .5 ,5 ,6 ,7 ) ] )>>> aar ray ( [ [ 1 .5 , 2 . , 3 . , 4 . ] ,
[ 4 .5 , 5 . , 6 . , 7 . ] ] )
>>> a [ : , 1 ]a r ray ( [ 2 . , 5 . ] )>>> a [ 1 , : ]a r ray ( [ 4 .5 , 5 . , 6 . , 7 . ] )
>>> a [ 1 , 0 : 3 ]a r ray ( [ 4 .5 , 5 . , 6 . ] )>>> a [ 1 , 1 : 3 ]a r ray ( [ 5 . , 6 . ] )>>> a[0 ,−1] # dern i è re va leur de l a premiè re l i g n e4.0
>>> i = np . ar ray ( [ 0 , 2 ] )>>> a [ : , i ] # r écupè r a t i o n à l ’ a ide d ’ un " ar ray " pour les i nd i cesar ray ( [ [ 1 .5 , 3 . ] ,
[ 4 .5 , 6 . ] ] )
et aussi : np.diag, np.linalg.det, np.linalg.eig, ...
("linalg" pour algèbre linéaire, voir plutôt scipy)
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Numpy (6/6) : Intégrer du code C ou fortran
C’est possible (f2py, swig, ...)
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Scipy
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Scipy (1/3) : prolonge Numpy.
[wilk@localhost ∼]$ python
>>> import numpy as np>>> import sc ipy as sp
>>> np . s q r t (−1.) , sp . s q r t (−1.)( nan , 1 j )
>>> np . log (−1.) , sp . log (−1.)( nan , 3.1415926535897931 j )
...
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Scipy (2/3) : des modules spécialisés.
Sous module Descriptioncluster Clustering algorithmsconstants Physical and mathematical constantsfftpack Fast Fourier Transform routinesintegrate Integration and ordinary differential equation solversinterpolate Interpolation and smoothing splinesio Input and Outputlinalg Linear algebramaxentropy Maximum entropy methodsndimage N-dimensional image processingodr Orthogonal distance regressionoptimize Optimization and root-finding routinessignal Signal processingsparse Sparse matrices and associated routinesspatial Spatial data structures and algorithmsspecial Special functionsstats Statistical distributions and functionsweave CC++ integration
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Scipy (3/3) : Stockage morse
Importer le module "scipy.sparse" :
>>> import scipy.sparse as sp_sp
Les différentes classes, modules et fonctions,un petit exemple.
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Les différentes classes
Différents stockages morses :csc_matrix: Compressed Sparse Column format,
csr_matrix: Compressed Sparse Row format,
bsr_matrix: Block Sparse Row format,
lil_matrix: List of Lists format,
dok_matrix: Dictionary of Keys format,
coo_matrix: COOrdinate format,
dia_matrix: DIAgonal format.
Les formats "csc_matrix" et "csr_matrix" sont àprivilégier lors des opérations de factorisation, derésolution, ...Les autres sont plus souples pour construire oumanipuler les matrices.
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Quelques fonctions
et aussi pour construire une matrice morse :
eye : 1 sur la k ième diagonale, sinon 0,
identity : matrice identité stockée morse,
kron, kronsum : produit et somme de kronecker de matrices morses,
spdiags : matrice diagonale stockée morse,
tril, triu : partie "lower" et "upper" d’une matrice morse,
bmat : création d’une matrice bloc à partir de matrices morses, voiraussi hstack et vstack.
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Exemplesimport numpy as npimport sc ipy . sparse as sp_sp
row = np . ar ray ( [ 0 , 2 , 1 ] ) ; co l = np . ar ray ( [ 0 , 2 , 1 ] ) ; data = np . ar ray ( [ 4 , 5 , 7 ] )pr in t sp_sp . coo_matr ix ( ( data , ( row , co l ) ) , shape =(3 ,3) ) . todense ( )# [ [ 4 0 0 ]# [0 7 0 ]# [0 0 5 ] ]
pr in t sp_sp . eye (3 ,3 , k =1 ) . todense ( )# [ [ 0 . 1 . 0 . ]# [ 0 . 0 . 1 . ]# [ 0 . 0 . 0 . ] ]
data = np . ar ray ( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ) ; d iags = np . ar ray ( [0 , −1 ,1] )pr in t sp_sp . spdiags ( data , diags , 3 , 3 ) . todense ( )# [ [ 1 8 0 ]# [4 2 9 ]# [0 5 3 ] ]
A = sp_sp . coo_matr ix ( [ [ 1 , 2 ] , [ 3 , 4 ] ] )B = sp_sp . coo_matr ix ( [ [ 5 ] , [ 6 ] ] ) ; C = sp_sp . coo_matr ix ( [ [ 7 ] ] )pr in t A. todense ( ) ; pr in t B. todense ( ) ; pr in t C. todense ( )# [ [ 1 2 ] [ [ 5 ] [ [ 7 ] ]# [3 4 ] ] [ 6 ] ]
pr in t sp_sp . bmat ( [ [ A ,B ] , [ None ,C ] ] ) . todense ( )# [ [ 1 2 5 ]# [3 4 6 ]# [0 0 7 ] ]
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Des modules
extract : pour extraire différentes parties d’une matrice morse,
sparsetools : différentes routines pour manipuler les matrices ...produits,
...
en relation avec (A une matrice stockée morse, x un vecteur) :
LaDiagonale = A.diagonal(),UnProduitMatriceVecteur = A.dot(x) = A._mul_vector(x),...
linalg : algèbre linéaire pour des matrices morses (sous-modules :
eigen (valeurs propres), isolve (méthodes itératives), dsolve
(méthodes directes).
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
scipy.sparse.linalg
matmat, matvec,
cg : gradient conjugué,
bicg : gradient bi-conjugué,
bicgstab : gradient biconjugué stabilisé,
cgs : gradient conjugué carré,
eigs, eigsh : valeurs et vecteurs propres d’une matrice carrée stockéemorse non herm. et herm. (Arpack),
factorized : LU,
gmres, lgmres : minimisation du résidu généralisé,
lobpcg : valeurs propres (utilisant un préconditionnement),
lsqr : Large sparse QR,
minres : (experimental)
qmr : quasi-minimisation du résidu,
splu, spilu : LU et LU incomplet (SuperLU).
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Qq exemples
Pour A une matrice stockée morse(stockage au format CSC ou CSR pour Umfpack) :
>>> [Val, Vect] = sp_sp.linalg.eigs(A, k = 10) # les 10 premières v.p.,
>>> sp_sp.linalg.use_solver(useUmfpack = True) # ... sinon SuperLU>>> solve = sp_sp.linalg.factorized( A ) # factorisation LU>>> x1 = solve( b1 ) # descente-remontée, b1 scd. membre,>>> x2 = solve( b2 ) # même chose sur un autre scd membre.
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Visualiser sous Python
Matplotlib (courbes, images ... haute qualité, 2D),autres (plutôt orienté 3D, vtk) : Mayavi, Paraview,...
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Matplotlib (1/4) : un point de vue.
Visualisation 2D de qualité (png, pdf, eps, ...),Matlab-like (pylab : pyplot + numpy),intégration de commandes LaTeX,doc. bien faite (http://matplotlib.sourceforge.net/).
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Matplotlib (2/4) : visu. intéractive.
[wilk@localhost ∼]$ python
import numpy as npimport m a t p l o t l i b . pyp lo t as p l t
x = np . ar ray ( [ 0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ] )y = x∗x
p l t . f i g u r e ( )
p l t . subp lo t (211)
p l t . p l o t ( x , y , co l o r = ’ r ’ )p l t . t i t l e ( ’ T i t r e 1 ’ , co l o r = ’ g ’ )
p l t . subp lo t (212)
p l t . p l o t ( x , y , marker= ’ o ’ )p l t . t i t l e ( ’ T i t r e 2 ’ , co l o r = ’ b ’ )
p l t . show ( )
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Matplotlib (3/4) : sauvegarde auto. png, ...[wilk@localhost ∼]$ python
import numpy as npimport m a t p l o t l i b . pyp lo t as p l timport m a t p l o t l i b as mpl
# Pour avo i r du tex te ( t i t r e ) en LaTeXmpl . rc ( ’ t e x t ’ , usetex=True )
x = np . ar ray ( [ 0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ] )y = x∗x
p l t . ion ( ) # mode dynamique ( non s tandar t )
p l t . f i g u r e ( )
p l t . p l o t ( x , y , marker= ’ o ’ )p l t . x l im (2 , 8)
p l t . t i t l e ( r ’ $ \ varph i$ en \ LaTeX ’ )
p l t . draw ( )
p l t . save f ig ( ’ image . png ’ )
p l t . i o f f ( ) # pour r e v e n i r en mode s tandar t
et aussi : plt.imshow, plt.colorbar,plt.legend, ...
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Matplotlib (4/6) : nos exemples
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Matplotlib (4/6) : nos exemples (1/9)
[wilk@localhost ∼]$ python
# −∗− coding : u t f−8 −∗−import numpy as npimport m a t p l o t l i b . pyp lo t as p l timport m a t p l o t l i b as mpl
n_ l ig , n_col = 3 , 4 ; num = 1
p l t . ion ( ) # p l t . i o f f ( ) : mode dynamique ou s tandar tp l t . f i g u r e (num=1 , f i g s i z e =(16 , 8 ) ) # cr é a t i on d ’ une f i g u r ep l t . c l f ( ) # On n e t t o i e l a f i g u r e
# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−p l t . subp lo t ( n_ l ig , n_col , num) ; num += 1x = np . l i nspace (0 , np . p i , 10 )y = np . l i nspace (0 , np . p i , 10 )[X,Y ] = np . meshgrid ( x , y )p l t . qu ive r (X,Y, np . cos (X) , np . s in (Y ) )
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.50.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Matplotlib (4/6) : nos exemples (2-3/9)
[wilk@localhost ∼]$ python
p l t . subp lo t ( n_ l ig , n_col , num, po la r=True ) ; num += 1r = np . arange (0 , 3 .0 , 0 .01) ; the ta = 2∗np . p i∗ rp l t . po la r ( theta , r )
0°
45°
90°
135°
180°
225°
270°
315°
0.51.01.52.02.53.0
[wilk@localhost ∼]$ python
p l t . subp lo t ( n_ l ig , n_col , num) ; num += 1x = np . arange (0 ,20 ,1 )p l t . bar ( x , x )
0 5 10 15 200
5
10
15
20
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Matplotlib (4/6) : nos exemples (4-5/9)[wilk@localhost ∼]$ python
p l t . subp lo t ( n_ l ig , n_col , num) ; num += 1x = np . arange (0 ,20 ,1 )p l t . semilogy ( x , np . exp ( x ) )p l t . g r i d ( )# v o i r auss i : p l t . semilogx
0 5 10 15 20100
101
102
103
104
105
106
107
108
109
[wilk@localhost ∼]$ python
p l t . subp lo t ( n_ l ig , n_col , num) ; num += 1n = 256x = np . l i nspace (−3, 3 , n )y = np . l i nspace (−3, 3 , n )[X, Y ] = np . meshgrid ( x , y )def f ( x , y ) :
return (1 − x / 2 + x ∗∗ 5 + y ∗∗ 3) ∗ np . exp(−x ∗∗ 2 −y ∗∗ 2)p l t . con tou r f (X, Y, f (X, Y) , 8 , cmap=" hot " )C = p l t . contour (X, Y, f (X, Y) , 8 , co lo rs = ’ b lack ’ , l i n e w i d t h = .5 )p l t . c l a b e l (C, f o n t s i z e =10)# v o i r auss i : p l t . contour
3 2 1 0 1 2 33
2
1
0
1
2
3
-0.500
-0.250
0.000
0.2500.5
00
0.500 0.750
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Matplotlib (4/6) : nos exemples (6-7/9)[wilk@localhost ∼]$ python
ax1 = p l t . subp lo t2g r i d ( ( 3 , 4 ) , (1 , 1 ) , colspan =2) ; num += 2the ta = np . l i nspace ( 1 . e−9, 2∗np . pi , 100 , endpoint=False )xc = 3∗np . cos ( the ta )yc = 1∗np . s in ( the ta )t r i a n g = mpl . t r i . T r i a n g u l a t i o n ( xc , yc )Z = ( t r i a n g . x∗∗2 + t r i a n g . y∗∗2)p l t . ax is ( ’ equal ’ ) # même dimension en x qu ’ en y ( un ce rc le sera rond )p l t . ax is ( " o f f " )p l t . t r i c o n t o u r f ( t r i ang , Z ,20 )
[wilk@localhost ∼]$ python
p l t . subp lo t ( n_ l ig , n_col , num) ; num += 1phi = 100 + 10 ∗ np . random . randn (1000)n , bins , patches = p l t . h i s t ( phi , 20 , co l o r = " green " )# v o i r auss i : p l t . h i s t2d
60 70 80 90 100 110 120 1300
20
40
60
80
100
120
140
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Matplotlib (4/6) : nos exemples (8-9/9)[wilk@localhost ∼]$ python
ax2 = p l t . subp lo t2g r i d ( ( 3 , 4 ) , (2 , 0 ) , colspan =3) ; num += 3x = np . arange (0 ,10 ,1 )p l t . p l o t ( x , x , co l o r = " red " , marker= "<" , l a b e l = " $x$ " )p l t . p l o t ( x , x∗∗2, co l o r = " green " , marker= " o " , l a b e l = " $x^2$ " )p l t . p l o t ( x , x∗∗3, co l o r = " blue " , marker= ">" , l a b e l = " $x^3$ " )p l t . legend ( loc=" upper l e f t " )p l t . x l im (2 , 8)p l t . x l a b e l ( " abscisse " )
2 3 4 5 6 7 8abscisse
0
100
200
300
400
500
600
700
800x
x2
x3
[wilk@localhost ∼]$ python
p l t . subp lo t ( n_ l ig , n_col , num) ; num += 1#M1 = np . arange (0 ,256 ,1 ) . reshape ( [ 1 6 , 1 6 ] )# p l t . ax is ( " o f f " )image = p l t . imread ( " An t i l ope . png " )p l t . imshow ( image [ : , : , 0 ] , cmap=" gray " ) ; p l t . co lo rba r ( ) ; p l t . draw ( )# v o i r auss i : cmap=" hot " , cmap=" j e t " , . . .# v o i r auss i : p l t . imread , p l t . imsave
0 100 200 300 400 500
0
100
200
300
400
500 0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Matplotlib (5/6) : le 3D, un exemple
[wilk@localhost ∼]$ python
import numpy as npimport m a t p l o t l i b . pyp lo t as p l tfrom m p l _ t o o l k i t s . mplot3d import Axes3D
def l o renz ( x , y , z , s=10 , r =28 , b=2.667) :" " " x_pt , y_pt , z_pt " " "return ( s∗( y − x ) , r∗x − y − x∗z , x∗y − b∗z )
T = 10. ; d t = 0.01 ; npas = i n t (T / d t )
x , y , z = np . zeros ( [ 3 , npas ] )
# Condi t ions i n i t i a l e sx [ 0 ] , y [ 0 ] , z [ 0 ] = ( 0 . , 1 . , 1 .05)
for i in xrange ( npas−1) :x_pt , y_pt , z_pt = lo renz ( x [ i ] , y [ i ] , z [ i ] )x [ i +1] = x [ i ] + x_pt∗dty [ i +1] = y [ i ] + y_pt∗dtz [ i +1] = z [ i ] + z_pt∗dt
f i g = p l t . f i g u r e ( )ax = f i g . gca ( p r o j e c t i o n = ’ 3d ’ )ax . p l o t ( x , y , z ) ; ax . s e t _ t i t l e ( " A t t r a c t e u r de Lorenz " )p l t . show ( )p l t . save f ig ( " . . / PS/7 e_ Ma tp l o t l i b . pdf " )# v o i r auss i : ax . p lo t_sur face , ax . p lo t_w i re f rame
10 5 0 5 10 15 2010
010
20
10
20
30
40
50
Attracteur de Lorenz
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Matplotlib (6/6) : Bcp d’autres exemples.
Site web : http://matplotlib.sourceforge.net/gallery.html
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
Python pour le calculscientifique
O. Wilk
Introduction
Des basesCommentaires, chaines
Listes
Types et opérations
Entrée - Sortie
Fonctions
Le calcul scientifiqueNumpy
Scipy
scipy.sparse
La visualisationMatplotlib
Bibliographie
Bibliographie
Pierre Puiseux, Université de Pau et des Pays de l’Adour, Traduction française du tutoriel écrit parGuido Van Rossum http : //python.developpez.com/cours/TutoVanRossum/.
Exposés journée Python à Autrans, 2010 : Sylvain Faure, Loïc Gouarin, Thierry Dumont, PierreRaybaut
O. Wilk: Python pour le calcul scientifique Calcul scientifique/Math/Cnam
top related