PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela...

174
PIP: Certification python http://www.python.org Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg 28 mars 2015 Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 1 / 174

Transcript of PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela...

Page 1: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

PIP: Certification pythonhttp://www.python.org

Marcela Szopos, Michel Mehrenberger, Laurent Navoret, PierreNavaro

Université de Strasbourg

28 mars 2015

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 1 / 174

Page 2: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

But : Interface graphique en Python.

Volume horaire : 13h cours intégré et 13h TD13 SéancesS1,S2,S4,S6,S8,S10 : 6 seances de cours, groupe completS3,S5,S7,S9,S11,S12 : 6 seances de TP, groupe dédoublé (L.Navoret/M. Mehrenberger)S13 : TP noté

Évaluation continue intégrale :1ère session : contrôle continu (TP, mini projet), coefficient 1 ;2ème session : épreuve orale.

Pour qui ?

M1 Calcul Scientifique et Mathématiques de l’Information ;M1 Mathématiques Fondamentales, parcours Recherche.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 2 / 174

Page 3: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

Séances de cours

Slides de M. Szopos : section I a XSlides complémentaires : section XI

⇒ Matériel disponible sur moodle

The Python Tutorial : à consulter/télécharger sur internet

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 3 / 174

Page 4: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

Séances de TP

Sujet de TP papier

Questions à répondre sur papier

Questions sur fichier(s), dossier...

Pour le TP noté :

Sujet papier

Rendre un seul fichier TP_Nom_Prenom.py par email ou clé usb

Rendre feuille(s) pour les questions sur papier (questionspréliminaires à la programmation, résultats, commentaires)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 4 / 174

Page 5: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

Mini-projet

Sujet parmi une liste de titresCiter les sourcesPar binômeRendu : répertoire Nom1_Nom2 (ordre alphabétique) contenant

Rapport Nom1_Nom2.pdf (pas slides) contenantLa description et motivation du sujetLa méthode utiliséeLes résultats obtenus

Fichiers et éventuellement sous-répertoires avec commentaires,README pour l’utilisation/présentation

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 5 / 174

Page 6: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

Execution de python

Méthode 1 : interactif

Lancer python ou ipython

Pour faire des petits calculs/vérifications

Attention : pas de sauvegarde

Ctrl+D ou quit() pour sortir

Méthode 2 : dans un fichier

Sauvegarder un fichier fichier.py

Utilisation d’un éditeur adapté (Ex : pycharm)

Executer ce fichier (dans la console, dans l’éditeur, en modeinteractif...)

Méthode 3 : webSzopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 6 / 174

Page 7: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Historique I

http://fr.wikipedia.org/wiki/Python_langage

∼ 1990 : première version dulangage, due à Guido Van Rossum(Centrum voor Wiskunde enInformatica (CWI), Amsterdam,Pays-Bas).

Licence : Python SoftwareFoundation Licensehttp://docs.python.org/2/license.html

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 7 / 174

Page 8: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Utilisation I

En entreprise :Google Groups Web Interface (Guido van Rossum y a travaillé,2005 – 2012) ;Nasa Workflow Automation Software ;Zope Web Application server etc.

Comme langage de commande de différents logiciels libres :Blender (logiciel de modélisation 3D) ;LibreOffice (bureautique) ;ParaView (logiciel de visualisation de données numériques) etc.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 8 / 174

Page 9: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Utilisation I

Dans le monde académique, sous forme de bibliothèquesscientifiques :

Calcul : NumPy, SciPy, PyIMSL Studio, Sympy, SAGE

Visualisation : pydot, maplotlib, pyngl, MayaVi ;

Simulation : simPy ;

Chimie : PyMOL, MMTK, Chimera, PyQuante ;

Biologie : Biopython etc.

Voir aussi :

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 9 / 174

Page 10: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Utilisation II

http://www.scipy.org/Topical_Software

http://www.enthought.com/products/epdlibraries.php

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 10 / 174

Page 11: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Avantages I

Python : langage de programmation moderne.

Programmation structurée (à l’aide de fonctions).

Programmation orientée objet (interaction de briques logiciellesélémentaires appelées “objets”).

Python : logiciel libre.

www.python.org

Python : logiciel portable (Windows, Linux, Mac OS).Installation très simple, exemple (Ubuntu) :

apt-get install python

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 11 / 174

Page 12: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Quelques caractéristiques I

Langage interprété : un programme est traduit enlangage-machine au moment de son exécution ;

en opposition avec les langages compilés (par exemple FORTRAN,C, C++), où le programme est traduit en langage-machine une foispour toutes.

Langage de haut-niveau : orienté autour du problème à résoudre ;les programmes sont écrits en utilisant des mots usuels (trèssouvent de l’anglais) et des symboles mathématiques familiers ;

à comparer avec des langages de bas niveau, où le codage serapproche du langage machine.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 12 / 174

Page 13: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Performances (merci à Pierre Navaro) I

Python n’est pas rapide ... mais :

Ce n’est pas toujours vrai.Il y a des modules performants en C/C++/Fortran. (Numpy)C’est le programmeur qui devient plus efficace.Ce qu’il faut optimiser, c’est le temps jusqu’au bout du projet.

Conseils de programmation

Ecrivez votre programme en Python d’Äôabord.Si c’est assez rapide, soyez contents.Sinon, optimisez les parties critiques (et rien d’autre).

L’optimisation trop précoce est souvent source d’erreurs.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 13 / 174

Page 14: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Exécution d’un programme Python I

Méthode 1 : en tapant les lignes du code une à une dans l’interpréteur(comme dans Matlab/Octave/Scilab).

% pythonPython 2.7.3 (default, Aug 1 2012, 05:14:39)[GCC 4.6.3] on linux2Type "help", "copyright", "credits" or "license" formore information.>>> quitUse quit() or Ctrl-D (i.e. EOF) to exit>>> quit()

Le (+) : facile pour une utilisation ponctuelle.

Le (-) : fastidieux si l’on veut ré-exécuter le programme (il faut toutre-taper).

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 14 / 174

Page 15: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Exécution d’un programme Python

Méthode 2 : utiliser un programme d’édition de texte pour sauver leprogramme dans un fichier (extension ’.py’).Quels éditeurs de texte (libres) ?

Emacs, Vim : puissants, mais nécessitent une prise en mainpréalable.

Gedit sous GNOME ou Kate sous KDE.

éditeurs dédiés à Python : DrPython, Eric3, SPE.

sous Windows (si aucun des éditeurs cités ci-dessus n’estinstallé) : le bloc-notes.

Étapes : taper le programme, le sauvegarder dans un fichier nomméprog.py, saisir la commande execfile(’prog.py’) pourl’exécuter dans l’interpréteur Python.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 15 / 174

Page 16: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

La “calculatrice” Python I

Add i t i on e t s ous t r a c t i on :

>>> 20+80100

>>> 6−51

M u l t i p l i c a t i o n :

>>> 2*510

Puissance :

>>> 5**225

D i v i s i o n vs . d i v i s i o n sans reste , n i decimales vs .

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 16 / 174

Page 17: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

La “calculatrice” Python II

d i v i s i o n avec decimales :

>>> 21/37

>>> 23/37

>>> 23 .0 /3 .07 . 6 6 6 6 . . .

Reste de l a d i v i s i o n :

>>> 49%109

Af f i chage du r e s u l t a t a l ’ ecran :

>>> p r i n t "1 + 2 est une a d d i t i o n "1 + 2 est une a d d i t i o n

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 17 / 174

Page 18: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

La “calculatrice” Python III

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 18 / 174

Page 19: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Commandes I

TABLE: Opérations Python

commande nom exemple sortie+ addition 4+5 9* multiplication 4*5 20/ division 18/3 6% reste 19%3 5** puissance 2**4 16

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 19 / 174

Page 20: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Commandes II

La priorité (ordre) des opérations est respectée (mêmes règles qu’enmaths) :

1 parenthèses ()2 puissance **3 multiplication *, division et reste4 addition + et substraction -

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 20 / 174

Page 21: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Priorité des opérations

Un exemple simple :

Code Listing 1 – Exemple 1>>> 1 + 2 * 37>>> (1 + 2) * 39

Une remarque importante : un programme source est destiné àl’être humain ! Pour en faciliter sa lecture, il doit êtrejudicieusement commenté.Un commentaire commence par le caractère # et s’étend jusqu’àla fin de la ligne.

Code Listing 2 – Exemple 2>>> # Voici un commentaire

>>> 9+2 # en voici un autre11

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 21 / 174

Page 22: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

I. INTRODUCTION

Les expressions booléennes

Deux valeurs possibles : False, True.

Opérateurs de comparaison : ==,!=, >, >=, <, <=.

Code Listing 3 – Exemple 3>>> 2 > 8 # False

>>> 2 <= 8 < 15 # True

Opérateurs logiques (concept de shortcut) : not, or, and.

Code Listing 4 – Exemple 3>>> (3==3) or (9 >24) # True (des le premier membre)

>>> (9 > 24) and (3==3) # False (des le premier membre)

Les opérateurs logiques et de comparaisons sont à valeurs dansFalse, True.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 22 / 174

Page 23: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Les données et les variables

VariableC’est un nom donné à une valeur.Informatiquement, c’est une référence à une adresse mémoire.

Remarques :Les noms des variables sont conventionnellement écrits enminuscule ; ils commencent par une lettre ou le caractère souligné(_), puis, éventuellement, des lettres, des chiffres ou encore ducaractère _.Ils doivent être différrents des mots réservés de Python :

import keywordprint "Liste des mots-cle :", keyword.kwlist

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 23 / 174

Page 24: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

L’affectation

AffectationOn affecte une variable par une valeur en utilisant le signe = ; dansune affectation, le membre de gauche reçoit le membre de droite.

Remarque : Affecter n’est pas comparer !

l’affectation a un effet mais n’a pas de valeur :>>>a=b>>>

la comparaison a une valeur mais n’a pas d’effet :>>> a==bFalse>>>

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 24 / 174

Page 25: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Instructions d’affectation : différentes formes

a=10 # forme de base

a+=1 # meme chose que a = a + 1, si a est deja connue;# avantage : si a est une expression complique, on# a besoin d’une seule evaluation de a ;# forme standard : a est evalue deux fois.

b = c = 10 # cibles multiples# (affectation de droite a gauche)

d, e, f = 1.5, 2.5, 3.5 # affectation de tuple# (par position)

g, h = h, g # echange les valeurs de g et h

m, n = [5,7] # affectation de liste (par position).

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 25 / 174

Page 26: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Typage

Python détecte automatiquement le type des variables :# definition d’un entier valant 1a=1b=a/2print b???type(b)???

# definition d’un nombre reela=1.0b=a/2print b???type(b)???

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 26 / 174

