Documente Academic
Documente Profesional
Documente Cultură
In i ti ati on
Tristan Colombo
Objectifs
Développer des applications effectuant :
- des calculs scientifiques
- des affichages de données sous forme de
diagrammes ou de graphiques.
Pré-requis :
- Savoir développer en Python
- Connaissances mathématiques
http://www.xkcd.com/353
Linux Pratique HS n°23
Février/Mars 2012
« Préfère : la beauté à la laideur,
l’explicite à l’implicite,
le simple au complexe
et le complexe au compliqué, (...) »
Support / Maintenance
= initialement 2 ans
Duck Typing
Les Nombres Les Flottants
8 7.99999999
Les Nombres Les Flottants
En machine : n = (-1)s x m x be
s : signe du nombre (0 : nombre positif, 1 : nombre
négatif
m : mantisse – nombre « définissant » le réel.
Ex : 12.5 = 1.25 x 101, 1.25 est la mantisse
b : la base (en machine b=2).
e : l'exposant (variation de la position de la virgule)
0.7 en machine :
0 011111110 01100110011001100110011
Conversion : 0.699999988079...
la représentation machine est un arrondi !
C
Fonctions
Les fonctions originales
Définir une fonction :
def nom_fonction():
Exemple :
def affiche_hello():
print("hello")
Définir une fonction avec des paramètres :
def nom_fonction(param_1, ..., param_n):
Exemple :
def somme(a, b):
return a+b
return pour renvoyer une valeur (absence = None)
Fonctions
Les fonctions originales
Paramètres par défaut
Uniquement sur les derniers paramètres
def nom_fonction(a, b, c=2, d=3):
...
Exemples :
def exemple(a): def exemple2(liste, elt):
a=a+1 liste.append(elt)
a=1 liste=[ ]
exemple(a) exemple2(liste, 3)
=> a vaut toujours 1 => liste vaut [3]
Fonctions
Les fonctions originales
- Éditeur Spyder
Spyder
Environnement de Développement Intégré
- objectif : remplacer Matlab
Enthought
Enthought Python Distribution
- Éditeur à déterminer
Numpy Scipy Matplotlib
Partie 1
m py
Nu
Math
Module standard
Pas d'installation
Utilisation
import math ou import cmath
Fonctions classiques
Math
cos(x), sin(x), tan(x), asin(x), acos(x), atan(x),
hypot(x, y) = sqrt(x**2 + y**2)
Constantes
pi = 3.14159...
e = 2.71828...
Valeurs particulières
Math
En cas de dépassement mémoire
inf : Infini (mécanisme de protection)
OverflowError : Erreur de débordement
nan : N'est pas un nombre (calcul impossible)
Calcul matriciel
Installation
Paquetage python-numpy ou python3-numpy
Source
http://sourceforge.net/projects/numpy/files/
NumPy/
Numpy
Introduit deux nouveaux types de données
- Tableaux
Opérations simultanées sur l'ensemble des
données
Exemple
import numpy
a = numpy.array([1, 2, 4, 8, 16])
a**2
>> array([1, 4, 16, 64, 256])
Numpy
Quelques tableaux particuliers :
taille donnée sous forme de tuple (lignes,
colonnes) ou simple entier pour colonnes
zeros(taille)
ones(taille)
empty(taille) Exemples
identity(taille) x = numpy.ones((2, 3))
>> array([[ 1., 1., 1.],
[ 1., 1., 1.]])
x = numpy.identity(2)
>> array([[ 1., 0],
[ 0, 1.])
Numpy
Accès aux éléments comme dans une
liste (accès plus rapide)
Exemple
x = numpy.array([[1, 2, 3], [4, 5, 6]])
>> x[0][1]
2
>> x[0,1]
2
Numpy
Modification des éléments comme dans une
liste + accès direct colonnes et lignes
Exemples
x = numpy.array([[1, 2, 3], [4, 5, 6]])
>> x[0,1] = 10 # Sélection de l'élément (0,1)
>> x[0] = 0 # Sélection de la première ligne
array([[0, 0, 0],
[4, 5, 6]])
>> x[:,0] = 8 # Sélection de la première colonne
array([[8, 2, 3],
[8, 5, 6]])
Atelier 4ion
u l a t
a n i p x
M l ea u
e t a b
d
Manipulation de tableaux
1234 13
A=5 6 7 8 B=5 7
4321 42
Solution :
A = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8], [4, 3, 2, 1]])
B = A[ :,::2]
Numpy
Connaître la taille d'un tableau : shape
x = numpy.array([[1, 2, 3], [4, 5, 6]])
x.shape
>>> (2, 3)
Exemple
import numpy
Résoudre (méthode de Cramer) :
3x – 2y + 4z = -7
5x + 7y – 3z = 16
x+ y– z=6
Rappel : A.X = K
A matrice des coefficients
K matrice des constantes
A => A où la kième colonne est remplacée par K
Solution : x = det(A ) / det(A)
Les boucles
Numpy
Vectorisation des opérations :
Boucles implicites sur tableaux :
>>>a = numpy.arange(0, numpy.pi, numpy.pi/8).reshape((2,4))
>>> numpy.cos(a)
Exemple :
>>> a = numpy.matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
>>> numpy.vsplit(a, 2)
[matrix([[0, 1, 2],
[3, 4, 5]]), matrix([[ 6, 7, 8],
[ 9, 10, 11]])]
Numpy
Types de données spécifiques dans un tableau:
- Paramètre dtype lors de la création
Étapes :
- Créer un objet dtype :
dt = numpy.dtype([('nom', 'S5'), ('age', 'i')])
- Créer la matrice :
a = numpy.matrix([('Richard', 4), ('Linus', 5)], dtype=dt)
Installation
Paquetage python-scipy ou python3-scipy
Source
http://sourceforge.net/projects/scipy/files/scipy/
Scipy
Boîte à outil ou couteau suisse scientifique
Contient de nombreux sous-modules
fftpack pour transformées de Fourier
linalg pour l'algèbre linéaire
signal pour le traitement du signal
Intégration, statistiques, clustering,
traitement des images, etc.
Voir http://docs.scipy.org/doc/scipy/reference/np-
modindex.html
Aide par info() :
import scipy as s
s.info('fft')
Constantes scientifiques
Scipy
import scipy
import scipy.constants as const
dir(const)
Exemple :
# Nombre d'Avogadro
print const.N_A
import scipy
import scipy.integrate
scipy.info(scipy.integrate.quad)
Interpolation
Scipy
import scipy
import scipy.interpolate
x = scipy.linspace(0, 1, 10)
y = np.sin(2*scipy.pi*x)
linear_interp = scipy.interpolate.interp1d(x, y) #par defaut,
# interpolateur lineaire
cubic_interp = scipy.interpolate.interp1d(x, y, kind='cubic')
#interpolateur cubique
fine_x = np.linspace(0, 1, 50)
y_fromlinearinterp = linear_interp(fine_x)
y_fromcubicinterp = cubic_interp(fine_x)
Interpolation
Scipy
Matrices creuses avec Sparse
Scipy
Différents types disponibles :
- csc_matrix : Compressed Sparse Column
- coo_matrix : Coordinate
- dia_matrix : Diagonal, etc.
import scipy.sparse
import scipy
A = scipy.array([[1, 0, 2], [0, 3, 0]])
A = scipy.csc_matrix(A)
... calculs
A = A.todense()
Lecture / Ecriture de matrices
Scipy
- matrices Python
Exemple :
>>> import sympy
>>> x = sympy.Symbol('x')
>>> y = sympy.Symbol('y')
>>> x+y+x**2+y
x**2 + x + 2*y
Sympy
Calculs algébriques
>>> sympy.expand((x+y)**3)
x**3 + 3*x**2*y + 3*x*y**2 + y**3
>>> sympy.simplify((x+x*y)/x)
y+1
>>> sympy.limit(1/x, x, 'oo')
0
>>> sympy.series(sympy.cos(x), x)
1 - x**2/2 + x**4/24 + O(x**6)
>>> sympy.solve([x + 5*y - 2, -3*x + 6*y - 15], [x, y])
{x: -3, y: 1}
Sympy
Calcul matriciel
>>> A = sympy.Matrix([[1, x], [y, 1]])
>>> A
[1, x]
[y, 1]
Atelier 10
li q ue
m bo
ul s y y
Cal c ym p
v ec S
a
Calcul symbolique avec Sympy
http://scikit-learn.org/stable/
Module Python
Installation
Enthought Tools Suite
Source :
https://svn.enthought.com/enthought/wiki/Install
Commande checkout : python ets.py co
Attention : Très long !
Paquetages Debian
mayavi2
Mayavi2
Mayavi2
Exemple
x = [1, 2, 3, 4, 5, 6]
y = [0, 0, 0, 0, 0, 0]
z=y
s = [.5, .6, .7, .8, .9, 1]
Documentation :
http://networkx.lanl.gov/contents.html
Installation
sudo pip install -U networkx
Source http://pypi.python.org/packages/source/n/
networkx/
Networkx
Exemple :
import pylab as plt
import networkx as nx
G=nx.Graph()
G.add_edge(1, 2)
G.add_edge(1, 3)
G.add_node(4)
nx.draw(G)
plt.show()
Pandas
Python Data Analysis Library
http://pandas.pydata.org/
http://statsmodels.sourceforge.net/
Partie 3 tl i b
p lo
Ma th
Matplotlib
Graphiques scientifiques en 2D
Installation
Paquetage python-matplotlib
Source
http://sourceforge.net/projects/matplotlib/files/
matplotlib/
Matplotlib
Import par
import pylab as pl ou from pylab import *
import matplotlib.pyplot as pl # sous-module graphes
Graphe simple
import pylab as pl
Exemple :
import pylab as pl
Exemple
import pylab as pl
Exemple
import pylab as pl
y = [13,11,13,12,13,10,30,12,11,13,12,11,13,12]
pl.plot(y)
pl.ylim(ymax=35)
pl.annotate('Point remarquable...', xy=(6, 30),
xytext=(8,31.5), arrowprops=dict(facecolor='black',
shrink=0.05))
pl.show()
Matplotlib
shrink=espace
xy
xytext
Matplotlib
Pour afficher plusieurs courbes :
pl.plot(x, y, ...)
Tend vers 0
Les boucles
Matplotlib
Plusieurs origines possibles pour les données :
- base de données
- fichiers (CSV, etc)
- Web
Structure classique :
- en-tête
- sections
- mot-clé en début de ligne
- identifiant puis valeur
- colonnes de données séparées par un caractère
Les fichiers
3 étapes
Les fichiers
1
Ouverture du fichier et création de l'objet-fichier
2 Traitement
Écriture Fin d e
a
f
î
ich
= ide
n e v
fic.write("À écrire dans le fichier") Ch
Lecture
- Tout le fichier
texte = fic.read()
- Les 10 premiers caractères
texte = fic.read(10)
- Une ligne
ligne = fic.readline()
- Toutes les lignes dans une liste
lignes = fic.readlines()
Les fichiers
3
Fermeture du fichier
fic.close()
Atelier 17 s
i er
e s f ich
L
Les fichiers
[article]
author = Tristan Colombo
title = Manipulation de fichiers avec Python
Les fichiers
Utilisation du module ConfigParser :
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('lp.ini')
print parser.get('web', 'name')
Atelier 18
e ap h r
Gr i c hi e
u n f
pui s
de
Graphe depuis un fichier
3. Matplotlib
Numpy Scipy Matplotlib
support@info2dev.com
Bibliographie