Sei sulla pagina 1di 78

Scientic Python Tutorial

Scientic Python Yann Tambouret


Scientic Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu

October, 2012

Yann - yannpaul@bu.edu (SCV)

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

2 / 59

Beyond the Basics

Super Scripting

pass pass

is pythons way of saying Keep moving, nothing to see here....

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

3 / 59

Beyond the Basics

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.

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

3 / 59

Beyond the Basics

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!

1 def step1 (): 2 pass 3 step1 () # no error ! 4 step2 () # error , darn !


Yann - yannpaul@bu.edu (SCV) Scientic Python October 2012 3 / 59

Beyond the Basics

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

4 / 59

Beyond the Basics

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

4 / 59

Beyond the Basics

Super Scripting

"__main__"

Every module has a name, which is stored in __name__ The script/console that you are running is called "__main__".

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

5 / 59

Beyond the Basics

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)

Hi! Timmy ... Hows it going?


Scientic Python October 2012 5 / 59

Beyond the Basics

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.

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

6 / 59

Beyond the Basics

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

Beyond the Basics

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

7 / 59

Beyond the Basics

More on Functions

Returning Values
A function can return multiple values. Formally this creates a Tuple - an immutable list

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

8 / 59

Beyond the Basics

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

8 / 59

Beyond the Basics

String Formatting

string.format()

Strings can be paired with values to control printing.


4 5 6 7 8 9

>>> " 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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

9 / 59

Beyond the Basics

String Formatting

Keyword arguments to format


Its sometimes tricky to format many values You can name some of the format targets
9 10 11 12 13 14 15 16 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 )

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

10 / 59

Beyond the Basics

String Formatting

Keyword arguments to format result


13 14 15 16 17 18 19 20 21 22 23 24 >>> ... ... ... ... >>> ... ... 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 )

Subject : Happy Halloween Date : 10/31/12 Message : Booh

More features at: http://docs.python.org/library/string.html


Yann - yannpaul@bu.edu (SCV) Scientic Python October 2012 11 / 59

Beyond the Basics

Files

Basic File Manipulation


You create a le object with open(filename, r for reading, w for writing read() for single string readlines() for a list of lines close() when youre done.
1 outfile = open ( story . txt , w ) 2 outfile . write ( Once upon a time ...\ n ) 3 outfile . close () r)

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

12 / 59

Beyond the Basics

Files

csv reader and writer


For reading and writing comma-separated-values csv.reader for reading, csv.writer for writing Dialects option correspond to predened formats excel for excel output without needing to know the separator and quote characters
1 2 3 4 5 reader = csv . reader ( file ) for row in reader : # row is a list writer = csv . writer ( file ) writer . writerow ([1 ,2 ,3])

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

13 / 59

Beyond the Basics

Command line arguments

argparse

easy command line arguments

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

14 / 59

Beyond the Basics

Command line arguments

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 !

Beyond the Basics

External Programs

subprocess

running external programs

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

Yann - yannpaul@bu.edu (SCV)

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

Yann - yannpaul@bu.edu (SCV)

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 ()

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

18 / 59

Scientic Python

matplotlib

Basic Plot - Results

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

19 / 59

Scientic Python

matplotlib

World Population - Practice 1


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

We read in the data

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

20 / 59

Scientic Python

matplotlib

World Population - Practice 1


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

We read in the data For each line (point) we need to separate the date from population
Scientic Python October 2012 20 / 59

Yann - yannpaul@bu.edu (SCV)

Scientic Python

matplotlib

World Population - Practice 1


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

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

matplotlib

World Population - Practice 2


13 14 15 16 17 18 def plot_world_pop ( dates , populations ): pass dates , populations = get_data () plot_world_pop ( dates , populations ) pyplot . show ()

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

World Population - Getting Help


http://matplotlib.sourceforge.net/ Quick Search for pyplot.plot matplotlib.pyplot.plot http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plot

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

22 / 59

Scientic Python

matplotlib

World Population - Final

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

23 / 59

Scientic Python

matplotlib

Life Expectancy - Practice 1