Page 27: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Typage

Python détecte automatiquement le type des variables :# definition d’un entier valant 1a=1b=a/2print b0 # division euclidienne sur les entiers, de 1 par 2.

type(b)<type ’int’>

# definition d’un nombre reela=1.0b=a/2print b0.5 # division classique sur les reels.

type(b)<type ’float’>

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 27 / 174

Page 28: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Les entrées / sorties

L’instruction input permet de saisir une entrée au clavier. Commec’est une évaluation, elle effectue un typage dynamique.>>> n = input("Entrez un entier : ")Entrez un entier : 7>>> type(n)<type ’int’>>>> n = input("Entrez un entier : ")Entrez un entier : 1.1>>> type(n)<type ’float’>

L’instruction print permet d’afficher des sorties à l’écran :>>> a=2>>> b=5>>> print("La somme a+b est : "), a+bLa somme a+b est : 7

Le séparateur virgule permet d’empêcher le retour à la ligne.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 28 / 174

Page 29: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Instructions conditionnelles

But : Contrôler une alternative.

Code Listing 5 – La syntaxe de IF - ELIF - ELSEif {conditions}:

{executer ce code}elif {conditions}:

{executer ce code}elif {conditions}:

{executer ce code}else:

{executer ce code}

Remarques :

Il est possible, après un IF de tester autant de conditions que l’onsouhaite avec des ELIF (y compris 0) ; par contre, il ne peut y avoirqu’un seul ELSE à la fin.Le caractère : est obligatoire à la fin de chaque ligne contenant IF,ELIF ou ELSE.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 29 / 174

Page 30: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Instructions conditionnelles

Trouver, par exemple, le minimum de deux nombres :

x, y =4, 3

# Ecriture classique :

if x<y:min=x

else:min=y

# Utilisation de l’operateur ternaire :

min = x if x < y else y

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 30 / 174

Page 31: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Instructions conditionnelles

Un autre exemple :

nom=input("Introduire un nom : ")

if nom == "Marie":print "Bonjour Marie !"

elif nom == "Pierre":print "Salut Pierre !"

elif nom == "Michel":print "Salut Michel !"

else:print "Nouveau prenom"

Question : Saisissez un flottant. S’il est positif ou nul, affichez saracine, sinon affichez un message d’erreur. Utiliser :# importfrom math import sqrt

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 31 / 174

Page 32: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Boucle WHILE

But : Répéter une portion de code.

Code Listing 6 – La syntaxe de WHILEwhile {condition a laquelle la boucle continue}:

{code execute dans la boucle}# indentation necessaire, d’habitude 4 espaces;

{code qui ne sera pas execute dans la boucle}# car il n’est pas indente.

Code Listing 7 – Exemplex = 10while x != 0:

x = x - 1print ("X decroit, valeur non nulle egale a "), x

print ("La boucle est finie, x est nul")

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 32 / 174

Page 33: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Boucle WHILE

Question 1 : Que fait l’exemple précédent ? commenter le résultat.

Question 2 : Commenter l’exemple suivant.

Code Listing 8 – Exemplen = input("Entrez un entier [1 .. 10] : ")while (n < 1) or (n > 10):

n = input("Entrez un entier [1 .. 10], S.V.P. : ")

Question 3 : Initialisez deux entiers : a = 0 et b = 10.

(i) Écrire une boucle affichant et incrémentant la valeur de a tant qu’ellereste inférieure à celle de b.

(ii) Écrire une autre boucle décrémentant la valeur de b et affichant savaleur si elle est impaire. Boucler tant que b n’est pas nul.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 33 / 174

Page 34: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Indentation

Le code doit obligatoirement être indenté !

Remarques :

La tabulation sert à délimiter les blocs de code.

C’est une bonne pratique dans tout langage.

Code Listing 9 – Indentation>>> a=2>>> b=3File "<stdin>", line 1b=3^IndentationError: unexpected indent

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 34 / 174

Page 35: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

II. VAR LOOPS

Indentation

Un exemple plus complet. Commenter les 3 niveaux d’indentation.

Code Listing 10 – Exemplex = 10while x > 0:

print xif x > 5:

print "Nombre plus grand que 5"elif x % 2 != 0:

print "C’est un nombre impaire"print "Il n’est pas plus grand que 5"

else:print "Ce nombre n’est pas plus grand que 5"print "Il n’est pas impaire, non plus"

x = x - 1print "nous avons diminue x de 1"print "on continue la boucle tant que x restesuperieur a 0"

print "Maintenant x n’est plus superieur a 0"print "la boucle est finie."

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 35 / 174

Page 36: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Les listes : définition et exemples

ListeCollection hétérogène, ordonnée et modifiable d’éléments, séparéspar des virgules, et entourée de crochets.

Code Listing 11 – Créer une listefruits = [’figue’, ’raisin’, ’abricot’, ’poire’]

Opérations de base :

>>> print fruits[2] # abricot

>>> fruits[1]=13

>>> print fruits # [’figue’, 13, ’abricot’, ’poire’]

>>> print fruits[0:2] # [’figue’, 13]

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 36 / 174

Page 37: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Les listes : initialisation

Utilisation de la répétition et de l’instruction ’range()’ :

Code Listing 12 – Fonction range>>> debut = []# liste vide

>>> repet = [0.0] * 3# [0.0, 0.0, 0.0]

>>> liste_1=range(4)# [0, 1, 2, 3]

>>> liste_2=range(4,10)# [4, 5, 6, 7, 8, 9]

Liste de listes :

>>> liste_3=[liste_1,liste_2]>>> print liste_3# [[0, 1, 2, 3], [4, 5, 6, 7, 8, 9]]

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 37 / 174

Page 38: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Les listes : indiçage

Accès à des éléments ou informations sur la liste :

>>> print fruits# [’figue’, ’abricot’, ’poire’, ’pomme’, 18]

>>> fruits[1:3]# [’abricot’, ’poire’]

>>> fruits[:2]# [’figue’, ’abricot’]

>>> fruits[:]# [’figue’, ’abricot’, ’poire’, ’pomme’, 18]

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 38 / 174

Page 39: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

>>> fruits[-1]# 18

>>> len(fruits)# 5

>>> 18 in fruits# True

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 39 / 174

Page 40: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Les listes : méthodes

Pour ajouter une valeur à †une liste, utiliser la fonction ’append()’ :

Code Listing 13 – Fonction append>>> fruits.append(18)

>>> print fruits# [’figue’, 13, ’abricot’, ’poire’, ’pomme’, 18]

Pour effacer une valeur d’une liste, utiliser la fonction ’del’ :

Code Listing 14 – Fonction del>>> del fruits[1]

>>> print fruits# [’figue’,’abricot’, ’poire’, ’pomme’, 18]

Plus généralement, pour afficher les méthodes de la classe “liste” :help(list)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 40 / 174

Page 41: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Les listes : techniques de “slicing”

Insertion d’élémentsDans le membre de gauche d’une affectation, il faut obligatoirementindiquer une tranche pour effectuer une insertion. Le membre de droitedoit lui-même être une liste.

Code Listing 15 – Insertion>>> print fruits# [’figue’,’abricot’, ’poire’, ’pomme’, 18]

>>> fruits[2:2]=[’orange’]# insertion en 3ieme position

>>> print fruits#[’figue’, ’abricot’, ’orange’, ’poire’, ’pomme’, 18]

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 41 / 174

Page 42: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Les listes : techniques de “slicing”

Suppression/remplacement d’élémentsMêmes remarques : une tranche dans le membre de gauche, une listedans le membre de droite.

Code Listing 16 – Suppression/remplacement>>> print fruits# [’figue’,’abricot’, ’orange’, ’poire’, ’pomme’, 18]

>>> fruits[1:3]=[]# effacement par affectation d’une liste vide>>> print fruits# [’figue’, ’poire’, ’pomme’, 18]

>>> fruits[2:4]=[1.5,2.5]# remplacement>>> print fruits# [’figue’, ’poire’, 1.5, 2.5]

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 42 / 174

Page 43: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Les n-uples : définition et exemples

N-uples

Collection hétérogène, ordonnée et non-modifiable d’éléments,séparés par des virgules, et entourée de parenthèses.

Code Listing 17 – Créer un n-upleparametres = (200, ’pression’, 10, ’vitesse’)

Remarques :

À la différence des listes, les n-uples, une fois créés, ne peuventêtre modifiés : on ne peut plus y ajouter d’objet ou en retirer ;

Leur parcours est plus rapide que celui des listes ;

Ils sont utiles pour définir des constantes, paramètres etc.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 43 / 174

Page 44: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Les dictionnaires : définition et exemples

Dictionnaire

Collection de couples clé : valeur entourée d‚Äôaccolades.

Code Listing 18 – Créer un dictionnaireannuaire = { ’Bureau Marie’ : 201 , \’Bureau Pierre’ : 202 , ’Bureau Alain’ : 203 , \’Bureau Jeanne’ : 204}

Remarques :

On les appelle aussi "tableaux associatifs" ;Les indices sont appelés "clés". ;d[Nom] affiche l’élément dont la clé est Nom ;d.keys() affiche les clés ;d.items() affiche les éléments du dictionnaire.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 44 / 174

Page 45: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Boucle FOR

But : Répéter une portion de code pour chaque valeur d’une séquence(chaîne, liste ou n-uple).

Code Listing 19 – La syntaxe de FORfor {valeur} in {sequence}:

{code execute dans la boucle}# indentation necessaire, d’habitude 4 espaces;

{code qui ne sera pas execute dans la boucle}# car il n’est pas indente.

Code Listing 20 – Exemplesfor lettre in "bonjour":

print lettre,# b o n j o u r

for i in [1,2,3]:print i,

# 1 2 3

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 45 / 174

Page 46: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Autres techniques pour les boucles

Pour les tableaux de très grande taille, préférez xrange à range :

$ python -m timeit ’for i in range(1000000):’ ’ pass’10 loops, best of 3: 39.8 msec per loop

$ python -m timeit ’for i in xrange(1000000):’ ’ pass’100 loops, best of 3: 15.7 msec per loop

Utilisation du générateur enumerate :

liste = [1,2,3,5,7,11,13]for index, elem in enumerate (liste):

print index, elem,

Question : Que fait l’exemple précédent ? commenter le résultat.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 46 / 174

Page 47: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Les listes en compréhension : définition et exemples

Liste en compréhensionExpression qui permet de générer une liste de manière très compacte.Elle est équivalente à une boucle for qui construirait la même liste enutilisant la méthode append().

Code Listing 21 – Exemple, premiere forme :

resultat_1 = [x+1 for x in range(5)]

# a le meme effet que :

