Upload
albert-defusco
View
67
Download
5
Tags:
Embed Size (px)
Citation preview
Python for Scientific ComputingLecture 1: The Python Calculator
Albert DeFuscoCenter for Simulation and Modeling
September 23, 2013
Section 1
Computer Programming
a · b =
nÿ
i=1
aibi
Assembler1 g l o b a l _mult32 sum equ 163 s e c t i o n . t e x t4 _mult3 :5 push ebp
6 mov ebp , esp
7 push e s i
8 push e d i
9 sub esp , 410 mov e s i , [ ebp+12 ]11 mov edi , [ ebp+8 ]12 mov dword [ ebp≠sum ] , 013 mov ecx , 314 . f o r l o o p :15 mov eax , [ e d i ]16 imul dword [ e s i ]17 add edi , 418 add e s i , 419 add [ ebp≠sum ] , eax
20 l oop . f o r l o o p21 mov eax , [ ebp≠sum ]22 add esp , 423 pop e d i
24 pop e s i
25 pop ebp
26 r e t
C source1
1 i n t mult 3 ( i n t � dst , i n t � s r c )2 {3 i n t sum = 0 , i ;45 f o r ( i = 0 ; i < 3 ; i ++)6 sum += d s t [ i ] � s r c [ i ] ;78 r e t u r n sum ;9 }
1011 i n t main ( vo id )12 {13 i n t d [ 3 ] = { 1 , 2 , 3 } ;14 i n t s [ 3 ] = {8 , 9 , 10 } ;1516 p r i n t f ( " answer is %i\n" , mult 3 ( d , s ) ) ;17 r e t u r n 0 ;18 }
1The first compiler was written by Grace Hopper in 1952 for the A-0 language
a · b =
nÿ
i=1
aibi
Python1 import numpy2 d i s t = numpy . a r r a y ( [ 1 , 2 , 3 ] )3 s r c = numpy . a r r a y ( [ 8 , 9 , 10 ] )45 p r i n t d i s t . dot ( s r c )
Choices
Computer Time Programmer Time
History of Python
I December 1989I Implementation by Guido van Rossum as successor of ABC to
provide exception handlingI February 1991
I Python 0.9.0 had classes with inheritance, exception handling,functions, and the core datatypes
I January 1994I Version 1.0 has functional programming features
I October 2000I Python 2.0 brings garbage collectionsI Python 2.2 improves Python’s types to be purely object oriented
I December 2008I Python 3I
Reduce feature duplication by removing old ways of doing things
I Not backwards compatible with Python 2.x
What’s so great about Python?
I PortableI Your program will run if the interpreter works and the modules are
installed
What’s so great about Python?
I E�cientI Rich language features built inI Simple syntax for ease of readingI Focus shifts to “algorithm” and away from implementation
What’s so great about Python?
I FlexibleI ImperativeI Object-orientedI Functional
What’s so great about Python?
I ExtendibleI Plenty of easy-to-use modules
IIf you can imagine it, then someone has probably developed a module
for it
I Your program can adjust the way the interpreter works
Why use python for science?
I A highly programmable calculatorI Fast proto-typing new algorithms or program designI Use C or Fortran routines directlyI Many science and mathematics modules already exist
Development Environment
I Frank1. Launch Putty2. Connect to
login0a.frank.sam.pitt.edu
Read the documentation
> pydoc
> python>>> help()
Disclaimer
Python 2.7 ! = 3.0
http://wiki.python.org/moin/Python2orPython3
Python syntax
I Extremely simplified syntaxI Nearly devoid of special charactersI Intended to be nearly English
I Dynamic typesI It is the responsibility of the programmerI Still “strongly typed”
Python objects
I All data in Python is represented by objectsI Objects have
I an identityI a typeI a valueI a name (“variable”)2
I Variables are names assigned to objects
2http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables
Section 2
Hands-on Python
Numerical objects
I IntegersI a = 1
I FloatsI a = 1.0
I Complex numbersI a = 1.5 + 0.5jI a. real and a.imag return each component
I Type castsI myFloat = float(myInteger)I myInt = int(myFloat)
I OperatorsI Addition +I Subtraction ≠I Multiplication �I Exponentiation ��I Division /I Modulus %
Mathematical functions
I many functions exist with the math module
1 import math23 h e l p ( math )45 p r i n t math . cos ( 0 )6 p r i n t math . p i
Logicals
I Boolean typeI a = (3 > 4)
I ComparisonsI ==I !=,<>I >I <I <=I >=
Strings
I a = ’single quoted’
I a = "double quoted"
I Triple quotes preserve whitespace and newlines
1 a = """ t r i p l e2 quoted3 s t r i n g """
I “\” is the escape character
String operations
I TypecastingI doubleA = float(a)I intA = int(a)
I Comparisons return a BooleanI A == B
I concatenated = a + b
Formatted stringsI width placeholders
\%s string\%d integer\%f float with 6 decimals\%E scientific notation
\%\% the % sign
I modifiersI integers after % adjust with width to printI decimal points are specified after the width as “.x”I use a hyphen after % to left justifyI printing long strings or large numbers will skew columns
1 from math import pi , e23 p r i n t "pi is %d and e is %d" % ( pi , e )4 p r i n t "pi is %6.4f and e is %6.4f" % ( pi , e )5 p r i n t "pi is %f and e is %f" % ( pi , e )6 p r i n t "pi is %10.8 e and e is %10.8 e" % ( pi , e )7 p r i n t "pi is %15.8 e and e is %15.8 e" % ( pi , e )
Writing a script file
I save the file to hello.py
1 #/ u s r / b i n / env python23 #This i s my comment about the f o l l o w i n g s c r i p t4 p r i n t ’Hello , world !’
I run the file
> module load python/epd-7.2> python hello.pyHello, world!
Structured blocks
1 i f ( a>b ) :2 p r i n t ’a is bigger ’3 e l i f ( b>a ) :4 p r i n t ’big is bigger ’5 e l s e :6 p r i n t ’a must equal b’
I Why is it indented?
Structured blocks
1 i f ( a>b ) :2 p r i n t ’a is bigger ’3 e l i f ( b>a ) :4 p r i n t ’big is bigger ’5 e l s e :6 p r i n t ’a must equal b’
I Why is it indented?
Logical operations
Inot, and, or
I be careful with assignmentsI Just use if statements
Structured blocks
1 i=02 w h i l e ( i <10 ) :3 p r i n t i4 i=i+1
Structured blocks
1 f o r i i n range ( 4 ) :2 p r i n t i
Ifor is not limited to arithmetic
Simple loops
I range( start ,stop, step)I list of integers from start to stop-1 in step incrementsI End point is always omitted
1 f o r i i n range ( 4 ) :2 p r i n t i
Simple Functions
I Simplify your programI Easier debuggingI Improved elegance
1 import math2 def a r ea ( r a d i u s ) :3 r e t u r n math . p i � r a d i u s ��2
Simple Functions
I Functions must be defined before being usedI Arguments are passed by reference to the object
3
I Variables do not have values, objects doI Functions are first class citizens
12 def y ( x ) :3 x=x+14 r e t u r n x ��256 x=57 y ( x )8 p r i n t x
3http://me.veekun.com/blog/2012/05/23/python-faq-passing/
Mathematical Exercises
I Print a table of temperature conversion
C =59 (F ≠ 32)
I Compute Pi using the Wallis formula
fi = 2ŒŸ
i=1
4i2
4i2 ≠ 1
Python for Scientific ComputingLecture 2: Data Structures
Albert DeFuscoCenter for Simulation and Modeling
September 18, 2013
Download your own Python
https://www.enthought.com/products/epd/free/
Review fi
fi = 2
ŒŸ
i=1
4i
2
4i
2 ≠ 1
1 p i = 2 .
2 f o r i i n range ( 1 , n ) :
3 p i �= 4 . � i ��2 / ( 4 . � i ��2 ≠ 1 )
4 p r i n t p i
Review fi
fi = 2
ŒŸ
i=1
4i
2
4i
2 ≠ 1
1 p i = 2 .
2 f o r i i n range ( 1 , n ) :
3 p i �= 4 . � i ��2 / ( 4 . � i ��2 ≠ 1 )
4 p r i n t p i
Containers
I tuples, lists and stringsI Elements are accessed with container[ ]
IIndexed starting at 0
I Arguments for len(container)
I Each type has special features
Tuples
ITuple = (1,3 ., ’red’)
I Contain references to other objectsI The structure cannot be changedI A convenient way to pass multiple objects
I Packing and un-packing
Lists
IList = [’red’,’green’,’blue’]
I ResizableI List-of-Lists is a multi-dimensional listI Lists are not arraysI
range() is a list
Dictionaries
I Key - value pairsProtons = {’Oxygen’: 8, ’Hydrogen’: 1}
Protons[’Carbon’] = 6
I Any type can be a key or valueI Look-up tablesI Sorting and searching operations
Indexing Lists and tuples
I Slicing just like Fortran 90L[ start : stop: stride ]
start Æ i < stop; i+ = stride
I Negative indices start at the end of the listI -1 is the last element
Other operations
I Search for value with in
I Concatenate with + or *
I Count number of occurrences
Loops
I Iterate over any sequenceI string, list, keys in dictionary, lines in file
1 vowe l s = ’aeiouy ’2 f o r i i n ’orbital ’ :
3 i f i i n vowe l s :
4 p r i n t ( i )
Loops
I Keep a counter
1 s h e l l s = ( ’s’ , ’p’ , ’d’ , ’f’ )
2 f o r i ndex , t h i s S h e l l i n enumerate ( s h e l l s ) :
3 p r i n t i ndex , t h i s S h e l l
Loops
I List comprehension
1 even = [ i f o r i i n range ( 100 ) i f i%2 == 0 ]
2
3 l i s t X = [≠1 , 0 , 1 ]
4 l i s t Y = [ 2 , 4 ]
5 myTuple = [ ( x , y ) f o r x i n l i s t X f o r y i n l i s t Y ]
Mutability of objects
I Immutable objects get created and destroyed upon assignment andcollection
I StringsI Numbers (no ++ operator)I Tuples
I Mutable objects create references to contained objects uponassignment
I ListsI Dictionaries
Hands-on: Mutability
Tuples or Lists?
I List: homogeneous dataI Elements can be added or deletedI Elements can be in any orderI Mutable
I Tuples: heterogeneous data (structs)I Constant sizeI Order mattersI Immutable
Container examples
I ListI ParticlesI Lines in an input file
I TupleI Position data
I DictionaryI Associated listsI Look-up tablesI HistogramsI NetworksI Graphs
Functions
I Doc stringsI Default valuesI Optional argumentsI Returns
Functions
1 def d i v i d e ( x , y ) :
2 """ D i v i d e t a k e s two i n t e g e r s as i n p u t
3 r e t u r n s a tupe o f q u o t i e n t and rema inde r """
4 r e t u r n x/y , x%y
Mathematical Exercises
I Write a function to di�erentiate another function
f
Õ(x) ¥ f (x + h) ≠ f (x ≠ h)
2h
If (x) and h are arguments
I make h = 0.01 the default valueI Practice with the following functions
If (x) = x
2 at x = 1I
f (x) = cos(x) at x = 2fiI
f (x) = e
≠2x
2 at x = 0
Mathematical Exercises
I Write a function to di�erentiate another function
f
Õ(x) ¥ f (x + h) ≠ f (x ≠ h)
2h
If (x) and h are arguments
I make h = 0.01 the default valueI Practice with the following functions
If (x) = x
2 at x = 1I
f (x) = cos(x) at x = 2fiI
f (x) = e
≠2x
2 at x = 0
recursions
n! =nŸ
k=1k
1 def f a c t o r i a l ( n ) :
2 i f ( n==0 ) :
3 r e t u r n 1
4 r e t u r n n� f a c t o r i a l ( n≠1 )
Python for Scientific ComputingLecture 3: Object-oriented Programming
Albert DeFuscoCenter for Simulation and Modeling
September 20, 2013
Modules
I Import math.py such that math becomes the object nameimport math
print math.pi
print math.sin(math.pi)
I AlternativesI from math import sin
I import math as maths
I AvoidI from math import �
If you can imagine it, someone probably has a module that can do it.
http://docs.python.org/2/py-modindex.html
http://wiki.python.org/moin/UsefulModules
Modules
I Any python script can be importedI The contents are run when importedI Use __main__ to just import definitionsI Name space defaults to the script’s file name
Functions and variablesI Functions can be documented easily
1 def p i ( i ) :
2 """ Compute the i t h term o f the W a l l i s f o rmu la """
3 r e t u r n 4 . � i ��2 / ( 4 . � i ��2 ≠ 1 )
4
5 h e l p ( p i )
I Multiple returns are tuples1 def myFunction ( x , y ) :
2 r e t u r n x ��2 , y�4
3
4 a , b = myFunction ( y=2 , x=8 )
I Default and optional arguments1 def d e r i v a t i v e ( f , x , h=0 . 01 ) :
2 r e t u r n ( f ( x+h ) ≠ f ( x≠h ) ) / 2 . � h
3
4 def f ( x ) :
5 r e t u r n x ��2
6
7 d e r i v a t i v e ( f , x=0 )
Functionals and variables
I Functions are objectsI Global variables can be defined
INot always good practice
IMay reduce the usability of a module
Name Spaces and Scopes
I ModulesI
Functions
Function Scope
I Variables assigned in a function are private
1 def p i ( i ) :
2 """ Compute the i t h term o f the W a l l i s f o rmu la """
3 temp=4 . � i ��2
4 r e t u r n temp / ( temp ≠ 1 )
5
6 p r i n t p i ( 2 )
7 p r i n t temp
Function Scope
I Warning!I
Variables assigned before a function are still in scope
IIt helps to define functions first
1 myVar = 5
2 def p i ( i ) :
3 """ Compute the i t h term o f the W a l l i s f o rmu la """
4 p r i n t myVar
5 temp=4 . � i ��2
6 r e t u r n temp / ( temp ≠ 1 )
7
8 p r i n t temp
Module Scope
I Names assigned in a module are readable by functionsI Names assigned in functions do not a�ect the outer scope
Object Oriented Programming
I Focus on data, not on the procedureI Encapsulate procedures with dataI Create modular code that can be reused
Object Oriented Programming
I ClassI
The description of a type of object
I ObjectI
The realization of the description
IAn instance of a class
Object Oriented Programming
I Classes defineI
Attributes
IMethods
I Instances haveI
data stored in attributes
IMethods to operate on the data
I Objects can interact with each other by passing attributes tomethods
Our modules
/home/sam/training/python/lecture3
http://core.sam.pitt.edu/python-fall2013
Classes
1 c l a s s shape ( o b j e c t ) :
2 """ Shapes have a name and c o l o r """
3 def __init__ ( s e l f , name=’shape ’ , c o l o r=’white ’ ) :
4 s e l f . name=name
5 s e l f . c o l o r=c o l o r
6
7 c l a s s Molecu l e ( o b j e c t ) :
8 """ M o l e c u l e s have a name and c h e m i c a l f o rmu la """
9 def __init__ ( s e l f , name , fo rmu la )
10 s e l f . name = name
11 s e l f . f o rmu la = fo rmu la
Operator Overloading
Change or define the behavior of operations1 c l a s s Molecu l e ( o b j e c t ) :
2 . . .
3 def __add__( s e l f , o t h e r ) :
4 newName = s e l f . name + " + " + o t h e r . name
5 newFormula = "[" + s e l f . f o rmu la + "]" + "[" + o t h e r . f o rmu la + "]"
6 r e t u r n Molecu l e (newName , newFormula )
7
8
9 mol1=Molecu l e ( ’water ’ , ’h2o ’ )
10 mol2=Molecu l e ( ’ammonia ’ , ’nh3 ’ )
11
12 mol3 = mol1 + mol2
InheritanceI Child classes can be more specific than the parentI Subclasses can override the superclass†
1 import math
2 c l a s s shape ( o b j e c t ) :
3 def __init__ ( s e l f , name=’shape ’ , c o l o r=’white ’ ) :
4 s e l f . name=name
5 s e l f . c o l o r=c o l o r
6
7 c l a s s c i r c l e ( shape ) :
8 def __init__ ( s e l f , r a d i u s=1 . , name=’circle ’ , c o l o r=’white ’ ) :
9 super ( c i r c l e , s e l f ) . __init__ ( name , c o l o r )
10 s e l f . r a d i u s=r a d i u s
11 def a r ea ( ) :
12 r e t u r n math . p i � s e l f . r a d i u s ��2
13
14 c l a s s squa r e ( shape ) :
15 def __init__ ( s e l f , s i z e=1 . , name=’square ’ , c o l o r=’white ’ ) :
16 super ( square , s e l f ) . __init__ ( name , c o l o r )
17 s e l f . s i z e=s i z e
18 def a r ea ( ) :
19 r e t u r n s e l f . s i z e ��2
†Polymorphism in Python is achieved when classes implement the same methods, which reduces
the number of if statements