DIRECTION DES SCIENCES DE LA MATIERE
Département de Recherche sur l’Etat Condensé, les Atomes et les Molécules
Laboratoire Interdisciplinaire sur l’Organisation Nanométrique et Supramoléculaire
Inititiation à
l’utilisation scientifique de Python
Cours Utilisation scientifique de Python O. Taché
Plan
• Philosophie de Python
• Quelques éléments de syntaxe
– Types
– Conditions
– Boucles
– Fichiers
– Fonctions
• Modules
– Son propre module
– Modules scientifiques
– Tableaux
• Tracé de courbes
– Introduction à Gnuplot
– Interface avec Python
Cours Utilisation scientifique de Python O. Taché
Philosophie de Python
• Langage de programmation « simple » qui
permet de se concentrer sur l’application
scientifique et pas la syntaxe
• Interface avec d’autres langages (Fortran, C,…)
• Interfaçage avec de nombreuses librairies
graphiques (Tkinter par défaut)
• Portable (utilisable sous unix, mac, pc,…)
• Orienté Objet et donc évolutif
• Open Source et gratuit
Cours Utilisation scientifique de Python O. Taché
Philosophie de Python : Interpréteur de
commande
additionner 2 valeurs
>>> 1 + 1
2 On peut aussi créer un programme
affecter une variable sans l’interpréteur
>>> a = 1
>>> a
1 Il suffit de lancer l’interpréteur python :
Chaîne de caractère [Link] [Link]
>>> s = “hello world”
>>> print s
hello world
Calculatrice scientifique très puissante
Cours Utilisation scientifique de Python O. Taché
Philosophie de Python : Modulaire
• Python est orienté objet
• De nombreux modules sont disponibles :
– Scientifique
– Imagerie
– Réseaux
– Interfaces graphiques
–…
• Documentés facilement (grâce à pyDoc)
Cours Utilisation scientifique de Python O. Taché
Aspects du langage
• Indentation importante:
If n in range(1,10):
Print n
Print ‘fini’
• Documentation
– Commentaires précédés de #
– Ou bien ’’ ’’ ’’
Cours Utilisation scientifique de Python O. Taché
Affectation des variables
• Pas de déclaration des variables x 1 2 3
• Comment affecter une variable ?
>>>x=[1,2,3]
• Une variable se réfère à une zone y
mémoire
>>>Y=X
• Deux variables peuvent de référer à la
x 1 0 3
même zone mémoire
>>>X[1]=0
y
>>>Print y
[1,0,2]
• Réaffecter une variable :
x 1 2 3
>>>y=[3,4]
y 3 4
Cours Utilisation scientifique de Python O. Taché
booleens
• True ou False
>>>test=true
>>>if test :
Print « vrai »
Vrai
Cours Utilisation scientifique de Python O. Taché
Nombres
Entier (int) 0, 1, 2, 3, -1, -2, -3
Real (float) 0., 3.1415926, -2.05e30, 1e-4
(doit contenir . ou exposant)
Complex 1j, -2.5j, 3+4j
• Addition 3+4, 42.+3, 1+0j
• soustraction 2-5, 3.-1, 3j-7.5
• Multiplication 4*3, 2*3.14, 1j*3j
• Division 1/3, 1./3., 5/3j
• Puissance 1.5**3, 2j**2, 2**-0.5
Cours Utilisation scientifique de Python O. Taché
Chaines de caractères (string)
• ‘’abc’’ ou ‘abc’
• ‘\n’ retour à la ligne
• ‘abc’+’def’ ‘abcdef’
• 3*’abc’ ‘abcabcabc’
• ’ab cd e’.split() [’ab’,’cd’,’e’]
• ’1,2,3’.split(’,’) [’1’, ’ 2’, ’ 3’]
• ’,’.join([’1’,’2’]) ’1,2’ ajoute , entre les éléments
• ’ a b c ’.strip() ’a b c’ enlève les espaces de fin et début
• ’text’.find(’ex’) 1 #recherche
• ’Abc’.upper() ’ABC’
• ’Abc’.lower() ’abc’
• Conversion vers des nombres: int(’2’), float(’2.1’)
• Conversion vers du texte : str(3), str([1, 2, 3])
Cours Utilisation scientifique de Python O. Taché
Listes ou séquences (list)
• Création • Définition d’un élément
>>>a=[1,2,3, ’blabla’,[9,8]] >>> a[1]=1
• Concatenation (pas addition… voir array) >>> a
>>>[1,2,3]+[4,5] [1, 1, 3, 'blabla', [9, 8], 'test']
[1,2,3,4,5]
• Ajout d’un élément • Indices négatifs
>>>[Link]('test') >>> a[-1]
[1,2,3, ’blabla’,[9,8],’test’] 'test'
• Longueur >>> a[-2]
>>>len(a) [9, 8]
7
• range([start,] stop[, step]) -> list of • Parties d’une liste (liste[lower:upper])
integers >>>a[1:3]
Return a list containing an arithmetic [2,3,’blabla’]
progression of integers.
>>> a[:3]
>>>range(5)
[1, 1, 3]
[0,1,2,3,4]
• Indexation simple
>>>a[0]
1 Les indices commencent toujours à 0
• Indexation multiple
>>> a[4][1]
8
Cours Utilisation scientifique de Python O. Taché
>>>Help(list)
| append(...)
| [Link](object) -- append object to end
|
| count(...)
| [Link](value) -> integer -- return number of occurrences of value
|
| extend(...)
| [Link](iterable) -- extend list by appending elements from the iterable
|
| index(...)
| [Link](value, [start, [stop]]) -> integer -- return first index of value
|
| insert(...)
| [Link](index, object) -- insert object before index
|
| pop(...)
| [Link]([index]) -> item -- remove and return item at index (default last)
|
| remove(...)
| [Link](value) -- remove first occurrence of value Usage :
|
| reverse(...) >>>[Link](var)
| [Link]() -- reverse *IN PLACE*
|
| sort(...)
| [Link](cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1
Cours Utilisation scientifique de Python O. Taché
Dictionnaires
Dictionnaire : Association d’une valeur et d’une clé.
• Création d’un dictionnaire
>>> dico = {}
>>> dico[‘C’] = ‘carbone’
>>> dico[‘H’] = ‘hydrogène’
>>> dico[‘O’] = ‘oxygène’
>>> print dico
{‘C': ‘carbone', ‘H': ‘hydrogène’, ‘O': ‘oxygène'}
• Utilisation
>>>print dico[‘C’]
Carbone
• Création d’un nouveau dictionnaire
>>> dico2={'N':'Azote','Fe':'Fer'}
• Concaténation de dictionnaires
>>> dico3=dico+dico2
Traceback (most recent call last):
File "<pyshell#18>", line 1, in -toplevel-
dico3=dico+dico2
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
>>> [Link](dico2)
>>> dico
{'H': 'hydrogène', 'C': 'carbone', 'Fe': 'Fer', 'O': 'oxygène', 'N': 'Azote'}
Cours Utilisation scientifique de Python O. Taché
>>>help(dict)
| clear(...) | pop(...)
| [Link]() -> None. Remove all items from D. | [Link](k[,d]) -> v, remove specified key and return the
| corresponding value
| copy(...) | If key is not found, d is returned if given, otherwise
| [Link]() -> a shallow copy of D KeyError is raised
| |
| get(...) | popitem(...)
| [Link](k[,d]) -> D[k] if k in D, else d. d defaults to None. | [Link]() -> (k, v), remove and return some (key, value)
| pair as a
| has_key(...) | 2-tuple; but raise KeyError if D is empty
| D.has_key(k) -> True if D has a key k, else False | |
| items(...) | setdefault(...)
| [Link]() -> list of D's (key, value) pairs, as 2-tuples | [Link](k[,d]) -> [Link](k,d), also set D[k]=d if k not in D
| |
| iteritems(...) | update(...)
| [Link]() -> an iterator over the (key, value) items of D | [Link](E) -> None. Update D from E: for k in [Link]():
| D[k] = E[k]
| iterkeys(...) |
| [Link]() -> an iterator over the keys of D | values(...)
| | [Link]() -> list of D's values
| itervalues(...) |
| [Link]() -> an iterator over the values of D
|
| keys(...)
| [Link]() -> list of D's keys
Cours Utilisation scientifique de Python O. Taché
Conditions
Exemples :
if test=True
<condition>: if test:
print 'vrai'
<code> else:
print 'faux'
elif ->vrai
<condition>:
if i==1:
<code> print
elif i==2:
'A'
else: print
elif i==3:
'B'
<code> else:
print 'C'
print "?"
Cours Utilisation scientifique de Python O. Taché
Boucles for loop
for <variable> in <list>:
<code>
>>> for i in range(5): >>> for i in dico:
print i, print i,
0 1 2 3 4
H C Fe O N
>>> for i in 'abcdef': >>> for i in dico:
print i, print dico[i],
a b c d e f
l=['C','H','O','N'] hydrogène carbone Fer
>>> for i in l: oxygène Azote
print i,
C H O N
Cours Utilisation scientifique de Python O. Taché
Boucles while
while <condition>:
<instructions>
Exécution répétée d’instructions en fonction d’une condition
>>> test=0 >>> i = 0
>>> while test<10: >>> while 1:
test=test+1 if i<3 :
print i,
print test,
else :
break
i=i+1
1 2 3 4 5 6 7 8 9 10
0 1 2
Cours Utilisation scientifique de Python O. Taché
Lecture des fichiers textes
• Rappel sur les fichiers textes :
– Ouverture du fichier
– Lecture ligne à ligne
– La ligne est affectée à une variable texte X,Y
– Fermeture du fichier
1,2
• En Python :
>>>f=open(‘nom_du_fichier.txt’,’r’) 2,4
>>>lignes=[Link]()
>>>[Link]() 3,6
L’instruction readlines affecte toutes les lignes du fichier dans une
liste.
• Chaque élément de la liste doit désormais être traité. 1,2
Dans le fichier il y a 2 colonnes x et y séparés par une ,
>>>x=[ ] #liste
>>>y=[ ]
>>>for chaine in lignes[1:]:On ne prend pas la 1ere ligne
elements=[Link](’,’) 1 2
[Link](float(element[0]))
[Link](float(element[1]))
Cours Utilisation scientifique de Python O. Taché
Ecriture des Fichiers
• Rappel sur les fichiers textes :
– Ouverture du fichier
– écriture ligne à ligne
– Fermeture du fichier
• En Python :
>>>f=open(‘nom_du_fichier.txt’,’w’)
>>>[Link](‘ligne1\n’)
>>>[Link](‘ligne2\n’)
>>>f=close()
Cours Utilisation scientifique de Python O. Taché
Fonctions
• Syntaxe :
def nomdelafonction(arguments):
instructions
return quelquechose
>>> def addition(a,b):
c=a+b
return c
>>> addition(2,3)
5
>>> addition('nom','prenom')
'nomprenom'
>>> addition(1.25,5.36)
6.6100000000000003
Cours Utilisation scientifique de Python O. Taché
Modules
• Créer son propre module:
[Link] : Un module qui s’execute :
def addition(a,b): # Ajouter ce code à la fin
c=a+b if __name__ == ‘__main__’:
return c test()
• Utiliser un module
>>>import exo1
>>>[Link](1,2)
3
• Recharger le module
>>>reload(exo1)
• Utiliser quelques parties d’un module
>>>from Numeric import array
• Utiliser tous les composants d’un module
>>>from Numeric import *
>>>import Numeric as N Plus propre parce que l’on sait quelle
>>> [Link](3.14) module est utilisé…
0.0015926529164868282
Cours Utilisation scientifique de Python O. Taché
Modules numeric et scientific
• Numerical Python
– Nouveau type array (tableau)
– Fonctions mathématiques universelles permettant de les
manipuler
>>>import Numeric
• Scientific Python
– Collection de modules pour le calcul scientifique puissantes et
complètes
>>>import Scientific
• Scipy
– « Fourre-tout » de modules scientifiques
– Fonctionalités de plotting (?!)
– Interface genre matlab
Cours Utilisation scientifique de Python O. Taché
Fonctions de Scientific
• PACKAGE CONTENTS
• BSP (package)
• DictWithDefault
• Functions (package)
• Geometry (package)
• IO (package)
• Installation
• MPI (package)
• Mathematica
• NumberDict
• Physics (package)
• Signals (package)
• Statistics (package)
• Threading (package)
• TkWidgets (package)
• Visualization (package)
Cours Utilisation scientifique de Python O. Taché
Type tableau (array)
• Attention, c’est différent d’une liste
(sequence) • Addition de tableaux
>>> t=[Link]([1,2,3,4.])
• Création d’un tableau :
>>> [Link]([1,2,3,4]) >>> t2=[Link]([1,2,3,4.])
array([1, 2, 3, 4]) >>> t+t2
>>> [Link]([1,2,3,4.]) array([ 2., 4., 6., 8.])
array([ 1., 2., 3., 4.])
>>> [Link](0,20,2) • Utilisation de fonctions mathématiques
array([ 0, 2, 4, 6, 8, 10, >>> t=[Link](0,10,2)
12, 14, 16, 18]) >>> t
array([0, 2, 4, 6, 8])
>>> t*[Link]
• Création d’un tableau à partir d’une
liste array([0.,6.28318531, 12.56637,
>>> l=range(1,10) 18.84955592, 25.13274123])
>>> a=[Link](l)
>>> a
array([1, 2, 3, 4, 5, 6, 7, 8,
9])
Cours Utilisation scientifique de Python O. Taché
Type tableau (array)
• Tableaux à plusieurs dimensions
>>> t=[Link](0,15)
>>> [Link]
(15,)
>>> tableau2d=[Link](t,(3,5))
>>> tableau2d
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
• Accès aux données
>>> tableau2d[0,3]
3
Attention tableau[y,x] !!!
• Parties
>>> tableau2d[:,3]
array([ 3, 8, 13])
Cours Utilisation scientifique de Python O. Taché
Fonctions array
Functions More Functions:
- array - NumPy Array construction - arrayrange (arange) - Return regularly spaced array
- zeros - Return an array of all zeros - asarray - Guarantee NumPy array
- shape - Return shape of sequence or array - sarray - Guarantee a NumPy array that keeps precision
- rank - Return number of dimensions - convolve - Convolve two 1-d arrays
- size - Return number of elements in entire array or a - swapaxes - Exchange axes
certain dimension - concatenate - Join arrays together
- fromstring - Construct array from (byte) string - transpose - Permute axes
- take - Select sub-arrays using sequence of indices - sort - Sort elements of array
- put - Set sub-arrays using sequence of 1-D indices - argsort - Indices of sorted array
- putmask - Set portion of arrays using a mask - argmax - Index of largest value
- reshape - Return array with new shape - argmin - Index of smallest value
- repeat - Repeat elements of array - innerproduct - Innerproduct of two arrays
- choose - Construct new array from indexed array tuple - dot - Dot product (matrix multiplication)
- cross_correlate - Correlate two 1-d arrays - outerproduct - Outerproduct of two arrays
- searchsorted - Search for element in 1-d array - resize - Return array with arbitrary new shape
- sum - Total sum over a specified dimension - indices - Tuple of indices
- average - Average, possibly weighted, over axis or array. - fromfunction - Construct array from universal function
- cumsum - Cumulative sum over a specified dimension - diagonal - Return diagonal array
- product - Total product over a specified dimension - trace - Trace of array
- cumproduct - Cumulative product over a specified dimension - dump - Dump array to file object (pickle)
- alltrue - Logical and over an entire axis - dumps - Return pickled string representing data
- sometrue - Logical or over an entire axis - load - Return array stored in file object
- allclose - Tests if sequences are essentially equal - loads - Return array from pickled string
- ravel - Return array as 1-D
- nonzero - Indices of nonzero elements for 1-D array
- shape - Shape of array
- where - Construct array from binary result
help(Numeric) - compress - Elements of array where condition is true
- clip - Clip array between two values
- zeros - Array of all zeros
help(function) - ones - Array of all ones
- identity - 2-D identity array (matrix)
Cours Utilisation scientifique de Python O. Taché
Introduction à Gnuplot
• Gnuplot n’est pas un programme Python
• Gnuplot est un logiciel permettant de tracer des courbes
(correctement !)
• En ligne de commande Æpas très convivial
• Charge des données issues de fichiers et permet
certains calculs
• Permet d’automatiser le tracé des figures
• Dispose d’un grand nombre de types de figures
• Gratuit et OpenSource
• Multiplateforme (windows, linux, mac)
• Æ Même philosophie que Python
• Python peut interfacer Gnuplot Æ le tracé est dédié à
Gnuplot
Cours Utilisation scientifique de Python O. Taché
Une courbe avec Gnuplot
Cours Utilisation scientifique de Python O. Taché
Interfaçage avec Python
Utilisation du module
[Link]
import Gnuplot
import Numeric as N
# Initialize Gnuplot
g = [Link]()
# Set up data
x = [Link](0., 5., 0.1)
y = [Link](-x) + [Link](-2.*x)
curve=[Link](x, y,with='linespoints')
[Link]('[Link](-x) + [Link](-2.*x)')
[Link](curve)
Cours Utilisation scientifique de Python O. Taché
Références
• [Link]
• Numerical Python ([Link]
• Scientific Python (Konrad Hinsen)
[Link]
n/
• [Link]
• [Link]
• Transparents inspirés de “Introduction to
Scientific Computing with Python”
• [Link]/scm/lions/python
Cours Utilisation scientifique de Python O. Taché