Introduction to Python
and Scientific Python
Fran¸cois Bianco
Unige
21th Dec 2011
Fran¸cois Bianco Introduction to Python
Outlook
1 Python features and syntax
2 Examples, pylab, and iPython
3 Flat files examples
Based on :
Learn Python in 10 minutes :
http://www.poromenos.org/tutorials/python
Python documentation : http://docs.python.org/index.html
Matplotlib : http://matplotlib.sourceforge.net/
Scipy : http://www.scipy.org/
Fran¸cois Bianco Introduction to Python
Python is
Strongly typed (i.e. types are enforced)
Dynamically, implicitly typed (i.e. you don’t have to declare
variables)
Python is
case sensitive (i.e. var and VAR are two different variables)
object-oriented (i.e. everything is an object)
able to handle memory by itself (i.e has a garbadge collector)
Fran¸cois Bianco Introduction to Python
Example
Example
l i s t = [1 ,1.1 ,1+1 j , ’ 1 ’ , True ]
for element in l i s t :
print element , type ( element ) , element==1.1
No mandatory statement termination character
Blocks are specified by indentation (4 spaces, or 1 tab)
Statements that expect an indentation level end in a colon “:”
Values are assigned (in fact, objects are bound to names) with
the equals sign “=”
Equality testing is done using two equals signs “==”
Fran¸cois Bianco Introduction to Python
Data structures
Three main data structures
list = [1,2,3,4,5,6] are mutable
tuples = (1,2,3,4,5,6) are unmutable
dictionary = { ’key’:’value’, ’answer’:42, ’obj’:list } also called
hash tables, access by key
List and tuples are access by index : list[index] (see array slicing).
Dictionary by key dictionary[’answer’].
Fran¸cois Bianco Introduction to Python
Modules loading
Classes and functions are stored in modules
from math import s i n #only one f u n c t i o n
s i n ( 0 . 3 )
import math #the whole module keeping namespace
math . s i n ( 0 . 3 )
from math import * #the whole module
cos ( 0 . 3 )
import m a t p l o t l i b as mptl #rename namespace
mptl . c o n v e r t e r ()
Fran¸cois Bianco Introduction to Python
Other features of Python
Modern way of handling errors
try :
f i l e O b j = open ( ’ fileName . t x t ’ )
except IOError :
print ErrorMessage
Lambda functions
f i t f u n c = lambda x , y : s q r t ( x/y )
f i t f u n c ( 4 . 5 , 2 . 3 )
Fran¸cois Bianco Introduction to Python
Other features of Python
Classes, functions...
def functionName ( param , optionalParam=value ) : . . .
class C h i l d C l a s s ( ParentClass ) : . . .
Automatic documentation generation (with Doxygen)
def toggleImages ( s e l f , event ) :
””” Toggle the two images according
to the t r i g g e r event .
param event Key or mouse event
t r i g g e r i n g the f u n c t i o n
”””
Fran¸cois Bianco Introduction to Python
Flow control statements
Example: Fibonnaci in a simple while loop
a , b = 0 ,1
while b<10:
print b
a , b = b , a+b
Easy variables assignation, and permutation, no extra variable
needed.
Fran¸cois Bianco Introduction to Python
Array slicing
Example: access to specific elements in an array
x = arange (10) #c r e a t e a vector from 0 to 9
x #the whole vector
x [ 0 ] #only the f i r s t element
x [ 3 ] #the 3 rd element
x [ −2] #the second l a t e s t element
x [ 1 : 4 ] #elements from 1 to 4
x [ : 5 ] #elements up to 5
x [ −3:] #the three l a s t elements
Fran¸cois Bianco Introduction to Python
Array masking
Example: create a mask on an array
a = arange (10)
mask = (( a % 2) == 0)
a [ mask ] = 0
This sets all the even value in a to 0.
Fran¸cois Bianco Introduction to Python
Easy plot
Example : plot with label and LATEX title
p l o t ( arange (5))
x l a b e l ( ’ Index ’ )
y l a b e l ( ’Sum ’ )
t i t l e ( r ’ $sum { i =0}ˆ i n f t y i $ ’ )
Fran¸cois Bianco Introduction to Python
Display matrix as an image
Example : create an image from a matrix
x = randn (20 ,20) #c r e a t e a random 20 x20 matrix
imshow ( x ) #p i x e l s c a l e
imshow ( x , extent =(0 ,1 ,0 ,1)) #add custom s c a l e
Fran¸cois Bianco Introduction to Python
Histogramm plot
Example : create an histogramm plot
mu, sigma = 100 , 15
x = mu + sigma * randn (10000)
h i s t ( x ,100)
Fran¸cois Bianco Introduction to Python
Many plots
Example : create two plots with legend
t = arange (0 ,5 ,0.05) # Vect . 0 , 0 . 0 5 , 0 . 1 , . . . , 5
s1=s i n (2* pi * t )
s2=s1 *exp(−t )
p l o t ( t , s1 , ’g−−o ’ , t , s2 , ’ r : s ’ ) # custom s t y l e s
legend (( ’ Sin wave ’ , ’Damped exp . ’ ))
Fran¸cois Bianco Introduction to Python
iPython
Usefull magic commands in iPython
help ( obj ) #Show help
obj ? #Show doc s t r i n g
obj ?? #Show source code
#r e t u r n l a s t value
%who #l i s t o b j e c t s
%whos #d e t a i l l e d o b j e c t s l i s t
%h i s t −n #h i s t o r y without l i n e number
%exec In [ 4 : 7 ] #redo l i n e 4 to 7
%e d i t 4:7 #e d i t l i n e 4 to 7 in s c r i p t
%run #launch a s c r i p t
% p f i l e #show source f i l e content
You want more of it ? Try %lsmagic
Fran¸cois Bianco Introduction to Python
Pro and cons
Cons
No GUI
Documentation spread on different websites
Requires basics programming skills
Pro
Easy to learn
Work on every plateform (WinXP,Vista,MacOS,Linux,...)
Could be bind to Gwyddion
It’s a free software
Fran¸cois Bianco Introduction to Python
Other good reasons to learn Python
Used by different universities and research centers : University
of Montreal, Princeton University, Space Telescope Science
Institute, Los Alamos National Laboratory, UC Berkeley, CERN,
NASA ...
If you want to look for a job in some “small” companies :
Google, HP, IBM, Nokia, Thawte Consulting (SSL certificates), EA
Games, Industrial Light & Magic (Hollywood), ...
Fran¸cois Bianco Introduction to Python
The end
“There should be one – and preferably only one –
obvious way to do it.”
Tim Peters, The Zen of Python
Fran¸cois Bianco Introduction to Python