resultat_1 = []for x in range(5):

resultat_1.append(x+1)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 47 / 174

Page 48: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Les listes en compréhension : exemples

Code Listing 22 – Exemple, deuxieme forme :

resultat_2 = [x+1 for x in range(5) if x > 2]# a le meme effet que :

resultat_2 = []for x in range(5):

if x > 2:resultat_2.append(x+1)

Code Listing 23 – Exemple, troisieme forme :

resultat_3 = [x*y for x in range(5) for y in range(2)]# a le meme effet que :

resultat_3 = []for x in range(5):

for y in range(2):resultat_3.append(x*y)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 48 / 174

Page 49: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

III. LISTS FOR

Les listes en compréhension

Question : Que font les exemples précédents ? commenter lesrésultats.

Question : Utilisez une liste en compréhension pour ajouter 3 àchaque élément d’une liste d’entiers de 0 à 5, mais seulement sil’élément est supérieur ou égal à 2.

Question : Utilisez une liste en compréhension pour obtenirla liste [’ad’, ’ae’, ’bd’, ’be’, ’cd’, ’ce’] à partirdes chaînes "abc" et "de".

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 49 / 174

Page 50: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Les fonctions : définition et exemples

Fonction

Groupe d‚Äôinstructions regroupé sous un nom et s’executant à lademande de l’utilisateur, lors de l’appel.

La liste des fonctions Python existantes est disponible en ligne :

http://docs.python.org/2/library/functions.html

Exemple :

>>> abs(x)# Return the absolute value of a number. The argument# may be a plain or long integer or a floating point# number. If the argument is a complex number, its# magnitude is returned.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 50 / 174

Page 51: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Les fonctions : syntaxe

Code Listing 24 – L’operateur DEFdef nom_fonction(liste des parametres):

"""Documentation de la fonction."""{ code execute dans la fonction }# indentation necessairereturn {valeur retournee dans le programme principal}

{ code qui ne sera pas execute dans la fonction }# car il n’est pas indente.

Remarques :

Dans la définition précédente, nom_fonction est le nom qui serautilisé ultérieurement pour appeler la fonction ;

Le bloc d’instructions est obligatoire. S’il ne fait rien (ou le coden’est pas encore écrit), on utilise l’instruction pass.

La documentation est fortement conseillée.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 51 / 174

Page 52: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Les fonctions : exemples

Utilisation sans liste de paramètres :

def somme():""" somme des 10 premiers entiers"""s=0for x in range(11):s+=x

return s

# appel de la fonctionprint ("La somme est :"), somme()# La somme est 55

help(somme)# Help on function somme in module __main__:

# somme()# somme des 10 premiers entiers

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 52 / 174

Page 53: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Passage des arguments

Passage par affectation

Chaque argument de la définition de la fonction correspond, dansl’ordre, à un paramètre de l’appel. La correspondance se fait paraffectation.

Exemple, plusieurs paramètres, pas de retour :

def table(base, debut, fin):""" !!! A COMPLETER !!! """n = debutwhile n <= fin:

print n,x,base,=,n*base,n += 1

# exemple d’appel :table(7, 2, 11)

Question : Que fait l’exemple précédent ? commenter.Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 53 / 174

Page 54: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Un ou plusieurs paramètres, utilisation du retour

from math import pi

def cube(x):return x**3

def volumeSphere(r):return 4.0 * pi * cube(r) / 3.0

# Saisie du rayon et affichage du volume

rayon = input("Le rayon de la sphere :"))print ("Volume de la sphere ="),volumeSphere(rayon)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 54 / 174

Page 55: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Fonction avec appel récursif

def fibo(n):""" Retourne le nombre de Fibonacci n """if n == 0 or n == 1:

return nelse:

return fibo( n - 1 ) + fibo( n - 2 )

# Appel de la fonctionprint fibo(9)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 55 / 174

Page 56: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Fonction avec un nombre d’arguments arbitraire

Fonction à nombre variable de paramètres :

def Somme(*args):""" Retourne la somme de n-uple """S = 0for nombre in args:

S += nombrereturn S

# Exemples d’appel :print Somme(35) # 35print Somme(12, -36, 30) # 6

Fonction à nombre variable de paramètres nommés :

def myfunc(**kwargs):print kwargs

myfunc(a=4, b=’python’, pi=3.14)# {’a’: 4, ’b’: ’python’,’pi’: 3.14}

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 56 / 174

Page 57: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Fonctions

Question : Ecrire une fonction VolCyl qui retourne le volume d’uncylindre. Les paramètres sont le rayon R et la hauteur H. Tester cettefonction par des appels avec différents arguments.

Question : Ecrire une fonction SolEq pour calculer les solutions réellesde l’équation

ax2 + bx + c = 0.

Le résultat de la fonction sera un n-uple : sur la première position, onaffiche le nombre de racines réelles (0, 1 ou 2) et sur les positionssuivantes les racines réelles ainsi calculées.Tester pour (1,−3,2), (1,−2,1) et (1,1,1).

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 57 / 174

Page 58: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Portée des objets

PortéeLes noms des objets sont créés lors de leur première affectation, maisne sont visibles que dans certaines régions de la mémoire.

Remarques :

Portée globale : celle du module __main__. Un dictionnaire gèreles objets globaux : l’instruction globals() fournit les couplesvariables : valeur ;

Portée locale : les objets internes aux fonctions (et aux classes)sont locaux. Les objets globaux ne sont pas modifiables dans lesportées locales. L’nstruction locals() fournit les couplesvariable : valeur.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 58 / 174

Page 59: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Exemple de portée (1/3)

# x et fonc sont affectes dans le module : globaux

def fonc(y):# y et z sont affectes dans fonc : locaux# dans fonc : portee localez = x + yreturn z

x = 99print fonc(1) # resultat : ?

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 59 / 174

Page 60: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Exemple de portée (2/3)

# x et fonc sont affectes dans le module : globaux

def fonc(y):# y, x et z sont affectes dans fonc : locauxx = 3 # ce nouvel x est local et masque le x globalz = x + yreturn z

x = 99print fonc(1) # resultat : ?

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 60 / 174

Page 61: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Exemple de portée (3/3)

# x et fonc sont affectes dans le module : globaux

def fonc(y):# y et z sont affectes dans fonc : locauxglobal x # permet de modifier x a la ligne suivantex += 2z = x + yreturn z

x = 99print fonc(1) # resultat : ?

Question : Quel sont les résultats dans les trois exemplesprécédents ?

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 61 / 174

Page 62: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Les fonctions map et zip : définition et exemples

zip permet de parcourir plusieurs séquences en parallèle :

Code Listing 25 – ZIP :L1 = [1, 2, 3]L2 = [4, 5, 6]for (x, y) in zip(L1, L2):

print x, y, ’--’, x + y

# 1 4 -- 5# 2 5 -- 7# 3 6 -- 9

map applique une méthode sur une ou plusieurs séquences et peutêtre beaucoup plus rapide qu’une boucle for :

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 62 / 174

Page 63: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Code Listing 26 – MAP :from math import factorialmap(factorial,range(4))

# [ 1, 1, 2, 6]

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 63 / 174

Page 64: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IV. FUNC

Utilisation de MAP

Question : En partant d’une liste de n éléments (l=range(n)), on veutproduire une nouvelle liste qui contient les valeurs e + 1 pour tous leséléments e de la liste de départ.

Exemple : [0,1,2, . . .] −→ [1,2,3, . . .].

Proposer :

Une version avec une boucle for ;

Une version avec map ;

Une version avec une liste de compréhension.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 64 / 174

Page 65: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Les modules : définition.

ModuleFichier indépendant permettant d’élaborer des bibliothèques defonctions ou de classes.

Remarques :

Avantage : on peut sauvegarder du code pour pouvoir le réutiliserultérieurement.

On donne généralement au nom du fichier ainsi créé l’extension.py.

La documentation (fortement conseillée !) et les tests peuvent êtreintégrés au module.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 65 / 174

Page 66: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Les modules : utilisation

Import d’un module : deux syntaxes possibles.

La commande import <nom module>

importe la totalité des objets du module.

import math

La commande from <nom module> import obj1, obj2 ...

n’importe que les objets obj1, obj2 ... du module.

from math import pi, sin, log

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 66 / 174

Page 67: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Les modules : exemple

Dans un fichier Fibo.py :

def fib(n):""" n-ieme terme de la suite de Fibonacci"""a, b = 0, 1while b < n:

print ba, b = b, a+b

Appel de la fonction fib :Méthode 1 :

import FiboFibo.fib(1000)

Méthode 2 :

from Fibo import fibfib(1000)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 67 / 174

Page 68: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Exécution d‚Äôun module Python

def print_fib(n):""" !!! A COMPLETER !!! """a, b = 0, 1while b < n:

print b,a, b = b, a+b

def list_fib(n):""" !!! A COMPLETER !!! """result,a,b =[],0,1while b < n:

result.append(b)a, b = b, a+b

return resultif __name__ == ’__main__’:

print_fib(100)print list_fib(100)

Question : Que fait l’exemple précédent ? commenter.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 68 / 174

Page 69: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Modules disponibles

1 Bibliothèque standard, avec des modules couvrant des domainestrès divers (maths, administration système, manipulation defichiers etc.)

http://docs.python.org/3/py-modindex.html

2 Nombreux modules (environ 41.000 ! ! ! à ce jour) développés parla communauté Python

https://pypi.python.org/pypi

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 69 / 174

Page 70: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Le module math

Le module math permet d’importer les fonctions et les constantes mathématiquesusuelles.

commande Python constante / fonction mathpi, e, exp(x) π,e = exp(1),exp(x)log(x), log(x,a) ln(x), loga(x)pow(x,y), floor(x), abs(x), factorial(n) xy , [x ], |x |,n!sin(x), cos(x), tan(x), asin(x), ... fonctions trigonométriquessinh(x), cosh(x), tanh(x), asinh(x), ... fonctions hyperboliques

Exemples :

Méthode 1 :import mathmath.cos(math.pi / 4.0)

Méthode 2 :from math import *cos(pi / 4.0)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 70 / 174

Page 71: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Le module random

Le module random propose diverses fonctions permettant de générerdes nombres (psedo-)aléatoires qui suivents différentes distributionsmathématiques.

random.randrange(p, n, h)# choisit un entier aleatoirement dans range(p,n,h)

random.randint(a, b)# choisit un entier N aleatoirement tel que# a <= N <= b.

random.choice(seq)# choisit un aleatoirement dans la sequence seq

random.random()# renvoie un decimal aleatoire dans [0,1[

random.uniform(a, b)# choisit un reel N aleatoirement, tel que# a <= N <= b si a <= b et b <= N <= a si b < a.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 71 / 174

