+ All Categories
Home > Documents > Python Tutorial Slides 3[1]

Python Tutorial Slides 3[1]

Date post: 04-Jun-2018
Category:
Upload: husnu-aksakal
View: 244 times
Download: 0 times
Share this document with a friend

of 78

Transcript
  • 8/13/2019 Python Tutorial Slides 3[1]

    1/78

    Scientific Python TutorialScientific Python

    Yann TambouretScientific Computing and Visualization

    Information Services & TechnologyBoston University

    111 Cummington St.

    [email protected]

    October, 2012

    Yann - [email protected] (SCV) Scientific Python October 2012 1 / 59

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    2/78

    This Tutorial

    This tutorial is for someone with basic pythonexperience.

    First I begin with a few intermediate items notcovered in basic tutorials.

    Then Ill provide a brief survey of the scientificpackages available, including

    1 matplotlib - plotting library, like Matlab2 numpy - fast arrays manipulation3 scipy - math methods galore.4 ipython - better interactive python

    Yann - [email protected] (SCV) Scientific Python October 2012 2 / 59

    http://goforward/http://find/http://goback/
  • 8/13/2019 Python Tutorial Slides 3[1]

    3/78

  • 8/13/2019 Python Tutorial Slides 3[1]

    4/78

  • 8/13/2019 Python Tutorial Slides 3[1]

    5/78

    B d th B i S S i ti

  • 8/13/2019 Python Tutorial Slides 3[1]

    6/78

    Beyond the Basics Super Scripting

    None

    None is Pythons formal value for nothingUse this as a default value for a variable,

    or as a return value when things dont work,and you dont want a catastrophic error.

    Yann - [email protected] (SCV) Scientific Python October 2012 4 / 59

    Beyond the Basics Super Scripting

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    7/78

    Beyond the Basics Super Scripting

    None

    None is Pythons formal value for nothingUse 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 handlethese special cases

    1 name=None

    2 if name is None:3 nam e = J oh nn y

    Yann - [email protected] (SCV) Scientific Python October 2012 4 / 59

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    8/78

    Beyond the Basics Super Scripting

  • 8/13/2019 Python Tutorial Slides 3[1]

    9/78

    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 file both a module anda script.

    1 # m od ul e g re et in g . py

    2 def h e y _ t h e r e ( n a m e ) :

    3 print " Hi ! " , name , " ... How s it go in g ?"

    4

    5 h e y _ t h e r e ( J o e y )6 if _ _ na me __ == " _ _ ma in __ " :

    7 h e y _ t h e r e ( T i m m y )

    python greeting.py Hi! Timmy ... Hows it going?

    Yann - [email protected] (SCV) Scientific Python October 2012 5 / 59

    Beyond the Basics Super Scripting

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    10/78

    Beyond the Basics Super Scripting

    The Docstring

    This is an un-assigned string that is used fordocumentation.It can be at the top of a file, documenting a scriptor module

    or the first thing inside a function, documenting it.

    Yann - [email protected] (SCV) Scientific Python October 2012 6 / 59

    Beyond the Basics Super Scripting

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    11/78

    y p p g

    The Docstring

    This is an un-assigned string that is used fordocumentation.It can be at the top of a file, documenting a scriptor module

    or the first thing inside a function, documenting it.This is what help()uses...

    1 def d o t _ pr o du c t ( v1 , v 2 ):

    2 """ P er fo rm t he d ot p rod uct o f v1 a nd v2 .

    34 v1 is a three e leme nt v ecto r .

    5 v2 is a three e leme nt v ecto r .

    6 """

    7 sum = 0 #....

    Yann - [email protected] (SCV) Scientific Python October 2012 6 / 59

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    12/78

    Beyond the Basics More on Functions

  • 8/13/2019 Python Tutorial Slides 3[1]

    13/78

    y

    Returning Values

    A function can return multiple values.Formally this creates a Tuple- an immutablelist

    Yann - [email protected] (SCV) Scientific Python October 2012 8 / 59

    Beyond the Basics More on Functions

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    14/78

    Returning Values

    A function can return multiple values.Formally this creates a Tuple- an immutablelist

    You can collect the returned values as a Tuple, or asindividual values.

    1 def pows(val):

    2 return v al , v al * val , v al * v al * v al

    3 two , four , e ig ht = po ws ( 2)

    4 one s = pow s (1)

    5 print o ne s [ 0] , o ne s [ 1] , o ne s [ 2] # 1 1 1

    Yann - [email protected] (SCV) Scientific Python October 2012 8 / 59

    Beyond the Basics String Formatting

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    15/78

    string.format()

    Strings can be paired with values to control printing.4 > >> " H i t he re { }! " . f o r ma t ( Y ann )

    5 Hi t he re Y an n !

    6 > >> " C o or ds : {} , { }; " . f or ma t ( -1 , 2)

    7 Co or ds : -1 , 2; 8 > >> " {1} , t he c os t is { 0: .2 f } " . f or ma t ( 1 12 5. 74 70 25 ,

    9 Yann , the co st is 11 25 .75

    Yann - [email protected] (SCV) Scientific Python October 2012 9 / 59

    Beyond the Basics String Formatting

    http://find/http://goback/
  • 8/13/2019 Python Tutorial Slides 3[1]

    16/78

    Keyword arguments to format

    Its sometimes tricky to format many valuesYou can name some of the format targets

    9 em ail = """

    10 Su b je c t : { s u b je c t }

    11 D a te : { m on : 2 d } /{ d a y : 2 d } /{ y ea r : 2 d }12 M es s ag e : { m sg }

    13 """

    14 print e m ai l . f o r ma t ( m o n =1 0 , y ea r = 12 , d ay = 31 ,

    15 s u bj e ct = H ap py H a ll o we e n ,

    16 m s g = B o o h )

    Yann - [email protected] (SCV) Scientific Python October 2012 10 / 59

    Beyond the Basics String Formatting

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    17/78

    Keyword arguments to format result

    13 >>> email = " ""14 . .. S ub je ct : { s u bj ec t }

    15 . .. D at e : { m on : 2 d } /{ d a y : 2 d } /{ y ea r : 2 d }

    16 . .. M es sa ge : { m sg }

    17 ... " ""

    18 > >> p ri nt e ma il . f o rm at ( m on = 10 , y ea r =12 , da y =31 ,19 ... subject = Happy Halloween ,

    20 ... msg = Booh )

    21

    22 S ub j ec t : H ap py H a ll o we e n

    23 Da te : 1 0 /3 1 /1 2

    24 Me s sa g e : B oo h

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

    Yann - [email protected] (SCV) Scientific Python October 2012 11 / 59

    Beyond the Basics Files

    http://docs.python.org/library/string.htmlhttp://docs.python.org/library/string.htmlhttp://find/http://goback/
  • 8/13/2019 Python Tutorial Slides 3[1]

    18/78

    Basic File Manipulation

    You create a file object with open(filename, r)r for reading, w for writing

    read() for single string

    readlines() for a list of lines

    close() when youre done.

    1 o ut fi le = o pe n ( st or y . tx t , w )

    2 o ut fi le . w r it e ( On ce u po n a t im e . .. \ n )

    3 o u t f i l e . c l o s e ( )

    Yann - [email protected] (SCV) Scientific Python October 2012 12 / 59

    Beyond the Basics Files

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    19/78

    csv reader and writer

    For reading and writing comma-separated-valuescsv.reader for reading, csv.writerfor writing

    Dialects option correspond to predefined formats

    excel for excel output without needing to know theseparator and quote characters

    1 re ad er = c sv . r e ad er ( f i le )

    2 for row in reader:

    3 # row is a list4 wr it er = c sv . w r it er ( f i le )

    5 w r i te r . w r i te r o w ( [ 1 , 2 , 3] )

    Yann - [email protected] (SCV) Scientific Python October 2012 13 / 59

    Beyond the Basics Command line arguments

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    20/78

    argparse easy command line arguments

    argparse module is the easiest way.You first create a ArgumentParserobject

    You define the allowable arguments with theadd_argument function

    You can add required or optional arguments

    sys.argv is a list of arguments passed to theprogram/script.

    Pass this list to parse_argsfunction to process andget an object with your parameters defined.

    Yann - [email protected] (SCV) Scientific Python October 2012 14 / 59

    Beyond the Basics Command line arguments

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    21/78

    argparse example

    Look over examples\argparse_ex.py1 i m p o r t s y s2 i m p o r t a r g p a r s e3 p a r s e r = a r g p a r s e . A r gu m en t Pa r s er ( d e s c r i p t i o n = P l o t z om bi e s t a t i s t4 p a r s e r . a dd a rg u me nt ( p r e f i x , h e l p= t he p r e f i x f o r t he p l o t f i l e n a5 p a r s e r . a d d a r g u me n t ( p , d e s t = p op , 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 me n t ( s , d e s t = s ho w ,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 dd a rg u me nt ( c i t y , h e lp= P l ot 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 )1112 a r g s = s y s . a r g v [ 1 : ]

    13 p ar am s = p a r s e r . p a r s e a r g s ( a r g s )1415 p r i n t p r e f i x = , p ar ams . p r e f i x16 p r i n t pop = , params . pop17 i f p a ra m s . c i t y i s n o t None :18 p r i n t c i t y = , pa ram s . c i t y19 p r i n t s how ?

    20 i f par ams . show :21 p r i n t y e s ! Yann - [email protected] (SCV) Scientific Python October 2012 15 / 59

    Beyond the Basics External Programs

    http://find/http://goback/
  • 8/13/2019 Python Tutorial Slides 3[1]

    22/78

    subprocess running external programs

    1 import subprocess2 ou tp ut = s ub pr oc es s . c al l ([ ls , -1 ])

    3 print " o u tp ut = " , o ut pu t

    subprocess provides many tools

    The most basic is the callfunction.

    It takes a list that is joined and executed.

    output just holds the exit code (0 if successful)

    check_output is like callbut 1) returns output and 2)causes an error if program fails

    Yann - [email protected] (SCV) Scientific Python October 2012 16 / 59

    Scientific Python matplotlib

    http://find/http://goback/
  • 8/13/2019 Python Tutorial Slides 3[1]

    23/78

    Plotting in scripts

    matplotlibis a package that has manymodules, pyplotis the main driver.

    matplotlibis designed for bothinteractive and script-based use.

    a Figurecan contain many Axesswhich contain many plots.

    pyplotallows you to access a default

    Figureand Axes.

    Yann - [email protected] (SCV) Scientific Python October 2012 17 / 59

    Scientific Python matplotlib

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    24/78

    Basic Example

    1 from matplotlib import pyplot2

    3 py plot . plot ([0 , 2 , 4 , 8 , 16 , 32] , " o" )

    4

    5 p y p l o t . y l a b e l ( " V a l u e " )

    6 p y p l o t . x l a b e l ( " T i m e " )

    7 p yp lo t . t i t le ( " T e st p lo t " )

    8

    9 p y p l o t . s h o w ( )

    Yann - [email protected] (SCV) Scientific Python October 2012 18 / 59

    Scientific Python matplotlib

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    25/78

    Basic Plot - Results

    Yann - [email protected] (SCV) Scientific Python October 2012 19 / 59

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    26/78

  • 8/13/2019 Python Tutorial Slides 3[1]

    27/78

    Scientific Python matplotlib

  • 8/13/2019 Python Tutorial Slides 3[1]

    28/78

    World Population - Practice 1

    practice/world_population.py3 def g e t _ d a t a ( ) :4 d at a = f il e ( " w o r l d _p o p ul a t io n . t x t " , " r " ) . r e ad l in e s ( )5 dat es = []6 p o pu l at i on s = [ ]7 for point in d a t a :

    8 d ate , p op u la ti o n = p oi nt . s p li t ( )9 d a t e s . a p p e n d ( d a t e )10 p o p u l a t i o n s . a p p e n d ( p o p u l a t i o n )11 return d a te s , p o pu l a ti o ns

    1

    We read in the data2 For each line (point) we need to separate the date

    from population3 split() splits text at any whitespace, by default.

    Yann - [email protected] (SCV) Scientific Python October 2012 20 / 59

    Scientific Python matplotlib

    http://localhost/var/www/apps/conversion/tmp/scratch_6/practice/world_population.pyhttp://localhost/var/www/apps/conversion/tmp/scratch_6/practice/world_population.pyhttp://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    29/78

    World Population - Practice 2

    13 def pl o t _ w o r ld _ p o p ( d a te s , p o p u la t i o n s ) :14 pass

    15

    16 d ate s , p op ul at io ns = g et _d at a ( )

    17 p l o t _ w or l d _ p o p ( d a te s , p o p u l at i o n s )

    18 p y p l o t . s h o w ( )

    Finish this method:1 Make a plot of population (y) vs dates (x)2

    Title: World population over time3 Y-axis: World population in millions4 X-axis: Year5 Set the plot type to a Magenta,downward-triangle

    Yann - [email protected] (SCV) Scientific Python October 2012 21 / 59

    Scientific Python matplotlib

    W ld P l G H l

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    30/78

    World Population - Getting Helphttp://matplotlib.sourceforge.net/ Quick Search for pyplot.plot

    matplotlib.pyplot.plot

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

    Yann - [email protected] (SCV) Scientific Python October 2012 22 / 59

    Scientific Python matplotlib

    W ld P l i Fi l

    http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plothttp://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plothttp://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    31/78

    World Population - Final

    Yann - [email protected] (SCV) Scientific Python October 2012 23 / 59

    Scientific Python matplotlib

    Lif E P i 1

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    32/78

    Life Expectancy - Practice 1

    practice/life_expectacies_usa.py1 from matplotlib import pyplot23 def g e t _ d a t a ( ) :4 # e ac h l in e : ye ar , men , w om en5 d at a = f il e ( " l i f e _ e xp e c ta n c i es _ u sa . t xt " , " r " ). r e a d l in e s ( )

    6 dat es = []7 men = []8 wom en = []9 # f in is h me !

    10 return d at es , men , w om en1112 def p l o t _ ex p e ct a n c ie s ( d a te s , m en , w o me n ) :

    13 pass1415 da te s , men , w om en = g et _d at a ( )16 p l o t_ e x p ec t a n ci e s ( d a te s , m en , w om e n )17 p y p l o t . s h o w ( )

    Yann - [email protected] (SCV) Scientific Python October 2012 24 / 59

    Scientific Python matplotlib

    Lif E P i 2

    http://localhost/var/www/apps/conversion/tmp/scratch_6/practice/life_expectacies_usa.pyhttp://localhost/var/www/apps/conversion/tmp/scratch_6/practice/life_expectacies_usa.pyhttp://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    33/78

    Life Expectancy - Practice 2

    1

    Use split(,)

    to split strings at commas2 Add a label to each plot (look at documentation)3 Label Axes and give a title.4 Call plot 2x to plot two lines5 Add a legend: pyplot.legend

    http://matplotlib.sourceforge.net searchfor pyplot.legend

    Yann - [email protected] (SCV) Scientific Python October 2012 25 / 59

    Scientific Python matplotlib

    Lif E t R lt

    http://matplotlib.sourceforge.net/http://matplotlib.sourceforge.net/http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    34/78

    Life Expectancy - Results

    Yann - [email protected] (SCV) Scientific Python October 2012 26 / 59

    Scientific Python matplotlib

    Pl tti I t ti l

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    35/78

    Plotting Interactively

    1 Home - Backward -Foward- Control edit history

    Yann - [email protected] (SCV) Scientific Python October 2012 27 / 59

    Scientific Python matplotlib

    Pl tti I t ti l

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    36/78

    Plotting Interactively

    1 Home - Backward -Foward- Control edit history

    2 Pan - Zoom - Left click +drag shifts center, right click

    + drag changes zoom

    Yann - [email protected] (SCV) Scientific Python October 2012 27 / 59

    Scientific Python matplotlib

    Plotting Interacti el

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    37/78

    Plotting Interactively

    1

    Home - Backward -Foward- Control edit history

    2 Pan - Zoom - Left click +drag shifts center, right click

    + drag changes zoom3 Zoom- Select zoom region

    Yann - [email protected] (SCV) Scientific Python October 2012 27 / 59

    Scientific Python matplotlib

    Plotting Interactively

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    38/78

    Plotting Interactively

    1

    Home - Backward -Foward- Control edit history2 Pan - Zoom - Left click +

    drag shifts center, right click

    + drag changes zoom3 Zoom- Select zoom region4 Save

    Yann - [email protected] (SCV) Scientific Python October 2012 27 / 59

    Scientific Python matplotlib

    Plotting Interactively

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    39/78

    Plotting Interactively

    1

    Home - Backward -Foward- Control edit history2 Pan - Zoom - Left click +

    drag shifts center, right click

    + drag changes zoom3 Zoom- Select zoom region4 Save

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

    Yann - [email protected] (SCV) Scientific Python October 2012 27 / 59

    Scientific Python matplotlib

    Matplotlib Resources

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    40/78

    Matplotlib Resources

    Possibilities:matplotlib.sourceforge.net/gallery.htmlhttp://matplotlib.org/basemap/users/

    examples.html

    Guide/Tutorial:matplotlib.sourceforge.net/users/index.

    html

    Questions:

    stackoverflow.comOr contact us: [email protected] for tutorial:openhatch.org/wiki/Matplotlib

    Yann - [email protected] (SCV) Scientific Python October 2012 28 / 59

    Scientific Python numpy

    Array Creation

    http://localhost/var/www/apps/conversion/tmp/scratch_6/matplotlib.sourceforge.net/gallery.htmlhttp://matplotlib.org/basemap/users/examples.htmlhttp://matplotlib.org/basemap/users/examples.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/matplotlib.sourceforge.net/users/index.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/matplotlib.sourceforge.net/users/index.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/stackoverflow.comhttp://localhost/var/www/apps/conversion/tmp/scratch_6/[email protected]://localhost/var/www/apps/conversion/tmp/scratch_6/openhatch.org/wiki/Matplotlibhttp://localhost/var/www/apps/conversion/tmp/scratch_6/openhatch.org/wiki/Matplotlibhttp://localhost/var/www/apps/conversion/tmp/scratch_6/[email protected]://localhost/var/www/apps/conversion/tmp/scratch_6/stackoverflow.comhttp://localhost/var/www/apps/conversion/tmp/scratch_6/matplotlib.sourceforge.net/users/index.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/matplotlib.sourceforge.net/users/index.htmlhttp://matplotlib.org/basemap/users/examples.htmlhttp://matplotlib.org/basemap/users/examples.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/matplotlib.sourceforge.net/gallery.htmlhttp://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    41/78

    Array Creation

    By convention: import numpy as np

    Yann - [email protected] (SCV) Scientific Python October 2012 29 / 59

    http://find/http://goback/
  • 8/13/2019 Python Tutorial Slides 3[1]

    42/78

    Scientific Python numpy

    Array Creation

  • 8/13/2019 Python Tutorial Slides 3[1]

    43/78

    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 - [email protected] (SCV) Scientific Python October 2012 29 / 59

    Scientific Python numpy

    Array Creation

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    44/78

    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 - [email protected] (SCV) Scientific Python October 2012 29 / 59

    Scientific Python numpy

    Array Creation

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    45/78

    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

    arraynp.ones(5) makes array([ 1., 1., 1., 1., 1.])

    np.zeros or np.arange, what do they do?

    np.linspace is similar to np.arangebut pass number ofelements, notstep size

    Yann - [email protected] (SCV) Scientific Python October 2012 29 / 59

    Scientific Python numpy

    Array Basics

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    46/78

    Array Basics

    3 import n umpy as np

    4 x = np . array (((1 , 2 , 3) , (4 , 5 , 6)))

    5 x.size # t ot al n um be r of e le me nt s

    6 x.ndim # n um be r of d im en si on s

    7 x.shape # n um be r of e le me nt s in e ach d im en si on

    8 x[1,2] # first index is the rows , then the colu mn

    9 x[1] # give me 1 row10 x[1][2]

    11 x.dtype

    Yann - [email protected] (SCV) Scientific Python October 2012 30 / 59

    Scientific Python numpy

    Array Basics - Results

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    47/78

    Array Basics Results

    4 >> > i mport numpy as np

    5 >>> x = np . array (((1 , 2 , 3) , (4 , 5 , 6)))

    6 >> > x . s iz e # t ot al n um be r of e le me nt s

    7 6

    8 >> > x . n di m # n um be r of d im en si on s

    9 2

    10 > > > x . s h ap e # n um be r of e le me nt s in e ach d im en si on11 (2 L , 3 L)

    12 >> > x [ 1 ,2] # first index is the rows , then the col umn

    13 6

    14 >> > x [ 1] # give me 1 row

    15 a rr ay ( [4 , 5 , 6 ])16 > > > x [ 1 ] [2 ]

    17 6

    18 > > > x . d t yp e

    19 dtype ( int32 )

    Yann - [email protected] (SCV) Scientific Python October 2012 31 / 59

    Scientific Python numpy

    Basic Operations

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    48/78

    Basic Operations

    14 x = np . a rr ay ( [0 , np . pi /4 , np . pi / 2])

    15 n p . s i n ( x )

    16 np . dot ([2 , 2 , 2] , [2 , 2 , 2])

    Yann - [email protected] (SCV) Scientific Python October 2012 32 / 59

    Scientific Python numpy

    Basic Operations

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    49/78

    Basic Operations

    14 x = np . a rr ay ( [0 , np . pi /4 , np . pi / 2])

    15 n p . s i n ( x )

    16 np . dot ([2 , 2 , 2] , [2 , 2 , 2])

    22 > >> x = np . a rr ay ( [0 , np . pi /4 , np . pi / 2])

    23 > > > n p . si n ( x )

    24 array ([ 0. , 0.70710678 , 1. ])

    25 >>> np . dot ([2 , 2 , 2] , [2 , 2 , 2])

    26 12

    Yann - [email protected] (SCV) Scientific Python October 2012 32 / 59

    Scientific Python numpy

    Solve Laplaces Equation 1a

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    50/78

    Solve Laplace s Equation 1a

    Solve 2u= 0

    Yann - [email protected] (SCV) Scientific Python October 2012 33 / 59

    Scientific Python numpy

    Solve Laplaces Equation 1a

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    51/78

    p q

    Solve 2u= 0

    Solve iteratively, each time changing u withfollowing equation:u

    n+1j,l = 1/4(u

    nj+1,l+ u

    n+1j1,l+ u

    nj,l+1+ u

    n+1j,l1)

    Just an averages of the neighboring points.

    Yann - [email protected] (SCV) Scientific Python October 2012 33 / 59

    Scientific Python numpy

    Solve Laplaces Equation 1a

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    52/78

    p q

    Solve 2u= 0

    Solve iteratively, each time changing u withfollowing equation:u

    n+1j,l = 1/4(u

    nj+1,l+ u

    n+1j1,l+ u

    nj,l+1+ u

    n+1j,l1)

    Just an averages of the neighboring points.

    Yann - [email protected] (SCV) Scientific Python October 2012 33 / 59

    Scientific Python numpy

    Solve Laplaces Equation 1b

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    53/78

    p q

    Solve 2u= 0

    Solve iteratively, each time changing u withfollowing equation:u

    n+1j,l = 1/4(u

    nj+1,l+ u

    n+1j1,l+ u

    nj,l+1+ u

    n+1j,l1)

    Just an averages of the neighboring points.

    Yann - [email protected] (SCV) Scientific Python October 2012 34 / 59

    Scientific Python numpy

    Solve Laplaces Equation 1c

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    54/78

    p q

    Solve 2u= 0

    Solve iteratively, each time changing u withfollowing equation:u

    n+1j,l = 1/4(u

    nj+1,l+ u

    n+1j1,l+ u

    nj,l+1+ u

    n+1j,l1)

    Just an averages of the neighboring points.

    Yann - [email protected] (SCV) Scientific Python October 2012 35 / 59

    Scientific Python numpy

    Solve Laplaces Equation 1d

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    55/78

    p q

    Solve 2u= 0

    Solve iteratively, each time changing u withfollowing equation:u

    n+1j,l = 1/4(u

    nj+1,l+ u

    n+1j1,l+ u

    nj,l+1+ u

    n+1j,l1)

    Just an average of the neighboring points.Repeat this calculation until rms(un+1 un)< ,some threshold

    Set some limit on total number of iterationspractice/laplace.py

    Yann - [email protected] (SCV) Scientific Python October 2012 36 / 59

    Scientific Python numpy

    Solve Laplaces Equation 2

    http://localhost/var/www/apps/conversion/tmp/scratch_6/practice/laplace.pyhttp://localhost/var/www/apps/conversion/tmp/scratch_6/practice/laplace.pyhttp://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    56/78

    First task:19 def p u r e _ p y t h o n _ s t e p ( u ) :20 P ur e p yt ho n i m p le m en t at i on o f G au ss - S i ed el m et ho d . P e rf or m21 i t e r a t i o n . 22 r ms _e rr = 023 # u se for loop t o l oop th ro ug h e ach el em en t in u24 # t empo rar ily store old value to later calcu late rms_err

    25 # update current u using 4 point avera ging26 # update running value of rms_err27 # w h en d on e l o op in g c o mp le te r ms _e rr c al cu la ti on a nd r et ur n i28 return rms_err

    Yann - [email protected] (SCV) Scientific Python October 2012 37 / 59

    Scientific Python numpy

    Slicing - 1

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    57/78

    19 x = np . array ((1 , 2 , 3 , 4 , 5 , 6))

    20 x[2]

    21 x[2:5]

    22 x [ 2 : - 1 ]

    23 x[:5]

    24 x [ :5:2] = 10

    25 x

    Yann - [email protected] (SCV) Scientific Python October 2012 38 / 59

    Scientific Python numpy

    Slicing - 2

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    58/78

    29 >>> x = np . array ((1 , 2 , 3 , 4 , 5 , 6))

    30 >> > x [ 2]

    31 3

    32 >> > x [ 2: 5]

    33 a rr ay ( [3 , 4 , 5 ])

    34 >> > x [ 2: - 1 ]

    35 a rr ay ( [3 , 4 , 5 ])36 >> > x [ :5 ]

    37 array ( [1 , 2 , 3 , 4 , 5])

    38 >> > x [ :5:2] = 10

    39 >>> x

    40 array ([10 , 2 , 10 , 4 , 10 , 6])

    Yann - [email protected] (SCV) Scientific Python October 2012 39 / 59

    Scientific Python numpy

    Array Copying

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    59/78

    43 > >> a = np . a rr ay ( (1 , 2 , 3 , 4) )

    44 >>> b = a

    45 >>> b is a

    46 True

    47 >>> c = a .view ()

    48 >> > c . shape = 2 ,2

    49 >> > c [ 1 , 1] =1 050 >>> c

    51 array ([[ 1 , 2] ,

    52 [ 3 , 10]])

    53 >>> a

    54 array ([ 1, 2 , 3 , 10])55 >>> d = a .copy ()

    Yann - [email protected] (SCV) Scientific Python October 2012 40 / 59

    Scientific Python numpy

    Solve Laplaces Equation 3a

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    60/78

    Yann - [email protected] (SCV) Scientific Python October 2012 41 / 59

    Scientific Python numpy

    Solve Laplaces Equation 3b

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    61/78

    Yann - [email protected] (SCV) Scientific Python October 2012 42 / 59

    Scientific Python numpy

    Solve Laplaces Equation 3c

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    62/78

    Yann - [email protected] (SCV) Scientific Python October 2012 43 / 59

    Scientific Python numpy

    Solve Laplaces Equation 3d

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    63/78

    Second task:35 def n u m p y _ s t e p ( u ) :36 N um py b a se d J ac ob i s me th od . P e rf or ms o n e i te ra ti on . 37 # m ake a copy s o t hat you can c al cu la te the e rr or38 u _o ld = u . c op y ()39 # u se sl ic in g to sh if t a rr ay40 # utmp = u [1: -1 , 1: -1] m ake s a new array , s o t hat utmp [ 0 ,0] i

    41 # as u [1 ,1]42 # t he n43 # utmp = u [0: -2 , 1: -1] m ake s a new ar ra y t hat le ads to a shi f44 # b ec aus e u tmp [ 0 ,0] i s the s ame a s u [0 , 1]45 # u se this c on ce pt to so lv e t his e qu at io n i n on line46 # u = 1/4 *( u_ {j -1 , i} + u_ {j +1 , i} + u_ {j , i -1} + u _ {j , i + 1})47 return c a l c_ e rr ( u , u _o l d )

    Yann - [email protected] (SCV) Scientific Python October 2012 44 / 59

    Scientific Python numpy

    Solve Laplaces Equation 4a

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    64/78

    Third task:4 def l a p la c e _d r i ve r ( u , s te pp er , m a xi t = 1 00 , e rr = 1 e 3 ) :5 R ep ea te dl y c a ll s te pp er ( u ) to s ol ve n ab la ^ 2 u = 0 u nt il6 rm s e rr or < er r or m ax it n um be r o f i te ra ti on s i s r ea ch ed .78 u - a nu mpy ar ray9 st epp er - a f un ct io n w ho se s ol e a rg um en t is u

    10 11 r ms _e rr = 012 # t ak e o n e s t ep w it h s t ep pe r , t o d ef in e i ni ti al r ms _e rr13 # loop un til r ms _e rr < err14 # check to see that number of itera tions is less than max15 # perform single iteration using stepper method16 # r et ur n r ms _e rr o r

    17 return rms_err

    Yann - [email protected] (SCV) Scientific Python October 2012 45 / 59

    Scientific Python numpy

    Solve Laplaces Equation 4b

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    65/78

    59 def t i m e _ m e t h o d ( s t e p p e r ) :

    60 T im e h ow l on g a p a rt ic ul ar s te pp er t ak es to s ol ve an i de al61 u = s e t_ b c ( n p . z er os ( ( 10 0 , 1 0 0 )) )62 s ta rt = t im e . ti me ( )63 e rr = l a pl a ce _ dr i ve r ( u , s te pp er )64 return t i m e . t i m e ( ) - s t a r t6566 if _ _n a me _ _ = = " _ _ m a in _ _ " :

    67 p u r e_ p y th o n _t i m e = t i m e_ m et h o d ( p u r e _ py t h on _ s te p )68 n u m py _ t im e = t i m e_ m et h o d ( n u m p y_ s t ep )69 print " P u re p yt ho n m et ho d t ak es { :. 3 f } s ec on ds " . f o rm at ( p u r e_ p70 print " N um p y m e th o d t ak e s { .3 f } s e co n ds " . f o r m at ( n u m py _ ti m e )

    Yann - [email protected] (SCV) Scientific Python October 2012 46 / 59

    Scientific Python numpy

    Solve Laplaces Results

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    66/78

    1 P ur e p yt ho n m et ho d t ak es 3 .6 24 s ec on ds

    2 N um py m et ho d t ak es 0 .0 16 s ec on ds

    Yann - [email protected] (SCV) Scientific Python October 2012 47 / 59

    Scientific Python numpy

    Plenty More

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    67/78

    www.scipy.org/Tentative_NumPy_Tutorial

    Universal Functions section

    PyTrieste Numpy Tutorial

    Yann - [email protected] (SCV) Scientific Python October 2012 48 / 59

    http://www.scipy.org/Tentative_NumPy_Tutorialhttps://github.com/thehackerwithin/PyTrieste/wiki/Python9-NumPyhttps://github.com/thehackerwithin/PyTrieste/wiki/Python9-NumPyhttp://www.scipy.org/Tentative_NumPy_Tutorialhttp://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    68/78

    Scientific Python scipy

    Constants

  • 8/13/2019 Python Tutorial Slides 3[1]

    69/78

    4 > >> f ro m s ci py i mp or t c on st an ts

    5 > > > c o ns t an t s . c # speed of light6 299792458.0

    7 >>> # p hy si ca l c on st an ts : val ue , un its , u nc er ta in ty

    8 >> > c o ns t an t s . p h y s i c al _ c on s t an t s [ " e l e c tr o n m as s " ]

    9 ( 9 .1 0 93 8 29 1 e - 31 , kg , 4 e - 3 8)

    10 >>> # look - up c on sta nts , on ly fi rs t 3 !11 > > > m a ss es = c o ns t an t s . f i nd ( " m a ss " ) [: 3]

    12 >>> for val in m as se s :

    13 ... print " {} is available ". format ( val )

    14 ...

    15 P la nc k mass is a va il ab le

    16 Pl an ck ma ss e ne rg y e qu iv al en t in GeV is a va il ab le

    17 a lp ha p ar ti cl e mass is a va il ab le

    Yann - [email protected] (SCV) Scientific Python October 2012 50 / 59

    Scientific Python scipy

    Zombie Apocalypse - ODEINT

    http://find/http://goback/
  • 8/13/2019 Python Tutorial Slides 3[1]

    70/78

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

    Apocalypse_ODEINT

    Yann - [email protected] (SCV) Scientific Python October 2012 51 / 59

    Scientific Python scipy

    Zombie Apocalypse - ODEINT

    http://www.scipy.org/Cookbook/Zombie_Apocalypse_ODEINThttp://www.scipy.org/Cookbook/Zombie_Apocalypse_ODEINThttp://www.scipy.org/Cookbook/Zombie_Apocalypse_ODEINThttp://www.scipy.org/Cookbook/Zombie_Apocalypse_ODEINThttp://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    71/78

    Yann - [email protected] (SCV) Scientific Python October 2012 52 / 59

    Scientific Python scipy

    Zombie Apocalypse - ODEINT

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    72/78

    Look at examples\zombie.py5 def c al c_ ra te ( P =0 , d = 0. 00 01 , B = 0. 00 95 , G = 0. 00 01 , A = 0.

    6 def f (y , t ):

    7 Si = y [0]

    8 Zi = y [1]

    9 Ri = y [2]

    10 # the model e qua tio ns ( 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 # i ni ti al z om bi e p op ul at i16 R0 = 0 # i ni ti al d ea th p op ul at io

    17 y0 = [ S0 , Z0 , R0 ] # i ni ti al c on di ti on v ec to

    18 t = np . linspace (0 , 5. , 1000) # time grid

    19 # solve the DEs

    20 soln = o deint ( f, y0 , t )Yann - [email protected] (SCV) Scientific Python October 2012 53 / 59

    Scientific Python ipython

    ipython (1) - plotting

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    73/78

    Amazing interactive python.

    Using the -pylab flag, you can get plotting for free1 % i py th on - p yl ab

    2 ...

    3 I n [ 1] : p lo t ( r a ng e ( 1 0 ))

    Yann - [email protected] (SCV) Scientific Python October 2012 54 / 59

    Scientific Python ipython

    ipython (2) - Magic Functions

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    74/78

    Amazing interactive python.

    It provids Magic functions:cd - like unix change directory

    ls - list directory

    timeit - time execution of statementand so on ...

    Yann - [email protected] (SCV) Scientific Python October 2012 55 / 59

    Scientific Python ipython

    ipython (3) - Logging

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    75/78

    Amazing interactive python.

    You can log an interactive session:1 In [ 1] : l og st ar t m yl og fi le . p y

    Everything you type will be recorded to mylogfile.py

    To re-run it in ipython, us the run command:1 In [1] : run - i m yl og fi le . py

    Yann - [email protected] (SCV) Scientific Python October 2012 56 / 59

    Scientific Python ipython

    ipython (4) - Misc.

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    76/78

    Amazing interactive python.

    You can use ? instead of help().In [1]: len?and Enter will print helpIn fact you get even more information than the

    standard help()Tab-completion

    Start typing a mtehod, and pop-up help is shownYou need a newer version than Katanas, andyou need to type ipython qtconsole

    Yann - [email protected] (SCV) Scientific Python October 2012 57 / 59

    Conclusion

    Resources

    http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    77/78

    SCV help site

    Numpy Tutorial

    Scipy tutorial

    Scientific Python Tutorial

    Another Scientific Python TutorialiPython Tutorial

    Yann - [email protected] (SCV) Scientific Python October 2012 58 / 59

    http://www.bu.edu/tech/research/training/scv-software-packages/python/http://www.scipy.org/Tentative_NumPy_Tutorial#head\discretionary%20{-}{}{}053463ac1c1df8d47f8723f470b62c4bd0d11f07http://docs.scipy.org/doc/scipy/reference/tutorial/index.htmlhttp://scipy-lectures.github.com/index.htmlhttps://github.com/thehackerwithin/PyTrieste/wikihttp://scipy.org/Getting_Startedhttp://scipy.org/Getting_Startedhttps://github.com/thehackerwithin/PyTrieste/wikihttp://scipy-lectures.github.com/index.htmlhttp://docs.scipy.org/doc/scipy/reference/tutorial/index.htmlhttp://www.scipy.org/Tentative_NumPy_Tutorial#head\discretionary%20{-}{}{}053463ac1c1df8d47f8723f470b62c4bd0d11f07http://www.bu.edu/tech/research/training/scv-software-packages/python/http://find/
  • 8/13/2019 Python Tutorial Slides 3[1]

    78/78


Recommended