Introduction to Python and Matplotlib

  • 1.
    Introduction to Python andScientific Python Fran¸cois Bianco Unige 21th Dec 2011 Fran¸cois Bianco Introduction to Python
  • 2.
    Outlook 1 Python featuresand syntax 2 Examples, pylab, and iPython 3 Flat files examples Based on : Learn Python in 10 minutes : http://www.poromenos.org/tutorials/python Python documentation : http://docs.python.org/index.html Matplotlib : http://matplotlib.sourceforge.net/ Scipy : http://www.scipy.org/ Fran¸cois Bianco Introduction to Python
  • 3.
    Python is Strongly typed(i.e. types are enforced) Dynamically, implicitly typed (i.e. you don’t have to declare variables) Python is case sensitive (i.e. var and VAR are two different variables) object-oriented (i.e. everything is an object) able to handle memory by itself (i.e has a garbadge collector) Fran¸cois Bianco Introduction to Python
  • 4.
    Example Example l i st = [1 ,1.1 ,1+1 j , ’ 1 ’ , True ] for element in l i s t : print element , type ( element ) , element==1.1 No mandatory statement termination character Blocks are specified by indentation (4 spaces, or 1 tab) Statements that expect an indentation level end in a colon “:” Values are assigned (in fact, objects are bound to names) with the equals sign “=” Equality testing is done using two equals signs “==” Fran¸cois Bianco Introduction to Python
  • 5.
    Data structures Three maindata structures list = [1,2,3,4,5,6] are mutable tuples = (1,2,3,4,5,6) are unmutable dictionary = { ’key’:’value’, ’answer’:42, ’obj’:list } also called hash tables, access by key List and tuples are access by index : list[index] (see array slicing). Dictionary by key dictionary[’answer’]. Fran¸cois Bianco Introduction to Python
  • 6.
    Modules loading Classes andfunctions are stored in modules from math import s i n #only one f u n c t i o n s i n ( 0 . 3 ) import math #the whole module keeping namespace math . s i n ( 0 . 3 ) from math import * #the whole module cos ( 0 . 3 ) import m a t p l o t l i b as mptl #rename namespace mptl . c o n v e r t e r () Fran¸cois Bianco Introduction to Python
  • 7.
    Other features ofPython Modern way of handling errors try : f i l e O b j = open ( ’ fileName . t x t ’ ) except IOError : print ErrorMessage Lambda functions f i t f u n c = lambda x , y : s q r t ( x/y ) f i t f u n c ( 4 . 5 , 2 . 3 ) Fran¸cois Bianco Introduction to Python
  • 8.
    Other features ofPython Classes, functions... def functionName ( param , optionalParam=value ) : . . . class C h i l d C l a s s ( ParentClass ) : . . . Automatic documentation generation (with Doxygen) def toggleImages ( s e l f , event ) : ””” Toggle the two images according to the t r i g g e r event . param event Key or mouse event t r i g g e r i n g the f u n c t i o n ””” Fran¸cois Bianco Introduction to Python
  • 9.
    Flow control statements Example:Fibonnaci in a simple while loop a , b = 0 ,1 while b<10: print b a , b = b , a+b Easy variables assignation, and permutation, no extra variable needed. Fran¸cois Bianco Introduction to Python
  • 10.
    Array slicing Example: accessto specific elements in an array x = arange (10) #c r e a t e a vector from 0 to 9 x #the whole vector x [ 0 ] #only the f i r s t element x [ 3 ] #the 3 rd element x [ −2] #the second l a t e s t element x [ 1 : 4 ] #elements from 1 to 4 x [ : 5 ] #elements up to 5 x [ −3:] #the three l a s t elements Fran¸cois Bianco Introduction to Python
  • 11.
    Array masking Example: createa mask on an array a = arange (10) mask = (( a % 2) == 0) a [ mask ] = 0 This sets all the even value in a to 0. Fran¸cois Bianco Introduction to Python
  • 12.
    Easy plot Example :plot with label and LATEX title p l o t ( arange (5)) x l a b e l ( ’ Index ’ ) y l a b e l ( ’Sum ’ ) t i t l e ( r ’ $sum { i =0}ˆ i n f t y i $ ’ ) Fran¸cois Bianco Introduction to Python
  • 13.
    Display matrix asan image Example : create an image from a matrix x = randn (20 ,20) #c r e a t e a random 20 x20 matrix imshow ( x ) #p i x e l s c a l e imshow ( x , extent =(0 ,1 ,0 ,1)) #add custom s c a l e Fran¸cois Bianco Introduction to Python
  • 14.
    Histogramm plot Example :create an histogramm plot mu, sigma = 100 , 15 x = mu + sigma * randn (10000) h i s t ( x ,100) Fran¸cois Bianco Introduction to Python
  • 15.
    Many plots Example :create two plots with legend t = arange (0 ,5 ,0.05) # Vect . 0 , 0 . 0 5 , 0 . 1 , . . . , 5 s1=s i n (2* pi * t ) s2=s1 *exp(−t ) p l o t ( t , s1 , ’g−−o ’ , t , s2 , ’ r : s ’ ) # custom s t y l e s legend (( ’ Sin wave ’ , ’Damped exp . ’ )) Fran¸cois Bianco Introduction to Python
  • 16.
    iPython Usefull magic commandsin iPython help ( obj ) #Show help obj ? #Show doc s t r i n g obj ?? #Show source code #r e t u r n l a s t value %who #l i s t o b j e c t s %whos #d e t a i l l e d o b j e c t s l i s t %h i s t −n #h i s t o r y without l i n e number %exec In [ 4 : 7 ] #redo l i n e 4 to 7 %e d i t 4:7 #e d i t l i n e 4 to 7 in s c r i p t %run #launch a s c r i p t % p f i l e #show source f i l e content You want more of it ? Try %lsmagic Fran¸cois Bianco Introduction to Python
  • 17.
    Pro and cons Cons NoGUI Documentation spread on different websites Requires basics programming skills Pro Easy to learn Work on every plateform (WinXP,Vista,MacOS,Linux,...) Could be bind to Gwyddion It’s a free software Fran¸cois Bianco Introduction to Python
  • 18.
    Other good reasonsto learn Python Used by different universities and research centers : University of Montreal, Princeton University, Space Telescope Science Institute, Los Alamos National Laboratory, UC Berkeley, CERN, NASA ... If you want to look for a job in some “small” companies : Google, HP, IBM, Nokia, Thawte Consulting (SSL certificates), EA Games, Industrial Light & Magic (Hollywood), ... Fran¸cois Bianco Introduction to Python
  • 19.
    The end “There shouldbe one – and preferably only one – obvious way to do it.” Tim Peters, The Zen of Python Fran¸cois Bianco Introduction to Python