Page 72: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Le module decimal

Un exemple surprenant :

>>> 1.1 + 2.23.3000000000000003

>>> 0.1 + 0.1 + 0.1 - 0.35.551115123125783e-17

Question : Pourquoi ? À comparer avec

>>> from decimal import *

>>> Decimal(’1.1’) + Decimal(’2.2’)Decimal(’3.3’)

>>> Decimal(’0.1’) + Decimal(’0.1’) + Decimal(’0.1’)- Decimal(’0.3’)Decimal(’0.0’)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 72 / 174

Page 73: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Chemin de recherche d’un module Python

Recherche dans sys.path :dans le répertoire courant ;dans PYTHONPATH si défini (même syntaxe que PATH) ;dans un répertoire par défaut (sous Linux : /usr/lib/python)

Remarque : Si l’on importe un module personnel qui n’est pas dans lerépertoire où se trouve le fichier à exécuter, un message d’erreur estrenvoyé, disant que ce module est inconnu.

Solution : Utiliser le module sys, qui contient des variables spécifiquesau système et et permet l’accès aux options passées en ligne decommande : écrire au début du fichier dans lequel on souhaiteimporter le module.

import syssys.path.append(’le/chemin/de/mon/module/’)import mon_module

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 73 / 174

Page 74: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Ouverture et fermeture des fichiers

Le type fichier est un type prédéfini de Python. Principaux modesd’ouverture :

f1 = open("monFichier", "r")# ouverture en lecture seule

f2 = open("monFichier", "w")# ouverture pour ecriture : si le fichier n’existe pas,# il est cree, sinon son contenu est ecrase

f3 = open("monFichier", "a")# ouverture pour ajout : si le fichier n’existe pas,# il est cree, sinon l’ecriture s’effectue a la suite# du contenu deja existant

f4 = open("monFichier", "+")# ouverture pour lecture et ecriture

Une seule méthode de fermeture :

f1.close()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 74 / 174

Page 75: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Exemples

Méthodes d’écriture :

f = open("fichier.txt", "w")

s = ’toto’f.write(s)# ecrit la chaine s dans f

l = [’a’, ’b’, ’c’]f.writelines(l)# ecrit les chaines de la liste l dans f

f.close()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 75 / 174

Page 76: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

On peut aussi utiliser le "print étendu" :f = open("fichier.txt", "a")

print >> f, "abcd"# ecrit dans f en mode ajout

f.close()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 76 / 174

Page 77: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Lecture sequentielle

f = open("fichier.txt", "r")

s = f.read()# lit tout le fichier --> string

s = f.read(n)# lit au plus n octets --> string

s = f.readline()# lit la ligne suivante --> string

s = f.readlines()# lit tout le fichier --> liste de strings

for ligne in f:print ligne

# bon procede parcours d’un fichier

f.close()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 77 / 174

Page 78: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Le module pickle

Plus que du stockage, il permet la conservation des types :

import pickle

a, b = 5, 2.83

f = open("Fichier.txt", "w") # en ecriture

pickle.dump(a, f)pickle.dump(b, f)

f.close()

f = open("Fichier.txt", "r") # en lecture

t = pickle.load(f)print t, type(t) # 5 <type ’int’>t = pickle.load(f)print t, type(t) # 2.83 <type ’float’>

f.close()Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 78 / 174

Page 79: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

V. MODULES FICHIERS

Manipulation des modules / fichiers

Question 1 : Que font les fonctions pickle.dump et pickle.loaddans l’exemple précédent ?

Question 2 : Écrire une fonction qui renvoie le nombre de lignes d’unfichier.

Question 3 : Créer un fichier texte contenant une suite aléatoire dechiffres (on pourra utiliser la fonction randint() du module random).

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 79 / 174

Page 80: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

NumPy : introduction

NumPyLe module incontournable du calcul scientifique avec Python.

Remarques :

S’installe comme un module Python standard.Contient les fonctions de manipulation des tableaux pour le calculnumérique.Bibliothèque mathématique importante.

import numpy as np

# les noms numpy sont accessibles avec le prefixe np

# inutile d’importer math dans la suite.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 80 / 174

Page 81: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Les tableaux NumPy

ndarray

Collection indexable, contenant des éléments du même type et de lamême taille.

Remarques :

Contrairement aux listes, ils contiennent des objets de typesidentiques, comme des flottants, ou des entiers.Comparés aux listes simples, les objets fournis par NumPy sontoptimisés pour le calcul numérique.La manipulation est similaire à tout autre objet Python.Les dimensions et parcours sont modifiables, les indexationssouples.

http:

//docs.scipy.org/doc/numpy/reference/arrays.ndarray.htmlSzopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 81 / 174

Page 82: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Création de tableaux

Différentes méthodes :

par le contenu :

a=np.array([1,3,5,7,9,11,13,17])# liste de valeurs

par la dimension (une liste : dimension 1, une liste de listes :dimension 2, une liste de listes de listes : dimension 3 etc.) :

a=np.array([0.1, 0.0, 0.2])b=np.array([[1,2,3],[4,5,6]])

par le type d’elément :

a=np.array([0.1, 0.0, 0.2],dtype=’f’)b=np.array([[1,2,3],[4,5,6]],dtype=’i’)# dtype est optionnel dans toutes les creations de# tableaux et fixe par defaut a float

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 82 / 174

Page 83: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Création de tableaux

Différentes méthodes (suite) :

comme fonction de ces indices :

def initfunction(i,j):return 100+10*i+j

c=np.fromfunction(initfunction,(5,3))

à partir d’un fichier :

a=np.ones((3,5,7))np.save("data.npy",a)b=np.load("data.npy")

Question : Que font les exemples précédents ? commenter.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 83 / 174

Page 84: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Les tableaux NumPy structurés (Record arrays)

http://docs.scipy.org/doc/numpy/reference/routines.

array-creation.html

np.empty(N,dtype=’int’)# tableau vide de N entiers

np.empty(N,dtype=’float’)#tableau vide de N reels

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 84 / 174

Page 85: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

np.zeros(N)# tableau de N zeros

np.ones((N,M))# tableau de dimension (N,M) de uns

np.zeros_like(a)# tableau de zeros de meme dimension et type qu’un# tableau a (idem np.ones_like, np.empty_like).

np.arange(M,N,P)#tableau allant de M a N avec pas P (M et P optionnels,# les valeurs par defaut sont M=0 et P=1)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 85 / 174

Page 86: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Modification du profil d’un tableau

Les dimensions d’un tableau et/ou le nombre de dimensions peuventêtre changés :

flat : vue 1D d’un tableau sans modification :

np.eye((3)).flat[:]# A COMPLETER

shape : n-uplet des dimensions d’un tableau

a=ones((3,5,7))a.shape# A COMPLETER

modification des dimensions, en conservant la longueur totale :

a=np.ones((4,6))a=a.reshape(8,3)# A COMPLETER

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 86 / 174

Page 87: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Copie et référence

b=a.copy()# copie d’un tableau a dans un tableau b

b=a# ne copie pas les elements, mais cree juste une# reference, i.e. si a est modifie, b l’est aussi.

Exécuter les scripts Python suivants ; commenter.

a = np.ones((4,3))b = a.transpose()b[0,1] = 10print a

a = np.arange(12)b = a.reshape((4,3))b[0,1] = 10print a

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 87 / 174

Page 88: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Référencer les éléments d’un tableau

a=np.arange(24).reshape(2,3,4)# A COMPLETER

Accès à un élément dans le tableau :

a[0][2][1]# A COMPLETER

Syntaxe avec implémentation optimisée pour l’accès :

a[0,:-1]# A COMPLETER

La syntaxe fonctionne pour la référence et l’assignation :

b=a[0:2]a[0:2]=9# A COMPLETER

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 88 / 174

Page 89: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Opérations

Opérations mathématiques : toutes les opérations arithmétiques etfonctions classiques s’appliquent terme à terme pour un tableau a :

a=np.eye(3)

2*a+1a**21+np.sin(a) # utilisation du sin de numpy

Opération globales :

a.max() # maximum globala.max(0) # maximum de chaque lignea.max(1) # maximum de chaque colonne

Même chose pour :a.min() # minimuma.sum() # sommea.prod() # produita.mean() # moyenne

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 89 / 174

Page 90: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Calcul numérique matriciel

Les matrices sont des tableaux à deux dimensions, les vecteurs destableaux à une dimension.

Création de matrices :

np.diag(v)# matrice avec le vecteur v sur la diagonale.

np.diag(np.arange(N))np.diag(np.ones(N))

np.diag(v,i)# matrice avec le vecteur v sur la ieme diagonale# superieure.np.diag(v,-i)# matrice avec le vecteur v sur la ieme diagonale# inferieure.

np.identity(n)# matrice identite de taille n

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 90 / 174

Page 91: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Opération sur des matrices

Utilisées dans numpy.linalg :

np.dot(A,B)# produit des matrices A et B

np.inner(x,y)# produit scalaire des vecteurs x et y

np.linalg.det(A)# determinant de la matrice A

np.linalg.inv(A)# inverse de la matrice A

np.linalg.solve(A,b)# solution x du systeme lineaire Ax=b

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 91 / 174

Page 92: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

np.linalg.eigvals(A)# valeurs propres de la matrice A

np.linalg.eig(A)# valeurs et vecteurs propres de A

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 92 / 174

Page 93: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Différentiation et intégration numérique

Intégrale du vecteur y avec la formule des trapèzes ; par défaut avec unpas de 1. Les abscisses ou le pas peuvent être donnés :

np.trapz(y)

Différences divisées de y :

np.diff(y)

Gradient d’un tableau à N dimensions :

gradient(f, *varargs)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 93 / 174

Page 94: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VI. NUMPY

Utiliser les tableaux

Question 1 : un tableau trié. Écrire une fonction partition(n) quiconstruit un tableau 1d x avec n éléments tels quex0 = 0 ≤ x1 ≤ x2 ≤ . . . ≤ xn−1 = 1 et où les xi , i ∈ {1, . . . ,n − 2} sontobtenus au hasard uniforme sur [0,1].

Question 2 : matrice du laplacien 1d discret. Écrire une fonctionmat_lap1d(n) qui, étant donné l’entier n, renvoie la matrice suivante :

A =

2 −1 . . . 0

−1 2. . .

. . . . . . −10 . . . −1 2

.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 94 / 174

Page 95: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

Matplotlib : introduction

MatplotlibModule qui permet de générer des graphes depuis Python (très richeen types de graphiques 2D).

Remarques :

Les (+) : bon rendu graphique, export immediat en .png, .pdf etc.

Les (-) : peu adaptée pour les animations, interactivitéquasi-inexistante.

import matplotlib as mpl

