Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
October, 2012
Scientic Python
October 2012
1 / 59
This Tutorial
This tutorial is for someone with basic python experience. First I begin with a few intermediate items not covered in basic tutorials. Then Ill provide a brief survey of the scientic packages available, including
1 2 3 4
matplotlib - plotting library, like Matlab numpy - fast arrays manipulation scipy - math methods galore. ipython - better interactive python
Scientic Python
October 2012
2 / 59
Super Scripting
pass pass
Scientic Python
October 2012
3 / 59
Super Scripting
pass pass
is pythons way of saying Keep moving, nothing to see here.... Its used for yet unwritten function. If you try to call a function that doesnt exist, you get an error.
Scientic Python
October 2012
3 / 59
Super Scripting
pass pass
is pythons way of saying Keep moving, nothing to see here.... Its used for yet unwritten function. If you try to call a function that doesnt exist, you get an error. pass just creates a function that does nothing. Great for planning work!
Super Scripting
None
is Pythons formal value for nothing Use this as a default value for a variable, or as a return value when things dont work, and you dont want a catastrophic error.
None
Scientic Python
October 2012
4 / 59
Super Scripting
None
is Pythons formal value for nothing Use this as a default value for a variable, or as a return value when things dont work, and you dont want a catastrophic error. Test if something is None, to see if you need to handle these special cases
None 1 name = None 2 if name is None : 3 name = Johnny
Scientic Python
October 2012
4 / 59
Super Scripting
"__main__"
Every module has a name, which is stored in __name__ The script/console that you are running is called "__main__".
Scientic Python
October 2012
5 / 59
Super Scripting
"__main__"
Every module has a name, which is stored in __name__ The script/console that you are running is called "__main__". Use this to make a le both a module and a script.
1 2 3 4 5 6 7 # module greeting . py def hey_there ( name ): print " Hi ! " , name , " ... How s it going ? " hey_there ( Joey ) if __name__ == " __main__ " : hey_there ( Timmy )
python greeting.py
Yann - yannpaul@bu.edu (SCV)
Super Scripting
The Docstring
This is an un-assigned string that is used for documentation. It can be at the top of a le, documenting a script or module or the rst thing inside a function, documenting it.
Scientic Python
October 2012
6 / 59
Super Scripting
The Docstring
This is an un-assigned string that is used for documentation. It can be at the top of a le, documenting a script or module or the rst thing inside a function, documenting it. This is what help() uses...
1 def dot_product ( v1 , v2 ): 2 """ Perform the dot product of v1 and v2 . 3 4 v1 is a three element vector . 5 v2 is a three element vector . 6 """ 7 sum = 0 # ....
Yann - yannpaul@bu.edu (SCV) Scientic Python October 2012 6 / 59
More on Functions
Keyword Arguments
Arguments that have default values. In the function signature, keyword=default_value None is a good default if you want to make a decision
1 def hello ( name = Joe , repeat = None ): 2 if repeat is None : 3 repeat = len ( name ) 4 print Hi ! , name * repeat
Scientic Python
October 2012
7 / 59
More on Functions
Returning Values
A function can return multiple values. Formally this creates a Tuple - an immutable list
Scientic Python
October 2012
8 / 59
More on Functions
Returning Values
A function can return multiple values. Formally this creates a Tuple - an immutable list You can collect the returned values as a Tuple, or as individual values.
1 2 3 4 5 def pows ( val ): return val , val * val , val * val * val two , four , eight = pows (2) ones = pows (1) print ones [0] , ones [1] , ones [2] # 1 1 1
Scientic Python
October 2012
8 / 59
String Formatting
string.format()
>>> " Hi there {}! " . format ( Yann ) Hi there Yann ! >>> " Coords : {} , {}; " . format ( -1 , 2) Coords : -1 , 2; >>> " {1} , the cost is {0:.2 f } " . format (1125.747025 , Y Yann , the cost is 1125.75
Scientic Python
October 2012
9 / 59
String Formatting
Scientic Python
October 2012
10 / 59
String Formatting
Files
Scientic Python
October 2012
12 / 59
Files
Scientic Python
October 2012
13 / 59
argparse
module is the easiest way. You rst create a ArgumentParser object You dene the allowable arguments with the add_argument function You can add required or optional arguments sys.argv is a list of arguments passed to the program/script. Pass this list to parse_args function to process and get an object with your parameters dened.
argparse
Scientic Python
October 2012
14 / 59
argparse
example
examples\argparse_ex.py
Look over
1 import sys 2 import argparse 3 p a r s e r = a r g p a r s e . A r g u m e n t P a r s e r ( d e s c r i p t i o n= P l o t z o m b i e s t a t i s t i 4 p a r s e r . a d d a r g u m e n t ( p r e f i x , h e l p= t h e p r e f i x f o r t h e p l o t f i l e n a 5 p a r s e r . a d d a r g u m e n t ( p , d e s t= pop , d e f a u l t =500 , t y p e=i n t , 6 h e l p= S e t t h e s t a r t r i n g p o p u l a t i o n ) 7 p a r s e r . a d d a r g u m e n t ( s , d e s t= show , 8 h e l p= Show t h e f i g u r e , a c t i o n= s t o r e t r u e ) 9 p a r s e r . a d d a r g u m e n t ( c i t y , h e l p= P l o t i n f o r m a t i o n f o r a s p e c i f i c 10 n a r g s= ? , d e f a u l t=None ) 11 12 a r g s = s y s . a r g v [ 1 : ] 13 params = p a r s e r . p a r s e a r g s ( a r g s ) 14 15 p r i n t p r e f i x = , params . p r e f i x 16 p r i n t pop = , params . pop 17 i f params . c i t y i s n o t None : 18 p r i n t c i t y = , params . c i t y 19 p r i n t show ? 20 i f params . show : Yann (SCV) Scientic Python October 2012 15 / 59 21 - yannpaul@bu.edu print y es !
External Programs
subprocess
1 import subprocess 2 output = subprocess . call ([ ls , -1 ]) 3 print " output = " , output
provides many tools The most basic is the call function. It takes a list that is joined and executed. output just holds the exit code (0 if successful) check_output is like call but 1) returns output and 2) causes an error if program fails
subprocess
Scientic Python
October 2012
16 / 59
Scientic Python
matplotlib
Plotting in scripts
is a package that has many modules, pyplot is the main driver. matplotlib is designed for both interactive and script-based use. a Figure can contain many Axess which contain many plots. pyplot allows you to access a default Figure and Axes.
matplotlib
Scientic Python
October 2012
17 / 59
Scientic Python
matplotlib
Basic Example
1 2 3 4 5 6 7 8 9 from matplotlib import pyplot pyplot . plot ([0 , 2 , 4 , 8 , 16 , 32] , " o " ) pyplot . ylabel ( " Value " ) pyplot . xlabel ( " Time " ) pyplot . title ( " Test plot " ) pyplot . show ()
Scientic Python
October 2012
18 / 59
Scientic Python
matplotlib
Scientic Python
October 2012
19 / 59
Scientic Python
matplotlib
Scientic Python
October 2012
20 / 59
Scientic Python
matplotlib
1 2
We read in the data For each line (point) we need to separate the date from population
Scientic Python October 2012 20 / 59
Scientic Python
matplotlib
1 2
We read in the data For each line (point) we need to separate the date from population split() splits text at any whitespace, by default.
Scientic Python October 2012 20 / 59
Scientic Python
matplotlib
Finish this method: 1 Make a plot of population (y) vs dates (x) 2 Title: World population over time 3 Y-axis: World population in millions 4 X-axis: Year 5 Set the plot type to a Magenta, downward-triangle
Yann - yannpaul@bu.edu (SCV) Scientic Python October 2012 21 / 59
Scientic Python
matplotlib
Scientic Python
October 2012
22 / 59
Scientic Python
matplotlib
Scientic Python
October 2012
23 / 59
Scientic Python
matplotlib
Scientic Python
October 2012
24 / 59
Scientic Python
matplotlib
Use split(,) to split strings at commas Add a label to each plot (look at documentation) Label Axes and give a title. Call plot 2x to plot two lines Add a legend: pyplot.legend http://matplotlib.sourceforge.net search for pyplot.legend
Scientic Python
October 2012
25 / 59
Scientic Python
matplotlib
Scientic Python
October 2012
26 / 59
Scientic Python
matplotlib
Plotting Interactively
1
Scientic Python
October 2012
27 / 59
Scientic Python
matplotlib
Plotting Interactively
1
Home - Backward Foward - Control edit history Pan - Zoom - Left click + drag shifts center, right click + drag changes zoom
Scientic Python
October 2012
27 / 59
Scientic Python
matplotlib
Plotting Interactively
1
Home - Backward Foward - Control edit history Pan - Zoom - Left click + drag shifts center, right click + drag changes zoom Zoom - Select zoom region
Scientic Python
October 2012
27 / 59
Scientic Python
matplotlib
Plotting Interactively
1
3 4
Home - Backward Foward - Control edit history Pan - Zoom - Left click + drag shifts center, right click + drag changes zoom Zoom - Select zoom region Save
Scientic Python
October 2012
27 / 59
Scientic Python
matplotlib
Plotting Interactively
1
3 4
Home - Backward Foward - Control edit history Pan - Zoom - Left click + drag shifts center, right click + drag changes zoom Zoom - Select zoom region Save
pyplot.savefig(filename)
Scientic Python
October 2012
27 / 59
Scientic Python
matplotlib
Matplotlib Resources
Possibilities: matplotlib.sourceforge.net/gallery.html http://matplotlib.org/basemap/users/ examples.html Guide/Tutorial: matplotlib.sourceforge.net/users/index. html Questions: stackoverflow.com Or contact us: scv@bu.edu Source for tutorial: openhatch.org/wiki/Matplotlib
Yann - yannpaul@bu.edu (SCV) Scientic Python October 2012 28 / 59
Scientic Python
numpy
Array Creation
By convention:
import numpy as np
Scientic Python
October 2012
29 / 59
Scientic Python
numpy
Array Creation
By convention:
import numpy as np x = np.array([1,2,3], int);
x is a Numpy array x is like a list, but certain operations are much faster
Scientic Python
October 2012
29 / 59
Scientic Python
numpy
Array Creation
By convention:
import numpy as np x = np.array([1,2,3], int);
x is a Numpy array x is like a list, but certain operations are much faster A = np.array(((1,0,0), (0, 0, -1), (0, 1, 0))) is a 2D array
Scientic Python
October 2012
29 / 59
Scientic Python
numpy
Array Creation
By convention:
import numpy as np x = np.array([1,2,3], int);
x is a Numpy array x is like a list, but certain operations are much faster A = np.array(((1,0,0), (0, 0, -1), (0, 1, 0))) is a 2D array np.ones(5) makes array([ 1., 1., 1., 1., 1.]) np.zeros or np.arange, what do they do?
Scientic Python
October 2012
29 / 59
Scientic Python
numpy
Array Creation
By convention:
import numpy as np x = np.array([1,2,3], int);
x is a Numpy array x is like a list, but certain operations are much faster A = np.array(((1,0,0), (0, 0, -1), (0, 1, 0))) is a 2D array np.ones(5) makes array([ 1., 1., 1., 1., 1.]) np.zeros or np.arange, what do they do? np.linspace is similar to np.arange but pass number of elements, not step size
Scientic Python
October 2012
29 / 59
Scientic Python
numpy
Array Basics
3 4 5 6 7 8 9 10 11 import numpy as np x = np . array (((1 , 2 , 3) , (4 , 5 , 6))) x . size # total number of elements x . ndim # number of dimensions x . shape # number of elements in each dimension x [1 ,2] # first index is the rows , then the column x [1] # give me 1 row x [1][2] x . dtype
Scientic Python
October 2012
30 / 59
Scientic Python
numpy
Scientic Python
numpy
Basic Operations
14 x = np . array ([0 , np . pi /4 , np . pi /2]) 15 np . sin ( x ) 16 np . dot ([2 , 2 , 2] , [2 , 2 , 2])
Scientic Python
October 2012
32 / 59
Scientic Python
numpy
Basic Operations
14 x = np . array ([0 , np . pi /4 , np . pi /2]) 15 np . sin ( x ) 16 np . dot ([2 , 2 , 2] , [2 , 2 , 2]) 22 23 24 25 26 >>> x = np . array ([0 , np . pi /4 , np . pi /2]) >>> np . sin ( x ) array ([ 0. , 0.70710678 , 1. >>> np . dot ([2 , 2 , 2] , [2 , 2 , 2]) 12
])
Scientic Python
October 2012
32 / 59
Scientic Python
numpy
Scientic Python
October 2012
33 / 59
Scientic Python
numpy
Scientic Python
October 2012
33 / 59
Scientic Python
numpy
Scientic Python
October 2012
33 / 59
Scientic Python
numpy
Scientic Python
October 2012
34 / 59
Scientic Python
numpy
Scientic Python
October 2012
35 / 59
Scientic Python
numpy
Scientic Python
October 2012
36 / 59
Scientic Python
numpy
19 def pu r e _ p y t h o n _ s t e p ( u ): 20 Pure python imple mentati on of Gauss - Siedel method . Performs 21 iteration . 22 rms_err = 0 23 # use for loop to loop through each element in u 24 # temporarily store old value to later calculate rms_err 25 # update current u using 4 point averaging 26 # update running value of rms_err 27 # when done looping complete rms_err calculation and return it 28 return rms_err
Scientic Python
October 2012
37 / 59
Scientic Python
numpy
Slicing - 1
19 20 21 22 23 24 25 x = np . array ((1 , 2 , 3 , 4 , 5 , 6)) x [2] x [2:5] x [2: -1] x [:5] x [:5:2] = 10 x
Scientic Python
October 2012
38 / 59
Scientic Python
numpy
Slicing - 2
29 30 31 32 33 34 35 36 37 38 39 40 >>> x = np . array ((1 , 2 , 3 , 4 , 5 , 6)) >>> x [2] 3 >>> x [2:5] array ([3 , 4 , 5]) >>> x [2: -1] array ([3 , 4 , 5]) >>> x [:5] array ([1 , 2 , 3 , 4 , 5]) >>> x [:5:2] = 10 >>> x array ([10 , 2 , 10 , 4 , 10 , 6])
Scientic Python
October 2012
39 / 59
Scientic Python
numpy
Array Copying
43 44 45 46 47 48 49 50 51 52 53 54 55 >>> a = np . array ((1 ,2 ,3 ,4)) >>> b = a >>> b is a True >>> c = a . view () >>> c . shape = 2 ,2 >>> c [1 ,1]=10 >>> c array ([[ 1 , 2] , [ 3 , 10]]) >>> a array ([ 1 , 2 , 3 , 10]) >>> d = a . copy ()
Scientic Python
October 2012
40 / 59
Scientic Python
numpy
Scientic Python
October 2012
41 / 59
Scientic Python
numpy
Scientic Python
October 2012
42 / 59
Scientic Python
numpy
Scientic Python
October 2012
43 / 59
Scientic Python
numpy
35 def numpy_step ( u ): 36 Numpy based Jacobi s method . Performs one iteration . 37 # make a copy so that you can calculate the error 38 u_old = u . copy () 39 # use slicing to shift array 40 # utmp = u [1: -1 , 1: -1] makes a new array , so that utmp [0 ,0] is 41 # as u [1 ,1] 42 # then 43 # utmp = u [0: -2 , 1: -1] makes a new array that leads to a shift 44 # because utmp [0 ,0] is the same as u [0 , 1] 45 # use this concept to solve this equation in on line 46 # u = 1/4*( u_ {j -1 , i } + u_ { j +1 , i } + u_ {j , i -1} + u_ {j , i +1}) 47 return calc_err (u , u_old )
Scientic Python
October 2012
44 / 59
Scientic Python
numpy
4 def laplace _driver (u , stepper , maxit =100 , err =1 e3 ): 5 Repeatedly call stepper ( u ) to solve nabla ^2 u = 0 until 6 rms error < err or maxit number of iterations is reached . 7 8 u - a numpy array 9 stepper - a function whose sole argument is u 10 11 rms_err = 0 12 # take one step with stepper , to define initial rms_err 13 # loop until rms_err < err 14 # check to see that number of iterations is less than maxi 15 # perform single iteration using stepper method 16 # return rms_error 17 return rms_err
Scientic Python
October 2012
45 / 59
Scientic Python
numpy
59 def time_method ( stepper ): 60 Time how long a particular stepper takes to solve an ideal 61 u = set_bc ( np . zeros ((100 ,100))) 62 start = time . time () 63 err = la place_dr iver (u , stepper ) 64 return time . time () - start 65 66 if __name__ == " __main__ " : 67 p u r e _ p y t h o n _ t i m e = time_method ( p u r e _ p y t h o n _ s t e p ) 68 numpy_time = time_method ( numpy_step ) 69 print " Pure python method takes {:.3 f } seconds " . format ( p u r e _ p y 70 print " Numpy method takes {.3 f } seconds " . format ( numpy_time )
Scientic Python
October 2012
46 / 59
Scientic Python
numpy
Scientic Python
October 2012
47 / 59
Scientic Python
numpy
Plenty More
www.scipy.org/Tentative_NumPy_Tutorial Universal Functions section PyTrieste Numpy Tutorial
Scientic Python
October 2012
48 / 59
Scientic Python
scipy
Scientic Python
scipy
Constants
4 5 6 7 8 9 10 11 12 13 14 15 16 17 >>> from scipy import constants >>> constants . c # speed of light 299792458.0 >>> # physical constants : value , units , uncertainty >>> constants . p hy si ca l_ co ns ta nt s [ " electron mass " ] (9.10938291 e -31 , kg , 4e -38) >>> # look - up constants , only first 3 ! >>> masses = constants . find ( " mass " )[:3] >>> for val in masses : ... print " {} is available " . format ( val ) ... Planck mass is available Planck mass energy equivalent in GeV is available alpha particle mass is available
Scientic Python
October 2012
50 / 59
Scientic Python
scipy
Scientic Python
October 2012
51 / 59
Scientic Python
scipy
Scientic Python
October 2012
52 / 59
Scientic Python
scipy
Scientic Python
ipython
Scientic Python
October 2012
54 / 59
Scientic Python
ipython
Scientic Python
October 2012
55 / 59
Scientic Python
ipython
Everything you type will be recorded to mylogle.py To re-run it in ipython, us the run command:
1 In [1]: run -i mylogfile . py
Scientic Python
October 2012
56 / 59
Scientic Python
ipython
Scientic Python
October 2012
57 / 59
Conclusion
Resources
SCV help site Numpy Tutorial Scipy tutorial Scientic Python Tutorial Another Scientic Python Tutorial iPython Tutorial
Scientic Python
October 2012
58 / 59
Conclusion
Scientic Python
October 2012
59 / 59