practice/life_expectacies_usa.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from matplotlib import pyplot def get_data (): # each line : year , men , women data = file ( " l i f e _ e x p e c t a n c i e s _ u s a . txt " , " r " ). readlines () dates = [] men = [] women = [] # finish me ! return dates , men , women def p l o t _ e x p e c t a n c i e s ( dates , men , women ): pass dates , men , women = get_data () p l o t _ e x p e c t a n c i e s ( dates , men , women ) pyplot . show ()

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

24 / 59

Scientic Python

matplotlib

Life Expectancy - Practice 2


1 2 3 4 5

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

25 / 59

Scientic Python

matplotlib

Life Expectancy - Results

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

26 / 59

Scientic Python

matplotlib

Plotting Interactively
1

Home - Backward Foward - Control edit history

Yann - yannpaul@bu.edu (SCV)

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

Yann - yannpaul@bu.edu (SCV)

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

Yann - yannpaul@bu.edu (SCV)

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

Yann - yannpaul@bu.edu (SCV)

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)

is an alternative to pyplot.show() when you are using pyplot non-interactively.

Yann - yannpaul@bu.edu (SCV)

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

Yann - yannpaul@bu.edu (SCV)

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

Yann - yannpaul@bu.edu (SCV)

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

Yann - yannpaul@bu.edu (SCV)

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?

Yann - yannpaul@bu.edu (SCV)

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

Yann - yannpaul@bu.edu (SCV)

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

30 / 59

Scientic Python

numpy

Array Basics - Results


4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 >>> import numpy as np >>> x = np . array (((1 , 2 , 3) , (4 , 5 , 6))) >>> x . size # total number of elements 6 >>> x . ndim # number of dimensions 2 >>> x . shape # number of elements in each dimension (2 L , 3 L ) >>> x [1 ,2] # first index is the rows , then the column 6 >>> x [1] # give me 1 row array ([4 , 5 , 6]) >>> x [1][2] 6 >>> x . dtype dtype ( int32 )
Scientic Python October 2012 31 / 59

Yann - yannpaul@bu.edu (SCV)

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])

Yann - yannpaul@bu.edu (SCV)

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

])

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

32 / 59

Scientic Python

numpy

Solve Laplaces Equation 1a


Solve 2 u = 0

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

33 / 59

Scientic Python

numpy

Solve Laplaces Equation 1a


Solve 2 u = 0 Solve iteratively, each time changing u with following equation: n+1 n+1 n n ujn,+1 l = 1/4(uj +1,l + uj 1,l + uj ,l +1 + uj ,l 1 ) Just an averages of the neighboring points.

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

33 / 59

Scientic Python

numpy

Solve Laplaces Equation 1a


Solve 2 u = 0 Solve iteratively, each time changing u with following equation: n+1 n+1 n n ujn,+1 l = 1/4(uj +1,l + uj 1,l + uj ,l +1 + uj ,l 1 ) Just an averages of the neighboring points.

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

33 / 59

Scientic Python

numpy

Solve Laplaces Equation 1b


Solve 2 u = 0 Solve iteratively, each time changing u with following equation: n+1 n+1 n n ujn,+1 l = 1/4(uj +1,l + uj 1,l + uj ,l +1 + uj ,l 1 ) Just an averages of the neighboring points.

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

34 / 59

Scientic Python

numpy

Solve Laplaces Equation 1c


Solve 2 u = 0 Solve iteratively, each time changing u with following equation: n+1 n+1 n n ujn,+1 l = 1/4(uj +1,l + uj 1,l + uj ,l +1 + uj ,l 1 ) Just an averages of the neighboring points.

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

35 / 59

Scientic Python

numpy

Solve Laplaces Equation 1d


Solve 2 u = 0 Solve iteratively, each time changing u with following equation: n+1 n+1 n n ujn,+1 l = 1/4(uj +1,l + uj 1,l + uj ,l +1 + uj ,l 1 ) Just an average of the neighboring points. Repeat this calculation until rms (u n+1 u n ) < , some threshold Set some limit on total number of iterations practice/laplace.py

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