# les noms matplotlib sont accessibles avec le# prefixe mpl

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 95 / 174

Page 96: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

Description de Matplotlib

Les possibilités :

Courbes 1D ;

Graphiques 2D scalaire et vecteurs ;

Formats : png, eps, pdf, svg ...

Insertion des formules Latex.

Les sous espaces :

pyplot : tous les graphiques ;

mlab : imite quelques fonctionalités MATLAB ;

pylab : module global regroupant mlab, pyplot et numpy.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 96 / 174

Page 97: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

Comment utiliser Matplotlib en pratique ?

Ne rien apprendre par cœur !

Aller sur

http://matplotlib.org

Chercher le type de figure que vous voulez.

Copier le code source (attention au règles du copyright, citez vossources !).

Adaptez-le si besoin.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 97 / 174

Page 98: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

Un premier exemple

from pylab import *

debut = -2 * pifin = 2 * pipas = 0.1x = arange(debut,fin,pas)y = cos(x)

plot(x,y)# genere un graphique avec des lignes et prend comme# valeurs en abscisse (x) et en ordonnees (y)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 98 / 174

Page 99: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

xlabel(’angle (rad)’)ylabel(’cos(angle)’)# donne un nom aux axestitle(’Fonction: y = cos(x)’)# definit le titre du graphiquegrid()# affiche une grille en filligrane

show()# active l’affichage a l’ecran du graphique

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 99 / 174

Page 100: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

Un autre exemple : utilisation de subplot

import numpy as npimport matplotlib.pyplot as plt

x = np.array([0,1,2,3,4,5,6,7,8,9])y = x*x

plt.figure()

plt.subplot(211)plt.plot (x,y,color=’r’)plt.title(’Titre 1’,color=’g’)

plt.subplot(212)plt.plot(x,y,marker=’o’)plt.title (’Titre 2’,color=’b’)

plt.show()

Question : Que fait le script précédent ? commenter.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 100 / 174

Page 101: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

L’objet figure

import numpy as npimport matplotlib.pyplot as plt

x = np.arange(0, 10, 0.2)y = np.sin(x)

fig = plt.figure()# Nouvelle figureax = fig.add_subplot(111)# un subplot dans la figure

l1, l2 = ax.plot(x, np.sin(x), ’-’, x,np.cos(x),’+’)# deux plots sur l’axe

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 101 / 174

Page 102: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

fig.legend((l1, l2), (’sin’, ’cos’), ’upper left’)# legende dans le coin de haut a gaucheax.set_xlabel(’t’)# ’t’ sur l’axe des xax.set_ylabel(’$\phi$’)# $\phi$ sur l’axe des y (utilisation de Latex)

plt .show()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 102 / 174

Page 103: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

Le couple meshgrid - contourf

from pylab import *

nx = 32ny = 32x = linspace(0,1,nx)y = x.copy()

X, Y = meshgrid(x,y)F = sin(pi*X)*cos(pi*Y)

cs = contourf(X,Y,F)cb = colorbar(cs)

show()

Question : Que fait le script précédent ? commenter.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 103 / 174

Page 104: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

Utilisation de mplot3d

from mpl_toolkits.mplot3d import Axes3Dfrom matplotlib import cmimport matplotlib.pyplot as pltimport numpy as np

fig = plt.figure()ax = Axes3D(fig)X = np.arange(-5, 5, 0.25)Y = np.arange(-5, 5, 0.25)X, Y = np.meshgrid(X, Y)

R = np.sqrt(X**2 + Y**2)Z = np.sin(R)surf = ax.plot_surface(X,Y,Z,rstride=1,cstride=1,

cmap=cm.jet,linewidth=0,antialiased=False)ax.set_zlim3d(-1.01, 1.01)

fig.colorbar(surf)plt.show()

http://matplotlib.org/mpl_toolkits/mplot3d/api.htmlSzopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 104 / 174

Page 105: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

Résolution d’une équation différentielle de premierordre

On considère le problème de Cauchy{u′(t) = u(t) ∀ t ∈ [0,5]

u(0) = 1.(1)

1) Calculer la solution exacte de (2).

2) On notera h le pas de temps supposé constant et uj , j = 0,1,2, . . .les valeurs approchées de u(tj), où tj = j h.(a) Ecrire le schéma d’Euler implicite et le schéma d’Euler explicite

correspondants à (2).(b) Ecrire le code Python correspondant.(c) Représenter sur le même graphique la solution exacte et les deux

solutions numériques ainsi obtenues.Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 105 / 174

Page 106: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

Améliorer l’interactivité

Remarque Plusieurs possibilités : Tkinter, PyQt, PyGTK etc.

Tkinter“Tool kit interface” : bibliothèque graphique qui facilite la constructionde GUI (Graphic User Interface) simples.

Exemple :

from Tkinter import *

fenetre=Tk()cv=Canvas(fenetre,width=200,height=200)cv.pack()cv.create_line(10,50,100,150)# dessine le segment MN avec M(10,50) et N(100,150)

fenetre.mainloop()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 106 / 174

Page 107: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VII. MATPLOTLIB

Tkinter : Comment ça marche ?

http://docs.python.org/2/library/tkinter.html

Importer Tkinter.Configurer et positionner les widgets (=composantes graphiques)utilisés.Entrer dans la boucle principale de gestion des événements.

from Tkinter import *

base = Tk()texte = Label(base,text="Bienvenue !",fg="red")texte.pack()bouton = Button(base,text="Quit",command=base.destroy)bouton.pack()

base.mainloop()

Question : Que font les deux exemples précédents ? commenter.Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 107 / 174

Page 108: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Scipy : introduction

ScipyModule contenant des algorithmes très utilisés en calcul scientifique :fft, méthodes directes ou itératives pour résoudre des systèmeslinéaires, intégration numérique etc.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 108 / 174

Page 109: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Remarques :

Dans la suite, on utilise :

import numpy as npimport scipy as sp

On peut le voir comme une extension de Numpy :

>>> np.sqrt(-1)# __main__:1: RuntimeWarning: invalid value# encountered in sqrt# nan>>> sp.sqrt(-1)# 1j

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 109 / 174

Page 110: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Description de Scipy

http://docs.scipy.org/doc/scipy/reference/

scipy.constants : Constantes physiques et mathématiques ;

scipy.fftpack : Transformée de Fourier Discrète ;

scipy.integrate : Intégration et équations différentielles ;

scipy.interpolate : Interpolation ;

scipy.linalg : Algèbre linéaire ;

scipy.optimize : Optimisation et recherche de racines ;

scipy.signal : Traitement du signal ;

scipy.sparse : Matrices creuses ;

scipy.stats : Fonctions statistiques ;

etc. ...Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 110 / 174

Page 111: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Fonctions spéciales : scipy.special

from scipy import special

Ce paquet de SciPy contient par exemple :

Les fonctions d’Airy, de Bessel, Gamma, Beta, ...

>>> sp.special.gamma(4)# 6.0 (prolongement de la fonction factorielle a# l’ensemble des nombres complexes)

Les fonctions et intégrales elliptiques ;

La fonction d’erreur et l’intégrale de Fresnel ;

Les polynômes de Legendre, de Chebyshev, de Jacobi, d’Hermite,...

Quelques outils de statistique.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 111 / 174

Page 112: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Interpolation : scipy.interpolate

from scipy import interpolate

Interpolation 1D :

interp1d(x,y,kind=’linear’)# avec kind=’zero’, ’linear’, ’quadratic’, ’cubic’,# ’nearest’, ’slinear’ (’linear’ par defaut).

Trouver le polynôme passant au plus près d’un ensemble depoints : BarycentricInterpolator, KroghInterpolator,PiecewisePolynomial (si l’on a également les dérivées) ;

Interpolation 2D : interp2d, griddata ;

Interpolation par splines.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 112 / 174

Page 113: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Un exemple

import pylab as plfrom scipy.interpolate import interp1d

x = sp.linspace(-1, 1, num=5)# 5 points regulierement espaces entre -1 et 1.y = (x-1.)*(x-0.5)*(x+0.5)# x et y sont des tableaux numpy

f0 = interp1d(x,y, kind=’zero’)f1 = interp1d(x,y, kind=’linear’)f2 = interp1d(x,y, kind=’quadratic’)f3 = interp1d(x,y, kind=’cubic’)f4 = interp1d(x,y, kind=’nearest’)xnew = sp.linspace(-1, 1, num=40)ynew = (xnew-1.)*(xnew-0.5)*(xnew+0.5)

pl.plot(x,y,’D’,xnew,f0(xnew),’:’, xnew, f1(xnew),’-.’,xnew,f2(xnew),’-.’,xnew ,f3(xnew),’s--’,xnew,f4(xnew),’--’,xnew, ynew, linewidth=2)pl.legend([’data’,’zero’,’linear’,’quadratic’,’cubic’,’nearest’,’exact’],loc=’best’)pl.show()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 113 / 174

Page 114: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Interpolation 1D

1.0 0.5 0.0 0.5 1.01.5

1.0

0.5

0.0

0.5

datazerolinearquadraticcubicnearestexact

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 114 / 174

Page 115: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Un autre exemplefrom scipy.interpolate import interp2d

x,y=sp.mgrid[0:1:20j,0:1:20j]#create the grid 20x20z=sp.cos(4*sp.pi*x)*sp.sin(4*sp.pi*y)#initialize the fieldX,Y=sp.mgrid[0:1:100j,0:1:100j]#create the interpolation grid 100x100

T1=interp2d(x,y,z,kind=’linear’)T2=interp2d(x,y,z,kind=’cubic’)T3=interp2d(x,y,z,kind=’quintic’)

pl.figure(1)pl.subplot(221) #Plot original datapl.contourf(x,y,z)pl.title(’20x20’)pl.subplot(222) #Plot linear interpolationpl.contourf(X,Y,T1(X[:,0],Y[0,:]))pl.title(’100x100 linear’)pl.subplot(223) #Plot cubic interpolationpl.contourf(X,Y,T2(X[:,0],Y[0,:]))pl.title(’100x100 cubic’)pl.subplot(224) #Plot quintic interpolationpl.contourf(X,Y,T3(X[:,0],Y[0,:]))pl.title(’100x100 quintic’)

plt.show()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 115 / 174

Page 116: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Interpolation 2D

0.0 0.2 0.4 0.6 0.8 1.00.0

0.2

0.4

0.6

0.8

1.0 20x20

0.0 0.2 0.4 0.6 0.8 1.00.0

0.2

0.4

0.6

0.8

1.0 100x100 linear

0.0 0.2 0.4 0.6 0.8 1.00.0

0.2

0.4

0.6

0.8

1.0 100x100 cubic

0.0 0.2 0.4 0.6 0.8 1.00.0

