Académique Documents
Professionnel Documents
Culture Documents
Scientific Python
Yann Tambouret
Scientific Computing and Visualization
Information Services & Technology
Boston University
111 Cummington St.
yannpaul@bu.edu
October, 2012
Scientific Python
October 2012
1 / 76
This Tutorial
This tutorial is for someone with basic python
experience.
First:
1
2
3
4
Scientific Python
October 2012
2 / 76
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.
matplotlib
Scientific Python
October 2012
3 / 76
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 Axes ,
which contain many plots.
pyplot creates a default Figure and
Axes if you just want get to plotting
things quickly.
matplotlib
Scientific Python
October 2012
3 / 76
Basic Example
1
2
3
4
5
6
7
8
9
Scientific Python
October 2012
4 / 76
Scientific Python
October 2012
5 / 76
practice/world_population.py
3 def get_data ():
4
data = file ( " w o r l d _ p o p u l a t i o n . txt " , " r " ). readlines ()
5
dates = []
6
populations = []
7
for point in data :
8
date , population = point . split ()
9
dates . append ( date )
10
populations . append ( population )
11
return dates , populations
Scientific Python
October 2012
6 / 76
practice/world_population.py
3 def get_data ():
4
data = file ( " w o r l d _ p o p u l a t i o n . txt " , " r " ). readlines ()
5
dates = []
6
populations = []
7
for point in data :
8
date , population = point . split ()
9
dates . append ( date )
10
populations . append ( population )
11
return dates , populations
1
2
Scientific Python
October 2012
6 / 76
practice/world_population.py
3 def get_data ():
4
data = file ( " w o r l d _ p o p u l a t i o n . txt " , " r " ). readlines ()
5
dates = []
6
populations = []
7
for point in data :
8
date , population = point . split ()
9
dates . append ( date )
10
populations . append ( population )
11
return dates , populations
1
2
Scientific Python
October 2012
6 / 76
Scientific Python
October 2012
7 / 76
Scientific Python
October 2012
8 / 76
Scientific Python
October 2012
9 / 76
Scientific Python
October 2012
10 / 76
1
2
3
4
5
Scientific Python
October 2012
11 / 76
Scientific Python
October 2012
12 / 76
Plotting Interactively
1
Scientific Python
October 2012
13 / 76
Plotting Interactively
1
Scientific Python
October 2012
13 / 76
Plotting Interactively
1
Scientific Python
October 2012
13 / 76
Plotting Interactively
1
3
4
Scientific Python
October 2012
13 / 76
Plotting Interactively
1
3
4
is an alternative to pyplot.show()
when you are using pyplot non-interactively.
pyplot.savefig(filename)
Scientific Python
October 2012
13 / 76
Matplotlib Resources
Possibilities:
matplotlib.org/gallery.html
http://matplotlib.org/basemap/users/examples.html
Guide/Tutorial:
matplotlib.org/users/index.html
Questions:
stackoverflow.com
Or contact us: help@scv.bu.edu
Source for tutorial:
openhatch.org/wiki/Matplotlib
Yann - yannpaul@bu.edu (SCV)
Scientific Python
October 2012
14 / 76
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
Scientific Python
October 2012
15 / 76
Array Creation
A 2D array:
1 A = np . array (((1 ,0 ,0) ,
2
(0 , 0 , -1) ,
3
(0 , 1 , 0)))
Scientific Python
October 2012
16 / 76
Array Creation
np.ones(5)
np.zeros
Scientific Python
October 2012
17 / 76
Array Creation
Scientific Python
October 2012
17 / 76
Array Creation
np.arange,
Scientific Python
October 2012
18 / 76
Scientific Python
October 2012
19 / 76
Basic Operations
Scientific Python
October 2012
20 / 76
Basic Operations
Scientific Python
])
October 2012
20 / 76
Scientific Python
October 2012
21 / 76
Calculating Neighbors
Scientific Python
October 2012
22 / 76
Scientific Python
October 2012
23 / 76
A Practice Problem
In the
1
practice
conway.py
directory:
is a program; try it out.
Scientific Python
October 2012
24 / 76
A Practice Problem
directory:
1
conway.py is a program; try it out.
2
conway work.py is an assignment; try to do it.
3
test conway.py is a program to test your work.
Remember, the shape attribute:
In the
practice
Scientific Python
October 2012
24 / 76
values.
1
2
3
4
5
6
7
8
>>> a
array ([[0 , 1 , 2] ,
[3 , 4 , 5] ,
[6 , 7 , 8]])
>>> np . roll (a , 1 , axis =0)
array ([[6 , 7 , 8] ,
[0 , 1 , 2] ,
[3 , 4 , 5]])
neighbors
Scientific Python
function.
October 2012
25 / 76
>>> b
array ([[ 0. , 0. , 0.] ,
[ 2. , 2. , 2.] ,
[ 0. , 3. , 0.]])
>>> np . where ( b == 0)
( array ([0 , 0 , 0 , 2 , 2]) , array ([0 , 1 , 2 , 0 , 2]))
>>> np . where ( b == 0 , -1 , b )
array ([[ -1. , -1. , -1.] ,
[ 2. , 2. , 2.] ,
[ -1. , 3. , -1.]])
Scientific Python
np.where
October 2012
can
26 / 76
Matplotlib Imshow
0
1
2
3
4
5
6
7
Scientific Python
October 2012
27 / 76
Nearest Neighbors
Scientific Python
October 2012
28 / 76
Matplotlib Imshow
11 plt . imshow (a ,
12 #
interpolation = nearest ,
13
cmap = plt . winter () ,
14
origin = lower )
15 plt . show ()
Scientific Python
October 2012
29 / 76
Scientific Python
October 2012
30 / 76
Plenty More
www.scipy.org/Tentative_NumPy_Tutorial
Universal Functions section
PyTrieste Numpy Tutorial
Scientific Python
October 2012
31 / 76
Scientific Python
October 2012
32 / 76
Constants
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Scientific Python
October 2012
33 / 76
Scientific Python
October 2012
34 / 76
Scientific Python
October 2012
35 / 76
examples\zombie.py
Scientific Python
October 2012
36 / 76
ipython - plotting
Scientific Python
October 2012
37 / 76
Scientific Python
October 2012
38 / 76
ipython - Logging
Amazing interactive python.
You can log an interactive session:
1 In [1]: logstart mylogfile . py
Scientific Python
October 2012
39 / 76
ipython - Misc.
Amazing interactive python.
You can use ? instead of help().
In [1]: len? and Enter will print help
In fact you get even more information than the
standard help()
Tab-completion
Start typing a method, and pop-up help is shown
You need a newer version than Katanas, and
you need to type ipython qtconsole
Scientific Python
October 2012
40 / 76
Scientific Python
October 2012
41 / 76
Pool
creates a pool of processes that you
give tasks to perform. See in
multiprocessing.Pool
examples/mp_vowels_pool.py
16
17
18
19
20
21
Scientific Python
October 2012
42 / 76
map
24
Scientific Python
October 2012
43 / 76
apply async
takes a function and a sequence of
arguments and applies that function to that argument.
task pool.apply async
27
28
29
30
31
32
33
34
async_results = []
for word in words :
async_results . append (
task_pool . apply_async ( count_vowels ,
( word ,)))
task_pool . close () # no more tasks
task_pool . join () # wait here until all
Scientific Python
October 2012
44 / 76
task pool.map
39
40
41
Scientific Python
October 2012
45 / 76
Scientific Python
Scientific Python
October 2012
46 / 76
pass
pass
Scientific Python
October 2012
47 / 76
pass
pass
Scientific Python
October 2012
47 / 76
pass
pass
Scientific Python
October 2012
47 / 76
None
Scientific Python
October 2012
48 / 76
None
1 name = None
2 if name is None :
3
name = Johnny
Scientific Python
October 2012
48 / 76
"__main__"
Scientific Python
October 2012
49 / 76
"__main__"
# 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)
October 2012
49 / 76
The Docstring
This is an un-assigned string that is used for
documentation.
It can be at the top of a file, documenting a script
or module
or the first thing inside a function, documenting it.
Scientific Python
October 2012
50 / 76
The Docstring
This is an un-assigned string that is used for
documentation.
It can be at the top of a file, documenting a script
or module
or the first 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)
Scientific Python
October 2012
50 / 76
Keyword Arguments
Scientific Python
October 2012
51 / 76
Returning Values
A function can return multiple values.
Formally this creates a Tuple - an immutable list
Scientific Python
October 2012
52 / 76
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
Scientific Python
October 2012
52 / 76
string.format()
Scientific Python
October 2012
53 / 76
email = """
Subject : { subject }
Date : { mon :2 d }/{ day :2 d }/{ year :2 d }
Message : { msg }
"""
print email . format ( mon =10 , year =12 , day =31 ,
subject = Happy Halloween ,
msg = Booh )
Scientific Python
October 2012
54 / 76
>>>
...
...
...
...
>>>
...
...
Scientific Python
October 2012
55 / 76
Scientific Python
October 2012
56 / 76
subprocess
1 import subprocess
2 output = subprocess . call ([ ls , -1 ])
3 print " output = " , output
Scientific Python
October 2012
57 / 76
argparse
Scientific Python
October 2012
58 / 76
argparse
example
Look over
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
examples\argparse_ex.py
import sys
import argparse
parser = argparse . ArgumentParser ( description = Plot zombie statistics )
parser . add_argument ( prefix , help = the prefix for the plot filename )
parser . add_argument ( -p , dest = pop , default =500 , type = int ,
help = Set the startring population )
parser . add_argument ( -s , dest = show ,
help = Show the figure , action = store_true )
parser . add_argument ( city , help = Plot information for a specific city ,
nargs = ? , default = None )
args = sys . argv [1:]
params = parser . parse_args ( args )
print " prefix = " , params . prefix
print " pop = " , params . pop
if params . city is not None :
print " city = " , params . city
print " show ? "
if params . show :
print " yes ! "
else :
print " no : -( "
Scientific Python
October 2012
59 / 76
Scientific Python
October 2012
60 / 76
Scientific Python
October 2012
60 / 76
Scientific Python
October 2012
60 / 76
Scientific Python
October 2012
61 / 76
Scientific Python
October 2012
62 / 76
Scientific Python
October 2012
63 / 76
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
Scientific Python
October 2012
64 / 76
Slicing - 1
19
20
21
22
23
24
25
Scientific Python
October 2012
65 / 76
Slicing - 2
29
30
31
32
33
34
35
36
37
38
39
40
Scientific Python
October 2012
66 / 76
Array Copying
43
44
45
46
47
48
49
50
51
52
53
54
55
Scientific Python
October 2012
67 / 76
Scientific Python
October 2012
68 / 76
Scientific Python
October 2012
69 / 76
Scientific Python
October 2012
70 / 76
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 )
Scientific Python
October 2012
71 / 76
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
Scientific Python
October 2012
72 / 76
Scientific Python
October 2012
73 / 76
Scientific Python
October 2012
74 / 76
Resources
Scientific Python
October 2012
75 / 76
Exception Handling
Duck Typing
Virtualenv
Pandas
mpi4py
And many other useful things
Scientific Python
October 2012
76 / 76