36 / 59

Scientic Python

numpy

Solve Laplaces Equation 2


First task:

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

Yann - yannpaul@bu.edu (SCV)

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

Yann - yannpaul@bu.edu (SCV)

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])

Yann - yannpaul@bu.edu (SCV)

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 ()

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

40 / 59

Scientic Python

numpy

Solve Laplaces Equation 3a

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

41 / 59

Scientic Python

numpy

Solve Laplaces Equation 3b

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

42 / 59

Scientic Python

numpy

Solve Laplaces Equation 3c

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

43 / 59

Scientic Python

numpy

Solve Laplaces Equation 3d


Second task:

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 )

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

44 / 59

Scientic Python

numpy

Solve Laplaces Equation 4a


Third task:

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

45 / 59

Scientic Python

numpy

Solve Laplaces Equation 4b

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 )

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

46 / 59

Scientic Python

numpy

Solve Laplaces Results


1 Pure python method takes 3.624 seconds 2 Numpy method takes 0.016 seconds

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

47 / 59

Scientic Python

numpy

Plenty More
www.scipy.org/Tentative_NumPy_Tutorial Universal Functions section PyTrieste Numpy Tutorial

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

48 / 59

Scientic Python

scipy

scipy: Many Useful Scientic Tools


http://docs.scipy.org/doc/scipy/reference/ tutorial/index.html Numpy Integration Optimization Interpolation FFT Linear Algebra Statistics And much more....
Yann - yannpaul@bu.edu (SCV) Scientic Python October 2012 49 / 59

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

50 / 59

Scientic Python

scipy

Zombie Apocalypse - ODEINT


http://www.scipy.org/Cookbook/Zombie_ Apocalypse_ODEINT

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

51 / 59

Scientic Python

scipy

Zombie Apocalypse - ODEINT

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

52 / 59

Scientic Python

scipy

Zombie Apocalypse - ODEINT


Look at
examples\zombie.py 5 def calc_rate ( P =0 , d =0.0001 , B =0.0095 , G =0.0001 , A =0. 6 def f (y , t ): 7 Si = y [0] 8 Zi = y [1] 9 Ri = y [2] 10 # the model equations ( see Munz et al . 2009) 11 f0 = P - B * Si * Zi - d * Si 12 f1 = B * Si * Zi + G * Ri - A * Si * Zi 13 f2 = d * Si + A * Si * Zi - G * Ri 14 return [ f0 , f1 , f2 ] 15 Z0 = 0 # initial zombie populati 16 R0 = 0 # initial death populatio 17 y0 = [ S0 , Z0 , R0 ] # initial condition vecto 18 t = np . linspace (0 , 5. , 1000) # time grid 19 # solve the DEs 20 soln = odeint (f , y0 , t )
Yann - yannpaul@bu.edu (SCV) Scientic Python October 2012 53 / 59

Scientic Python

ipython

ipython (1) - plotting


Amazing interactive python. Using the -pylab ag, you can get plotting for free
1 % ipython - pylab 2 ... 3 In [1]: plot ( range (10))

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

54 / 59

Scientic Python

ipython

ipython (2) - Magic Functions


Amazing interactive python. It provids Magic functions: cd - like unix change directory ls - list directory timeit - time execution of statement and so on ...

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

55 / 59

Scientic Python

ipython

ipython (3) - Logging


Amazing interactive python. You can log an interactive session:
1 In [1]: logstart mylogfile . py

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

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

56 / 59

Scientic Python

ipython

ipython (4) - 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 mtehod, and pop-up help is shown You need a newer version than Katanas, and you need to type ipython qtconsole

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

57 / 59

Conclusion

Resources
SCV help site Numpy Tutorial Scipy tutorial Scientic Python Tutorial Another Scientic Python Tutorial iPython Tutorial

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

58 / 59

Conclusion

What I Didnt Cover


Exception Handling Duck Typing Virtualenv Pandas mpi4py And many other useful things

Yann - yannpaul@bu.edu (SCV)

Scientic Python

October 2012

59 / 59

Potrebbero piacerti anche