0.2

0.4

0.6

0.8

1.0 100x100 quintic

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 116 / 174

Page 117: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Intégration : scipy.integrate

from scipy import integrate

Intégration numérique de fonctions (intégrales définies) :

>>> x2=lambda x: x**2>>> integrate.quad(x2,0.,4.)# (21.333333333333336, 2.368475785867001e-13)# resultat, borne superieure pour l’erreur.

Plusieurs options quad : intégrale simple, dblquad : intégraledouble, tplquad : intégrale triple etc.

Intégration numérique de données discrètes : trapz (dansNumpy), simps : méthode de Simpson composite etc.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 117 / 174

Page 118: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Intégration numérique

On souhaite calculer une approximation numérique de l’intégrale∫ 5

1x ln x dx .

(a) Ecrire la méthode composite des trapèzes pour calculer l’intégraleprécédente et le code Python correspondant.

(b) Comparer le résultat obtenu avec la solution analytique, ainsiqu’avec le résultat fourni par scipy.integrate. Commenter.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 118 / 174

Page 119: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Résolution d’équations différentielles : scipy.odeintimport scipy as spimport scipy.integrate as spi

Exemple : l’oscillateur de van der Pol

y ′1(t) = y2(t)

y ′2(t) = 1000(

1− y21 (t)

)y2(t)− y1(t).

def vdp1000(y,t):dy=sp.zeros(2)dy[0]=y[1]dy[1]=1000.*(1.-y[0]**2)*y[1]-y[0]return dy

t0=0tf=3000N=300000dt=(tf-t0)/N

tgrid=sp.linspace(t0,tf,num=N)y=spi.odeint(vdp1000,[2.,0.],tgrid)

import pylab as pltplt.plot(tgrid,y[:,0])plt.show()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 119 / 174

Page 120: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Résolution d’équations différentielles

Question 1 : Que fait l’exemple précédent ? Compléter le script afind’afficher le portrait de phase correspondant.

Question 2 : Dans le cours précédent, vous avez résolu l’équationdifférentielle suivante{

u′(t) = u(t) ∀ t ∈ [0,5]

u(0) = 1.(2)

par les schémas d’Euler implicite et explicite. Comparer les résultatsavec la méthode fournie par scipy.integrate.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 120 / 174

Page 121: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

VIII. SCIPY

Optimisation : scipy .optimize

from scipy import optimize

Résolution de problèmes d’optimisation et optimisation souscontrainte en utilisation des algorithmes “standard”.

Plusieurs options : leastsq : moindres carrés, minimize :minimisation avec ou sans contraintes, algorithme deBroyden-Fletcher-Goldfarb-Shanno (BFGS) etc.

Résolution de F (X ) = 0 :import scipy.optimize as spodef f(x):

out = [x[0]*sp.cos(x[1]) - 4 ]out.append ( x [ 1 ] * x [ 0 ] - x [ 1 ] - 5 )return out

x0 = spo.fsolve(f,[1,1])print x0 , f (x0)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 121 / 174

Page 122: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Les bibliothèques de Scipy

http://docs.scipy.org/doc/scipy/reference/

scipy.constants : Constantes physiques et mathématiques ;

scipy.fftpack : Transformée de Fourier Discrète ;

scipy.integrate : Intégration et équations différentielles ;

scipy.interpolate : Interpolation ;

scipy.linalg : Algèbre linéaire ;

scipy.optimize : Optimisation et recherche de racines ;

scipy.signal : Traitement du signal ;

scipy.sparse : Matrices creuses ;

scipy.stats : Fonctions statistiques ;

etc. ...Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 122 / 174

Page 123: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Algèbre linéaire : scipy.linalg

La bibliothèque scipy.linalg

Contenu : des outils d’algèbre linéaire (matrices pleines ou bandes).

Remarque : parties en commun avec Numpy.

Algèbre linéaire de base :norm, inv , solve, det, lstsq, pinv ,matrix_power,dans Numpy ; en plus dans SciPy : résolution de systèmeslinéaires à matrices bandes + une autre méthode de calcul pour lapseudo-inverse, utilisant la décomposition svd (au lieu de lstsq).

Valeurs propres : dans Numpy , eig (H), eigvals(H) (Hmatrice hermitienne) ; dans SciPy : en plus les mêmes méthodespour des matrices bandes.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 123 / 174

Page 124: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Algèbre linéaire : scipy.linalg

Décompositions : les méthodes qr, svd, cholesky communes avecNumpy ; les méthodes lu, lu_solve, orth, schur, hessenberg

(plus quelques variantes) ajoutées dans SciPy .

Code Listing 27 – Decompostion de Cholesky A = LLt , L triangulaireinf.np.linalg.cholesky([[1,2], [1,9]])#array([[ 1. , 0. ],# [ 1. , 2.82842712]])

sp.linalg.cholesky([[1,2], [1,9]])#array([[ 1. , 2. ],# [ 0. , 2.23606798]])

sp.linalg.cholesky([[1,2], [1,9]], lower=True)#array([[ 1. , 0. ],# [ 1. , 2.82842712]])

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 124 / 174

Page 125: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Fonctions de matrices : expm, sinm, sinhm etc..., calcul de la matricesigne signm, de la racine carrée d’une matrice sqrtm.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 125 / 174

Page 126: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Algèbre linéaire : scipy.linalg

Décomposition LU, deux possibilités :

Version écrite pour Scipy :

P,L,U=sp.linalg.lu(A)

Version LAPACK (getrf) :

LU,Piv=sp.linalg.lu_factor(A)

Question : Comparer ces deux méthodes pour la matrice bandesuivante :

A =

1. 3. 0. 0. 0.2. 1. −4. 0. 0.6. 1. 2. −3. 0.0. 1. 4. −2. −30. 0. 6. −3. 2.

.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 126 / 174

Page 127: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Algèbre linéaire : Ax = b

Exemple pour A matrice précédente et b = [1,1,1,1,1]t :

b=sp.ones(5)print "x=", sp.linalg.lu_solve((LU,Piv),b)# LAPACK (getrs)

print "x=", sp.linalg.solve(A,b,sym_pos=False)# LAPACK (gesv ou posv si matrice symetrique)

Exemple pour une matrice bande et même b :

A=sp.array([ [0.,3.,-4.,-3.,-3.],[1.,1.,2.,-2.,2.],[2.,1.,4.,-3.,0.],[6.,1.,6.,0.,0.] ])

print "x=", sp.linalg.solve_banded((2,1),A,b)# LAPACK (gbsv)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 127 / 174

Page 128: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Matrices spécialesSciPy et NumPy mettent à disposition plusieurs fonctions pour créer desmatrices souvent utilisées dans les calculs.

Matrice de Vandermonde (matrice avec une progressiongéométrique dans chaque colonne) :

np.vander([1, 2, 3, 5],3)# N=3, 1ere colonne x^(N-1), 2nde colonne x^(N-2) ...array([[ 1, 1, 1],

[ 4, 2, 1],[ 9, 3, 1],[25, 5, 1]])

