python1(1)
python1(1)
Scientific Computing
with Python
Adjusted from:
http://www.nanohub.org/resources/?id=99
Original Authors are: Eric Jones and Travis Oliphant
• Introduction to Python
• Numeric Computing
• SciPy and its libraries
What Is Python?
ONE LINER
ABSOLUTE VALUE
>>> a=1.5+0.5j
>>> abs(a)
1.5811388
Strings
CREATING STRINGS STRING LENGTH
# using double quotes >>> s = “12345”
>>> s = “hello world” >>> len(s)
>>> print s 5
hello world
# single quotes also work FORMAT STRINGS
>>> s = ‘hello world’ # the % operator allows you
>>> print s # to supply values to a
hello world # format string. The format
# string follows
STRING OPERATIONS # C conventions.
# concatenating two strings >>> s = “some numbers:”
>>> “hello “ + “world” >>> x = 1.34
‘hello world’ >>> y = 2
>>> s = “%s %f, %d” % (s,x,y)
# repeating a string >>> print s
>>> “hello “ * 3 some numbers: 1.34, 2
‘hello hello hello ’
The string module
>>> import string # replacing text in a string
>>> s = “hello world” >>> string.replace(s,’world’ \
... ,’Mars’)
# split space delimited words ‘hello Mars’
>>> wrd_lst = string.split(s)
>>> print wrd_lst # python2.2 and higher
[‘hello’, ‘world’] >>> s.replace(’world’ ,’Mars’)
‘hello Mars’
# python2.2 and higher
>>> s.split() # strip whitespace from string
[‘hello’, ‘world’] >>> s = “\t hello \n”
>>> string.strip(s)
# join words back together ‘hello’
>>> string.join(wrd_lst)
hello world # python2.2 and higher
>>> s.strip()
# python2.2 and higher ‘hello’
>>> ‘ ‘.join(wrd_lst)
hello world
Multi-line Strings
some_dict.has_key( x ) some_dict.items( )
>>> a[4:,4:] 0 1 2 3 4 5
array([[44, 45],
10 11 12 13 14 15
[54, 55]])
20 21 22 23 24 25
>>> a[:,2]
array([2,12,22,32,42,52]) 30 31 32 33 34 35
>>> a[2::2,::2] 50 51 52 53 54 55
array([[20, 22, 24],
[40, 42, 44]])
Slices Are References
Slices are references to memory in original array. Changing
values in a slice also changes the original array.
>>> a = array([0,1,2])
# changing b changed a!
>>> a
array([ 1, 2, 10])
Array Constructor
array(sequence, typecode=None, copy=1, savespace=0)
savespace - Forces Numeric to use the smallest possible numeric type for
the array. Also, it prevents upcasting to a different type during math
operations with scalars. (see coercion section for more details)
Array Constructor Examples
FLOATING POINT ARRAYS USE TYPECODE TO REDUCE
DEFAULT TO DOUBLE PRECISION
PRECISION
>>> a = array([0,1.,2,3]) >>> a = array([0,1.,2,3],'f')
>>> a.dtype() >>> a.dtype()
‘d‘ 'f‘
notice decimal
>>> len(a.flat)*a.itemsize()
16
ones(shape,typecode=None,savespace=0)
zeros(shape,typecode=None,savespace=0)
shape is a number or sequence specifying the dimensions of the array. If
typecode is not specified, it defaults to Int.
>>> ones((2,3),typecode=Float32)
array([[ 1., 1., 1.],
[ 1., 1., 1.]],'f')
Array Creation Functions
(cont.)
identity(n,typecode=‘l’)
Generates an n by n identity matrix with typecode = Int.
>>> identity(4)
array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
>>> identity(4,’f’)
array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]],'f')
Mathematic Binary Operators
a + b add(a,b) a * b multiply(a,b)
a - b subtract(a,b) a / b divide(a,b)
a % b remainder(a,b) a ** b power(a,b)
>>> a = array(((1,2,3,4),(2,3,4,5)))
>>> b = array(((1,2,5,4),(1,3,4,5)))
>>> a == b
array([[1, 1, 0, 1],
[0, 1, 1, 1]])
# functional equivalent
>>> equal(a,b)
array([[1, 1, 0, 1],
[0, 1, 1, 1]])
Bitwise Operators
bitwise_and (&) invert (~) right_shift(a,shifts)
bitwise_or (|) bitwise_xor left_shift (a,shifts)
BITWISE EXAMPLES
>>> a = array((1,2,4,8))
>>> b = array((16,32,64,128))
>>> bitwise_and(a,b)
array([ 17, 34, 68, 136])
# bit inversion
>>> a = array((1,2,3,4),UnsignedInt8)
>>> invert(a)
array([254, 253, 252, 251],'b')
Changed from
# surprising type conversion
UnsignedInt8
>>> left_shift(a,3)
to Int32
array([ 8, 16, 24, 32],'i')
Trig and Other Functions
TRIGONOMETRIC OTHERS
sin(x) sinh(x) exp(x) log(x)
cos(x) cosh(x) log10(x) sqrt(x)
arccos(x) arccosh(x) absolute(x) conjugate(x)
negative(x) ceil(x)
arctan(x) arctanh(x) floor(x) fabs(x)
arcsin(x) arcsinh(x) hypot(x,y) fmod(x,y)
arctan2(x,y) maximum(x,y) minimum(x,y)
hypot(x,y)
Element by element distance
calculation using x2 y2
SciPy
Overview
CURRENT PACKAGES
textfile.txt
Class for reading and writing binary files into Numeric arrays.
Methods
•file_name The complete path name to read read data from file and return
the file to open. Numeric array
•permission Open the file with given write write to file from Numeric array
permissions: ('r', 'w', 'a') fort_read read Fortran-formatted binary data
for reading, writing, or from the file.
appending. This is the same fort_write write Fortran-formatted binary data
as the mode argument in the to the file.
builtin open command. rewind rewind to beginning of file
•format The byte-ordering of the file: size get size of file
(['native', 'n'], ['ieee-le', 'l'], seek seek to some position in the file
['ieee-be', 'b']) for native, little- tell return current position in file
endian, or big-endian. close close the file
Few examples
>>> info(integrate)
.....<documentation of integrate module>.....
>>> integrate.quad(lambda t:
special.j1(t)/t,0,pi)
(1.062910971494,1.18e-14)
j1int.py module:
from scipy import *
def fun(x):
return integrate.quad(lambda t: special.j1(t)/t,0,x)
x=r_[0:30:0.01]
for tx in x:
print tx, fun(tx)[0]
Minimization
(x
uppose we want to minimize the function a ) 2 ( y b) 2 min
>>> from scipy import *
>>> import scipy
>>> info(scipy)
.... <documentation of all available modules>
>>> info(optimize)
>>> info(optimize.fmin_powell)
dtJ (t ) / t
0
1
1.0
0.8
0.6
0.4
x
dtJ (t ) / t 1
0.2
The function
1 0.0
0 5 10 15 20 25
0
has many solutions. Suppose we want to find all solution in the range [0:100]
Put it all together
from scipy import *
"""
Finds all solutions of the equation Integrate[j1(t)/t,{t,0,x}] == 1
in the range x=[0,100]
"""
def func(x,a):
" Computes Integrate[j1(t)/t,{t,0,x}] - a"
return integrate.quad(lambda t: special.j1(t)/t, 0, x)[0] - a
#environment setup
>>> import gui_thread
>>> gui_thread.start()
>>> from scipy import *
>>> import scipy.plt as plt
>>> x = r_[0:100:0.1]
>>> j0x = special.j0(x)
>>> plt.plot(x,j0x)
Special Functions
scipy.special
>>> z = r_[-5:1.5:100j]
>>> vals = special.airy(z)
>>> xplt.figure(0, frame=1,
color='blue')
>>> xplt.matplot(z,vals)
>>> xplt.legend(['Ai', 'Aip',
‘Bi‘,'Bip'],
color='blue')
>>> xplt.xlabel('z',
color='magenta')
>>> xplt.title('Airy
Functions and Derivatives‘)
Statistics
scipy.stats --- Continuous Distributions
over 80
continuous
distributions!
Methods
pdf
cdf
rvs
ppf
stats
Statistics
scipy.stats --- Discrete Distributions
10 standard
discrete
distributions
(plus any
arbitrary
finite RV)
Methods
pdf
cdf
rvs
ppf
stats
Statistics
scipy.stats --- Basic Statistical Calculations for samples
>>> x = r_[0:2*pi:100j]
>>> x2 = x[::5]
>>> y = sin(x)
>>> y2 = vecfunc(x2)
>>> xplt.plot(x,y,x2,y2,'rx')
Optimization
scipy.optimize --- unconstrained minimization and root finding
• Unconstrained Optimization
fmin (Nelder-Mead simplex), fmin_powell (Powell’s method), fmin_bfgs
(BFGS quasi-Newton method), fmin_ncg (Newton conjugate gradient),
leastsq (Levenberg-Marquardt), anneal (simulated annealing global
minimizer), brute (brute force global minimizer), brent (excellent 1-D
minimizer), golden, bracket
• Constrained Optimization
fmin_l_bfgs_b, fmin_tnc (truncated newton code), fmin_cobyla
(constrained optimization by linear approximation), fminbound (interval
constrained 1-d minimizer)
• Root finding
fsolve (using MINPACK), brentq, brenth, ridder, newton, bisect,
fixed_point (fixed point equation solver)
Optimization
EXAMPLE: MINIMIZE BESSEL FUNCTION
>>> x = r_[2:7.1:.1]
>>> j1x = j1(x)
>>> plt.plot(x,j1x,’-’)
>>> plt.hold(‘on’)
>>> j1_min = fminbound(j1,4,7)
>>> plt.plot(x,j1_min,’ro’)
Optimization
EXAMPLE: SOLVING NONLINEAR EQUATIONS
Rosenbrock function