1 Documentation and Resources
* Download:
o Requirements: Python, IPython, Numpy, Scipy, Matplotlib
o Windows: google "windows download (Python,IPython,Numpy,Scipy,Matplotlib"
o Debian based: sudo apt-get install python ipython numpy scipy matplotlib
* Screencast for IPython
o http://showmedo.com/videos/video?name=1000010&fromSeriesID=100
* Documentation for Plotting
o http://matplotlib.sourceforge.net/matplotlib.pyplot.html\#-subplot o http://matplotlib.sourceforge.net/
* Documentation for Arrays/Matrices/Linear Algebra o http://www.scipy.org/Numpy_Example_List_With_Doc o http://www.scipy.org/Cookbook
2 Getting Started with Numerical Computations in Python
Listing 1: Numpy examples
1 #!/ usr/bin/env python from numpy import ∗
from numpy . l i n a l g import ∗
# defining matrices
6 A = a r r a y ( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] , dtype = f l o a t ) print ’3 x3 identity matrix ’
print eye ( 3 )
print ’3 x3 matrix filled with 1 ’ print ones ( ( 3 , 3 ) )
11 print ’ repeat matrix along the first axis ’ print r e p e a t (A, 2 , a x i s =1)
print ’ array with 3 elements equally spaced from 0 to 5 ’ print l i n s p a c e ( 0 , 5 , 3 )
print ’ populate matrix ’
16 G = a r r a y ( [ [ s i n ( x)+ c o s ( y ) for x in l i n s p a c e ( 0 , 2∗pi , 4 ) ] for y in l i n s p a c e ( 2∗pi , 4∗pi , 4 ) ] )
print G
print ’ functions operate elementwise on arrays ’ G = s i n (G)
21
# modifying matrices
print ’ transpose of a 2 dim array ’ G t r a n s p o s e d = G.T
26 print ’ second column of A ’ print G [ : , 1 ]
print ’ second column and all rows but the last ’ print G[ :−1 , 1 ]
x = l i n s p a c e ( 0 , 5 , 1 0 )
31 print ’ whole vector x ’ print x
print ’ every second element ’ print x [ : : 2 ]
print ’ every second element in reverse ’
36 print x [ : :−2 ]
# l i n a l g procedures print ’rank (G )= ’,
2 GETTING STARTED WITH NUMERICAL COMPUTATIONS IN PYTHON
41 print rank (G)
print ’ matrix multiplication if 2D arrays A \ cdot B ’ print dot ( ones ( ( 3 , 3 ) ) , d i a g ( [ 1 , 2 , 3 ] ) )
print ’ inner product ’
print dot ( [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ) # works also on l i s t s
46 print ’ dyadic product v v^T ’ print o u t e r ( [ 1 , 2 , 3 ] , [ 4 , 5 ] )
print ’ elementwise multiplication A[i ,j ]* D[i ,j] ’ print G ∗ G t r a n s p o s e d
51
print ’ inverse of G ’ try:
i n v (G) # t h i s wont work since rank(G)=2 and G a 4x4 matrix except:
56 print ’ matrix inversion failed ’
print ’ solve A x=b ’ b = a r r a y ( [ 1 , 2 , 3 ] )
A = d i a g ( ones ( 3 ) ) + d i a g ( ones ( 2 ) , k=1) + d i a g ( ones ( 2 ) , k=−1)
61 x = s o l v e (A, b ) print x
Listing 2: Pylab examples
#!/ usr/bin/env python
2 from pylab import ∗ import numpy as npy
# figur e with two overlayed plots x = l i n s p a c e ( 0 , 1 0 , 1 0 0 )
7 y = s i n ( x ) z = c o s ( x ) f i g u r e ( )
p1=p l o t ( x , y ,’b - ’) p2=p l o t ( x , z ,’r. ’)
12 x l a b e l (’lala ’) y l a b e l (’ dumdedum ’)
l e g e n d ( ( p1 , p2 ) , (’foo ’,’bar ’) )
t e x t ( 2 , 0 . 5 , r’some text with Latex code $ i \ frac {d }{ dt } \ Psi = H \ Psi $ ’) arrow ( 0 , 0 , 2 , 1 )
17 g r i d (’on ’) t i t l e (’foo ’)
s a v e f i g (’lala . eps ’)
# figur e with subplots
22 f i g u r e ( ) s u b p l o t ( 2 , 2 , 1 ) p1=p l o t ( x , y ,’b - ’) s u b p l o t ( 2 , 2 , 2 ) p2=p l o t ( x , y ,’r - ’)
27 s u b p l o t ( 2 , 2 , 3 ) p3=p l o t ( x , y ,’g - ’) s u b p l o t ( 2 , 2 , 4 ) p4=p l o t ( x , y ,’k - ’) s a v e f i g (’ subplots . eps ’)
32
# figur e with contour plots of z=f (x , y)= xˆT A x
# A i n d e f i n i t e matrix A = d i a g ( [ 3 ,−2 ] )
x i = npy . r [−1 0 : 1 0 : 1 0 0 j ]
37 X,Y = meshgrid ( xi , x i )
x = X. r a v e l ( ) # make i t 1D array y = Y. r a v e l ( )
xy = a s a r r a y ( z i p ( x , y ) ) . T
z = d i a g ( dot ( xy . T, dot (A, xy ) ) ) # t h i s can d e f i n i t e l y be done more elegantly ; )
42 z = z . r e s h a p e ( 1 0 0 , 1 0 0 ) f i g u r e ( )
imshow ( z ) c o l o r b a r ( )
s a v e f i g (’ imshow . eps ’)
47## Contour plot f i g u r e ( )
c o n t o u r ( xi , xi , z ) c o l o r b a r ( )
s a v e f i g (’ contour . eps ’)
52 f i g u r e ( )
### ContourF plot c o n t o u r f ( xi , xi , z ) c o l o r b a r ( )
s a v e f i g (’ contourf . eps ’)
57 show ( ) #pops up some windows
Listing 3: Pitfalls examples
1 #!/ usr/bin/env python from numpy import ∗
# a l l objects are passed as references
# for example d i c t i o n a r i e s (hash maps, c al l e d map in c++)
6 a ={ ’foo ’: ’bar ’, 2 : 1} print a
c = a
c [’foo ’] = ’lala ’ print c
11 print a
# or arrays A = ones ( ( 2 , 2 ) ) B = A
16 B[ 0 , 0 ] = 1 2 . 3 2 3 print A
# a l l ? No, int , f l o a t , etc are immutable in Python a = 13
21 b = a b = 32 print a
# solution
26 C = A. copy ( ) C[ 0 , 1 ] = 1 2 3 4 5 6
print A
31# at the moment: integer di v i s i o n by standard ( changes in Python 3000) print 2/3 # output : 0
print 2 . / 3 #output 0.666666666
Listing 4: general stuff
1 #!/ usr/bin/env python from numpy import ∗ print ’ output formatting ’
6 print ’ fixed number of integer digits ’
print ’ an int with at least 5 digits length : %5 d ’%−23 print ’fill whitespaces with 0 ’
print ’%05 d ’%43
print ’ floating point ’
11 print ’%2.7 f ’%−1.23254234
3 OBJECT ORIENTED PROGRAMMING print ’%2.7 f ’%−1232323.2
print ’ exponential representation ’ print ’%e ’%(6.23∗10∗∗23)
print ’ insert a string %s ’%’ INPUTSTRING ’
16
# elementary datatypes
print ’ dictionary (= hash map ) ’
mydict = {’1 ’: 0 , 2 :’lala ’, ’ myarray ’: a r r a y ( [ 1 , 2 , 3 ] )}
21 print ’ access with ’
print mydict [’1 ’] , mydict [ 2 ] , mydict [’ myarray ’] print ’list ’
m y l i s t = [ 1 ,’2 ’, 3 ]
26
c l a s s m y c l a s s : a=1 b=2
myobject = m y c l a s s ( )
31 myobject . a = 2 myobject . b = 3
myobject . c = 4 # t h i s also works
# looping and i f then e l s e
36 for i in range ( 1 0 ) : # very slow ! ! ! print i
i = 0
while True : # slow ! ! !
41 print i
i = i + 1 i f i ==9:
break e l i f i == 8 :
46 print ’8 yay ! ’
e l s e:
print ’. ’
51 print ’ normal functions ’ def f (A, x ) :
return dot (A, x ) x = l i n s p a c e ( 0 , 9 , 1 0 ) A = ones ( ( 1 0 , 1 0 ) )
56 print f (A, x )
print ’ lambda functions ( anonymous functions ) ’ f = lambda x : x∗∗2
61 print ’pass functions as argument of functions ’ def f ( g ) :
return g ( 1 . 5 ) print f (lambda x : x∗∗2)
3 Object Oriented Programming
Listing 5: Algorithmic differentiation
1 #!/ usr/bin/env python import numpy
c l a s s adouble ( o b j e c t ) :
""" derive the class from object """
6 def i n i t ( s e l f , x , dx = 0 ) :
""" this function is automatically called when >>> a = adouble (0) , i.e. runs some initialization . Usually called CONSTRUCTOR
"""
s e l f . x = x
11 s e l f . dx = dx
def s t r ( s e l f ) :
""" string representation of adouble :
i.e. the result you see when you do : >>> print adouble (0) """
16 return ’[%f ,% f] ’%( s e l f . x , s e l f . dx ) def m u l ( s e l f , r h s ) :
""" multiplication between doubles and / or adboules a*b is equivalent to a. __mul__ (b)
21 """
i f numpy . i s s c a l a r ( r h s ) :
return adou ble ( s e l f . x ∗ rhs , s e l f . dx ∗ r h s ) e l s e:
return adou ble ( s e l f . x ∗ r h s . x , s e l f . x ∗ r h s . dx + s e l f . dx ∗ r h s . x )
26
def r m u l ( s e l f , l h s ) :
""" 2 * adouble (0) is equivalent to 2. __mul__ ( adouble (0)) , but integers dont have this functionality .
therefore this must be a right multipilcation , i.e.
31 adouble (0). __mul (2)
"""
return s e l f∗l h s i f n a m e == " __main__ ":
36 ### t h i s i s only executed i f t h i s s c r i p t i s ca l l e d
###by $python a l g o r i t h m i c d i f f e r e n t i a t i o n . py a = adouble ( 2 , 1 )
b = adoub le ( 3 ) print a ∗ b
41 print a ∗ 2 . print 2 ∗ a
0 2 4 6 8 10
-1.0 lala -0.5 0.0 0.5 1.0
dumd edum
some text with Latex code
idtd Ψ=HΨfoo foo
bar
Fig.3.1: Output produced by Listing 2.
3 OBJECT ORIENTED PROGRAMMING
0 2 4 6 8 10
-1.0 -0.5 0.0 0.5 1.0
0 2 4 6 8 10
-1.0 -0.5 0.0 0.5 1.0
0 2 4 6 8 10
-1.0 -0.5 0.0 0.5 1.0
0 2 4 6 8 10
-1.0 -0.5 0.0 0.5 1.0
Fig.3.2: Output produced by Listing 2.
-10 -5 0 5 10
-10 -5 0 5 10
-160 -80 0 80 160 240
(a)
-10 -5 0 5 10
-10 -5 0 5 10
-240 -160 -80 0 80 160 240 320
(b)
0 20 40 60 80
0
20
40
60
80
-200 -150 -100 -50 0 50 100 150 200 250
(c)
Fig.3.3: Output produced by Listing 2. File contour.eps in a) and contourf.eps in b). In c) imshow has been used, it plots the value of every matrix entry in a different color.