Matrice circulante (on passe d’une colonne à l’autre parpermutation circulaire

scipy.linalg import circulantcirculant([1, 2, 3 ,4])array([[1 4 3 2]

[2 1 4 3][3 2 1 4][4 3 2 1]])

Matrices par blocs diagonales, triangulaires, de Hilbert, de Toeplitzetc.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 128 / 174

Page 129: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Matrices creuses : scipy.sparse

import scipy.sparse as spsp

http://docs.scipy.org/doc/scipy/reference/sparse.html

Le stockage des matrices creuses peut être effectué aux formatssuivants :

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.Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 129 / 174

Page 130: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Stockage CSC des matrices creuses

Exemple : la matrice A donnée par :

A =

1 0 40 0 52 3 6

.row = sp.array([0,2,2,0,1,2])col = sp.array([0,0,1,2,2,2])data = sp.array([1,2,3,4,5,6])Mcsc1 = spsp.csc_matrix((data,(row,col)),shape=(3,3))print Mcsc1.todense()

Question : Comment la matrice A est-elle stockée dans l’exemplesuivant ?

indptr = sp.array([0,2,3,6])indices = sp.array([0,2,2,0,1,2])data = sp.array([1,2,3,4,5,6])Mcsc2=spsp.csc_matrix((data,indices,indptr),shape=(3,3))print Mcsc2.todense()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 130 / 174

Page 131: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Stockage CSC des matrices creuses

Avantages :

Opérations arithmétiques efficaces : csc + csc, csc ∗ csc, ...

"Slicing" efficace selon les colonnes ;

Produit matrice vecteur efficace.

Inconvénients :

"Slicing" selon les lignes moins efficaces qu’avec une matrice detype csr ;

Conversion coûteuse à d’autres formats de matrices creuses (parrapport aux formats lil et dok).

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 131 / 174

Page 132: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Stockage CSR des matrices creuses

Exemple : la matrice A donnée par :

A =

1 0 40 0 52 3 6

.row = sp.array([0,0,1,2,2,2])col = sp.array([0,2,2,0,1,2])data = sp.array([1,2,3,4,5,6])Mcsr1 = spsp.csr_matrix((data,(row,col)),shape=(3,3))print Mcsr1.todense()

Question : Comment la matrice A est-elle stockée dans l’exemplesuivant ?

indptr = sp.array([0 ,2 ,3 ,6])indices = sp.array([0 ,2 ,2 ,0 ,1 ,2])data = sp.array([1,2,3,4,5,6])Mcsr2=spsp.csr_matrix((data,indices,indptr),shape=(3,3))print Mcsr2.todense()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 132 / 174

Page 133: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Stockage CSR des matrices creuses

Avantages :

Opérations arithmétiques efficaces : csr + csr, csr ∗ csr, ...

"Slicing" efficace selon les lignes ;

Produit matrice vecteur efficace.

Inconvénients :

"Slicing" selon les colonnes moins efficaces qu’avec une matricede type csc ;

Conversion coûteuse à d’autres formats de matrices creuses (parrapport aux formats lil et dok).

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 133 / 174

Page 134: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Les formats dédiés a l’assemblage

lil_matrix : format agréable pour l’assemblage, mais il fautconvertir dans un autre format avant de calculer.

dok_matrix : format idéal pour un assemblage incrémental et laconversion vers un autre format est efficace.

coo_matrix : conversion tres rapide vers les formats csc/csr.

Remarque : Ce ne sont pas des formats “adaptés” au calcul (lesopérations arithmétiques peuvent être lentes), il est conseillé de lesconvertir après.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 134 / 174

Page 135: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Matrices creuses : scipy.sparse.linalg

http://docs.scipy.org/doc/scipy/reference/sparse.linalg.html

speigen, speigen_symmetric, lobpcg : calcul de valeurs etvecteurs propres (ARPACK).

svd : décomposition en valeurs singulières (ARPACK).

Résolution de Ax = b : méthodes directes (UMFPACK si présentou SUPERLU) ou itératives ; les formats csc/csr sont conseillés.

Algorithmes de minimisation : lsqr.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 135 / 174

Page 136: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Matrices creuses : Factorisation LU

import scipy as spimport scipy.sparse as spspimport scipy.linalg as splimport scipy.sparse.linalg as spspl

N=50un=sp.ones(N)w=sp.rand(N+1)A=spsp.spdiags([w[1:],-2*un,w[:-1]],[-1,0,1],N,N)

A=A.tocsc()b = unop=spspl.splu(A)print op

x=op.solve(b)print spl.norm(A*x-b)

Question : Commenter le script précédent.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 136 / 174

Page 137: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Matrices creuses : Gradient conjugué

Exemple pour résoudre le même système :

global kk=0def f(xk):

global kprint "iteration ",k," residu=",spl.norm(A*xk-b)k=k+1

x,info=spspl.cg(A,b,x0=sp.zeros(N),tol=1.0e-12,maxiter=N,M=None,callback=f)

A l’exécution :

iteration 0 residu= 2.71695646088iteration 1 residu= 1.23113341645...iteration 25 residu= 1.34905427044e-11iteration 26 residu= 5.41798161014e-12

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 137 / 174

Page 138: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

IX. SCIPYII

Matrices creuses : Gradient conjugué préconditionné

Exemple pour résoudre le même système :

pc=spspl.spilu(A,drop_tol=0.1)xp=pc.solve(b)spl.norm(A*xp-b)def mv(v):

return pc.solve(v)lo = spspl.LinearOperator((N,N),matvec=mv)k=0x,info=spspl.cg(A,b,x0=sp.zeros(N),tol=1.e-12,maxiter=N,M=lo,callback=f)

A l’exécution :

iteration 0 residu= 0.327201220193iteration 1 residu= 0.00973829257822...iteration 7 residu= 7.15477674159e-11iteration 8 residu= 3.67681615701e-12

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 138 / 174

Page 139: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Interfaçage : introduction

Python : www.python.org

Avantages :Langage simple, interprété avec une syntaxe claire.Facile à programmer et la gestion de la mémoire est automatique.Open source, gratuit et portable.Dispose de nombreux modules pour le calcul scientifique.

Inconvénient principal : Trop lent pour les taches numériquesintensives.

Solution : Interfacer avec C / C++ ou Fortran.

Taches de pré et post-traitement en Python.Parties numériques intensives en Fortran ou C / C++.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 139 / 174

Page 140: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

f2py : introduction

f2py“Fortran to Python interface generator” : module permettant deconvertir un code Fortran en modules et fonctions Python.

Remarque : f2py nécessite l’installation de Numpy. Trois méthodespour créer une interface sont possibles :

Interfacer des subroutines simples sans écrire de codesupplémentaire.

Ajouter des directives pour f2py dans le fichier source Fortran pourun interfaçage plus complexe.

Écrire un fichier d’interface décrivant les subroutines et lesdonnées à interfacer. f2py génère automatiquement un fichierd’interface simple qu’on peut ensuite éditer et modifier.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 140 / 174

Page 141: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Exemple de subroutine simpleCalcul de la norme : norme.f90 (Fortran 90/95 format libre).

subroutine norme (a, b, c)real(8), intent(in) :: a, breal(8), intent(out) :: cc= sqrt (a*a+b*b)end subroutine norme

Génération de l’interface Python avec f2py :

f2py -c norme.f90 -m vect --fcompiler=gnu95--f90flags=-O3

Appel depuis un shell Python :

>>> import vect>>> vect.norme(3,4)# 5.0

Documentation générée automatiquement par f2py :

>>> print vect.norme.__doc__norme - Function signature :c = norme(a,b)Required arguments :a : input floatb : input floatReturn objects :c : float

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 141 / 174

Page 142: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Ajout de directive f2py dans le source FortranRemarque :

Les ajouts dans le code source Fortran permettent de préciser le rôleet la définition des variables d’entrés-sorties. Sont utilisés :

Les attributs du F90 : intent(in), dimension(2,3).Les attributs spécifiques : !f2py intent(hide), depend(a).

subroutine norme_array(a,c,n)integer :: nreal(8),dimension(n),intent(in) :: a!f2py optional , depend(a) :: n=len(a)real(8),intent(out) :: creal(8) :: sommecinteger :: isommec = 0do i=1,n

sommec=sommec+a(i)*a(i)end doc=sqrt (sommec)end subroutine norme_array

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 142 / 174

Page 143: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Liste Python ou tableau numpy en argument

>>> from vect import *>>> a=[2,3,4] #Une liste Python>>> norme_array(a)# 5.3851648071345037>>> from numpy import *>>> a=arange(2,5) # Un tableau numpy>>> norme_array(a)# 5.3851648071345037

Documentation générée automatiquement par f2py :

>>> print norme_array.__doc__norme_array - Function signature :c = norme(a,[n])Required arguments :a : input rank-1 array(’d’) with bounds (n)Optional arguments :n := len(a) input intReturn objects :c : float

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 143 / 174

Page 144: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Utilisation du module distutils

setup.pyfrom numpy.distutils.core import setup, Extension

ext = Extension(name=’vect’,sources=["norme.f90"],extra_compile_args=[’-O3’])

setup(name=’vect’,version=’1.0’,description=’norm functions’,author=’Laurent’,author_email=’[email protected]’,url=’’,ext_modules=[ext])

#python setup.py build_ext --inplace

Ajouter dans le module vect la fonction norme_arrayEcrire un fichier test_vect qui teste les différentes fonctions dumodule vect.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 144 / 174

Page 145: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Utilisation d’un fichier signature

On peut générer automatiquement un fichier signature

f2py vecteur.f90 -h vecteur.pyf

Contenu de vecteur.pyf

! -*- f90 -*-! Note: the context of this file is case sensitive.

subroutine norme_array(a,c,n) ! in norme.f90real(kind=8) dimension(n),intent(in) :: areal(kind=8) intent(out) :: cinteger optional,check(len(a)>=n),depend(a) :: n=len(a)

end subroutine norme_array

! This file was auto-generated with f2py (version:2).! See http://cens.ioc.ee/projects/f2py2e/

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 145 / 174

Page 146: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Interfaçage C / C++ : motivation

Conjecture de Syracuse :http://fr.wikipedia.org/wiki/Conjecture_de_Syracuse

1 Choisir u0.2 Si uk pair, uk+1 → uk

2 ;3 Si uk impair, uk+1 → 3uk + 1.

La conjecture affirme que, pour tout u0 > 0 , il existe un indice k telque uk = 1 ; le plus petit indice avec cette propriété est appelétemps de vol.

Les programmes suivants calculent les temps de vol f (u0) pour1 ≤ u0 ≤ N, N fixé.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 146 / 174

Page 147: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Programme C

syracuse.c#include <sys/time.h>#include <stdlib.h>#include <stdio.h>long syracuse(long n) {

long compteur = 0L ;while (n > 1){

if ((n&1)==0) n /= 2; else n = 3*n+1; compteur ++;}

return compteur ;}int main() {

const long N = 1000000;double t1, t2;long i , *flights ;flights = (long*)malloc(N*sizeof(long));for (i = 0; i <N; i++) flights[i] = syracuse(i+1);return EXIT_SUCCESS;

}

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 147 / 174

Page 148: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Programme Python

def syrac_python(n) :compteur=0x=nwhile (x!=1) :

if ((x&1)==0) :x /= 2

else:x=3*x+1

compteur += 1return compteur

if __name__ == "__main__":N = 1000000flights = [syrac_python(i) for i in range(1,N+1)]

$ gcc -O3 syrac.c$ time ./a.outreal 0m0.313suser 0m0.310ssys 0m0.002s

$ time python syrac_python.pyreal 0m34.082suser 0m32.709ssys 0m0.130s# + simple, 100 x plus lent ...

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 148 / 174

Page 149: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Interfaçage avec C / C++ : C-types

ctypesBibliothèque Python permettant d’accéder aux fonctions et symbolesd’une bibliothèque externe (en particulier, codée en C).

https://docs.python.org/2/library/ctypes.html

Remarques :Plus rapide que le Python pur.Permet d’appeler des fonctions définies dans des fichiers DLLsous Windows.La syntaxe diffère suivant les systèmes d’exploitation.Syntaxe différente du reste du code Python.il faut apprendre un nouveau langage.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 149 / 174

Page 150: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Ctypes : exemple

Clong syracuse(long n){

long compteur = 0L ;while (n > 1){

if ((n&1)==0)n /= 2;

elsen = 3*n+1;

compteur++;}return compteur ;

}/*gcc -fPIC -shared -O3 \

-o syrac.so syrac.c*/

Pythonimport time

from ctypes import *syrac_ctypes=

CDLL("./syrac_ctypes.so")N=1000000t0 = time.time()flights =

[syrac_ctypes.syracuse(i)for i in range(1,N+1)]

t1 = time.time()print"Ctypes elapsed time %s"%(t1-t0)# elapsed time 0.891623973846

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 150 / 174

Page 151: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Interface d’une fonction C avec f2py

f2pyModule qui permet aussi d’interfaçer le C et le Python.

Clong syracuse(long n){

long compteur = 0L ;while (n > 1){

if ((n&1)==0)n /= 2;

elsen = 3*n+1;

compteur ++; }return compteur ;

}

syrac.pyfpython module syrac_cinterfacesubroutine syracuse(n,f)

intent(c) :: syracuseintent(c)integer(8), intent(in) :: ninteger(8), intent(out) :: f

end subroutine syracuseend python module syrac_c

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 151 / 174

Page 152: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Le programme Python

test_syrac.pyfrom numpy import *import timeN=10000000import syrac_f2pyt0 = time.time()flights =

[syrac_f2py.syracuse(i) for i in range(1, N+1)]t1 = time.time()print "f2py-C elapsed time %s"%(t1-t0)

Compilation et exécution :$ f2py -c syrac.c -m syrac_f2py syrac_f2py.pyf --opt=-O3$ python test_syrac.py# f2py-C elapsed time 8.69262194633

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 152 / 174

Page 153: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Utilisation du module distutils

setup.pyfrom numpy.distutils.core import setup, Extension

ext2 = Extension(name=’syrac_f2py’,sources=[’syrac.pyf’, "syrac.c"]

setup(name=’syrac_f2py’,version=’1.0’,description=’syrac functions’,author=’Laurent’,author_email=’[email protected]’,url=’’,ext_modules=[ext2])

#python setup.py build_ext --inplace

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 153 / 174

Page 154: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Interfaçage C / C++ et Python : autre possibilités

Swig

“Simplified Wrapper and Interface Generator“ : logiciel permettant deconnecter le C/C++ avec des langages de scripts tels que : Tcl, Perl,Python, Ruby, PHP etc. ou d’autres langages de programmationcomme Java.

http://www.swig.org/

CythonLangage hybride C/Python qui permet d’améliorer la création demodules compilés plus performants (non abordé ici).

http://cython.org/

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 154 / 174

Page 155: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Swig : exemple

Fichier d’interface swig syrac.i de la fonction dans syrac.c%module syracuseC%{

extern long syracuse(long n);%}extern long syracuse(long n);

Création d’un fichier syrac_wrap.c :

swig -python syrac.i

Compilation de la librairie dynamique :

$gcc ‘python2.6-config --cflags‘ -fPIC \-shared -O3 -o _syrac_swig.so syrac_wrap.c syrac.c

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 155 / 174

Page 156: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Performances de swig

Pythonfrom numpy import *import timeimport syracuseC

syracuse = syracuseC.syracuse

N=1000000flights = empty((N),int)t1 = time.time()flights[:] = map(syracuse,

xrange(1,N+1))t2 = time.time()print "elapsed time %s"%(t2-t1)

$ python test_syrac.py# elapsed time 0.870338201523

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 156 / 174

Page 157: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

X.1 WRAPPER

Utilisation du module distutils

setup.pyfrom numpy.distutils.core import setup, Extension

ext3 = Extension(name=’_syrac_swig’,sources=[’syrac_wrap.c’, ’syrac.c’],extra_compile_args=[’-O3’])

setup(name=’syrac_swig’,version=’1.0’,author="Laurent",description="swig syracuse",ext_modules=[ext3],py_modules=["syrac_swig"])

#python setup.py build_ext --inplace

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 157 / 174

Page 158: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XI. SCRIPTS

Hello world program

Code dans un fichier

#fichier hw.pyimport sys,mathr = float(sys.argv[1])s = math.sin(r)print("Hello world! sin("+str(r)+")="+str(s))

Execution

python hw.py 1.4

Résultat

Hello world! sin(1.4)=0.9854497299884601

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 158 / 174

Page 159: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XI. SCRIPTS

Exercice

TâcheEcrire un script qui renvoie une note aléatoire avec un chiffre après lavirguleCode

#Execution: python note_aleatoire.py#Renvoie une note aleatoire#avec un chiffre apres la virguleimport random as rnote = r.uniform(0,20)print("%.1f" % note)

Résultat

4.3

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 159 / 174

Page 160: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XI. SCRIPTS

Calculatrice

>>> 23//3 #division entiere7>>> 23./3. #division reelle7.666666666666667>>> 23%3 #reste2>>> 3.11+2.08 #addition5.1899999999999995>>> _-5.19 #_ est le dernier element-8.881784197001252e-16>>> [2**k for k in xrange(10)][1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 160 / 174

Page 161: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XI. SCRIPTS

Variables

Les variables permettent de stocker des données. Le nom desvariables ne peut pas commencer par un chiffre, ni par certainsmots-clés

>>> import keyword>>> a=keyword.kwlist>>> a[0] #premier mot-cle’False’>>> a[len(a)-1] #dernier mot-cle’yield’>>> a=10;a+=1;a>>> 11>>> a=1;b=2;[a,b]=[b,a];a,b #echange>>>(2, 1)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 161 / 174

Page 162: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XI. SCRIPTS

Types et comparaisons

Les opérateurs de comparaisons sont

is,is not,==,!=,<,>,<=,>=.

>>> ({3,3.} == {3}) and ({3,3.} is not {3})True

Les types sont nombreux

>>> a=[3,3.,True,[3,True],{3,3.},(3,3)]>>> [type(i) for i in a[0:3]][<class ’int’>, <class ’float’>, <class ’bool’>]>>> [type(i) for i in a[3:6]][<class ’list’>, <class ’set’>,<class ’tuple’>]

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 162 / 174

Page 163: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XI. SCRIPTS

Script avec boucles, fonctions et fichiers

Indentation obligatoire

#python fdata.py fin.dat fout.datimport sys, mathtry:

infilename = sys.argv[1]outfilename = sys.argv[2]

except:print("Usage:",sys.argv[0], "infile outfile")sys.exit()

infile = open(infilename, ’r’)outfile = open(outfilename, ’w’)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 163 / 174

Page 164: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XI. SCRIPTS

Script avec boucles, fonctions et fichiers

def myfunc(y):if y>=0.:return y**5*math.exp(-y)

else:return 0.

#Lit infile ligne par ligne#puis ecrit les valeurs transformeesfor line in infile:pair = line.split()x = float(pair[0])y = float(pair[1])fy = myfunc(y)outfile.write(’%g %12.5e\n’ % (x,fy))

infile.close()outfile.close()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 164 / 174

Page 165: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XI. SCRIPTS

On aura stocké dans ’fin.dat’

0.0 3.20.5 4.31.0 8.33332.5 -0.25

On obtient dans ’fout.dat’

0 1.36775e+010.5 1.99469e+011 9.66004e+002.5 0.00000e+00

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 165 / 174

Page 166: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XII. CLASSES

Programmation Objet avec Python

En programmation procédurale il y a une séparation stricte entre codeet données. En programmation objet les opérations sont des propriétésdes données.

Une classe python est composée d’attributs et de méthodes.

Instance : Création d’un objet, appel de la méthode nommée__init__.

Héritage : Un objet qui dérive d’un autre objet possède les mêmesattributs et les mêmes méthodes.

Quand une méthode est appelée, une référence vers l’objetprincipal est passé en tant que premier argument. Par conventionce premier argument est toujours : self.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 166 / 174

Page 167: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XII. CLASSES

Une classe Python

Définition

class MaClasse:def __init__(self, i, j):

self.i = i; self.j = jdef write(self):

print MaClasse: i=self.i, j=self.j

L’argument self est obligatoire pour la définition.

Utilisation

>>> obj1 = MaClasse(6,9)>>> print obj1.i, obj1.j6 9>>> obj1.write()MaClasse: i= 6 j= 9

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 167 / 174

Page 168: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XII. CLASSES

Héritage

Définition de la sous classe

class MaSousClasse(MaClasse):def __init__(self, i, j, k):

MaClasse.__init__(self,i,j)self.k = k

def write(self):print ’MaSousClasse: i=’,self.i,’j=’,self.j, \

’k=’, self.k

Utilisation

>>> obj1 = MaClasse(6,9)>>> obj1.write()MaClasse: i= 6 j= 9>>> obj2 = MaSousClasse(6,9,12)>>> obj2.write()MaSousClasse: i = 6 j= 9 k = 12

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 168 / 174

Page 169: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XII. CLASSES

Une classe qui s’utilise comme une fonction

Définition

class F:def __init__(self, a=1, b=1, c=1):

self.a=a; self.b=b; self.c=cdef __call__(self, x, y):

return self.a+self.b*x+self.c*y*y

Appel

>>> f = F(a=2,b=4)>>> v = f(2,1) + f(1.2,0)>>> print v17.8

Pratique lorsque l’on souhaite séparer les paramètres d’une fonction(a,b,c) des variables indépendantes (x,y).

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 169 / 174

Page 170: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XII. CLASSES

Surcharge des opérateurs

Une classe vecteur

class Vecteur:dimension = 2def __init__(self, x=0, y=0):

self.x=xself.y=y

def __eq__(self, vB):return (self.x==vB.x) and (self.y==vB.y)

def __add__(self, vB):return Vecteur(self.x+vB.x,self.y+vB.y)

def __sub__(self, vB):return Vecteur(self.x-vB.x,self.y-vB.y)

def __mul__(self, c):if isinstance(c,Vecteur):

return self.x*c.x+self.y*c.yelse:

return Vecteur(c*self.x,c*self.y)

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 170 / 174

Page 171: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XII. CLASSES

Surcharge des opérateurs (suite)

Manipulation

>>> U = Vecteur(); U.x,U.y = 0,1>>> V = Vecteur(); V.x,V.y = 1,0>>> print U, V<__main__.Vecteur instance at 0x2b8ee0> <__main__.Vecteur instance at 0x2b8f30>>>> W = U+V>>> print W<__main__.Vecteur instance at 0x2b8f80>>>> Vecteur.dimension=3>>> print 'Dimension de U=' + str(U.dimension)Dimension de U=3>>> print 'Dimension de V=' + str(V.dimension)Dimension de V=3>>> U.dimension=4>>> print 'Dimension de V=' + str(V.dimension)Dimension de V=3>>> Vecteur.dimension=5>>> print 'Dimension de U=' + str(U.dimension)Dimension de U=4>>> print 'Dimension de V=' + str(V.dimension)Dimension de V=5

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 171 / 174

Page 172: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XII. CLASSES

Créer une classe Python nommée Vecteur, que l’on utilisera pourdécrire un vecteur plan. Ces paramètres sont x et y . Implémenterl’addition __add__, la soustraction __sub__, la multiplication __mul__par un vecteur ou un scalaire et la représentation __repr__. Ne pasoublier le constructeur __init__.Attention votre multiplication n’est pas commutative par dÈfaut, il fautimplémenter la méthode __rmul__.Créer une classe nommée Particule, dont les paramètres sont lesvecteurs position et vitesse. Implémenter une méthode "deplace(dt)"pour calculer la nouvelle position d’une particule après un pas detemps dt . Créer ensuite une classe Ion dérivant de Particule avec unparamètre supplémentaire "masse".

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 172 / 174

Page 173: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XII. CLASSES

Classes abstraites

Les classe abstraites ne peuvent pas être instanciéesNe peuvent exister que si elles ont des sous-classesOn définit un concept commun à plusieurs objets (interface)Cette interface doit être la même ; permet d’È́viter de faire des tests surtous les types possibles.from abc import ABCMeta, abstractmethodclass BaseClass(object):__metaclass__=ABCMeta@abstractmethoddef printHello(self):

passclass GermanClass(BaseClass):def printHello(self):

print("Hallo")class FrenchClass(BaseClass):def printHello(self):

print("Bonjour")x = GermanClass()x.printHello()y = FrenchClass()y.printHello()

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 173 / 174

Page 174: PIP: Certification python mehrenbe/slides_cours_python.pdf · PIP: Certification python Marcela Szopos, Michel Mehrenberger, Laurent Navoret, Pierre Navaro Université de Strasbourg

XII. CLASSES

Ecrire une classe abstraite pour interpoler une fonction de [a,b] dansR.

Szopos-Mehrenberger-Navoret-Navaro (UDS) Python 28 mars 2015 174 / 174