Russell J. Hewett
Department of Mathematics, Massachusetts Institute of Technology
Extensive standard library: database tools; os, file, and url tools; web services, etc
Naturally object oriented scripting language
Cross-platform code: write once, run everywhere
Rapid prototyping
A joy to code in
(a quick note on Python 2.7 vs Python 3.x)
NumPy: Low-level data and array processing, BLAS
SciPy: High level scientific computing, sparse matrices
SymPy: Symbolic computation
matplotlib: 1D, 2D, and (some) 3D plotting and visualization
Wrapping external fortran, C, and C++ libraries: cython, swig, f2py
Parallel programming: mpi4py, numba
python
: the standard python console
ipython
: advanced python console (tab completion, online access to documentation)
ipython --pylab
: ipython with numerical packages pre-imported, MATLAB like environment
ipython notebook
: mathematica notebook style interface, used to write this talk
spyder: free GUI IDE with variable inspection, comes with Anaconda
pycharm: commercial GUI IDE with variable inspection
# Comments denoted with hash symbol
# Multi-line comments require
# repeated use of hash symbol
# Integers
my_int = 7
# floating point: careful with division
my_float = 6.0
# Boolean
my_bool = True # or False
# conventionally used for single words and characters
short_string = 'single-quote'
# conventionally used for longer strings
long_string = "double quotes are often used for longer strings"
really_long_string = """or triple quotes for long multiline strings,
such as documentation strings or other situations
where you want a string to run on and on for more
than one line"""
raw_string = r"ignores escaped characters like \n"
unicode_string = u"for non-ascii and foreign langauge characters"
# Tuples:
# IMMUTALBE collection of arbitrary items
# creatied with `comma`
t = (1, 3.0, 'str')
t
# Indexed with brackets
t[0]
# Elements can't be changed
t[0] = 4
# Lists:
# MUTABLE collection of arbitrary items
# created with brackets []
# indexed with brackets
mylist = [1, 3.0, 'str']
mylist
# Or created with list()
mylist2 = list()
mylist2.append(1)
mylist2.append(3.0)
mylist2.append('str')
mylist2
mylist[0] = 7
mylist
# Dictionaries:
# MUTABLE collection of arbitrary key-item pairs
# created with braces {}
# indexed with brackets
mydict = {'key1' : 'item 1', 2 : 'b', False : 'false string'}
mydict
# Indexed by key with brackets
mydict['key1'], mydict[False]
# Also created with dict()
mydict2 = dict(a=1, b=2)
# MUTABLE: Items added on the fly
mydict['key4'] = mydict2
mydict
# From python or ipython
# type variable name and press return
mylist
# Inside scripts
# use the `print` command
print 'Print strings and variables with the `print` "function"\n'
print my_int
print long_string
print mylist
print my_int, my_float, my_bool
import
statement¶# basic import
import numpy
print numpy.sin
# renamed import
import numpy as np
print np.sin
# partial import
from numpy import sin
print sin
Python uses white space to delineate code blocks
# The colon signifies the start of a new block
if condition:
print "Doing first thing"
elif other_condition:
print "Doing the second thing"
else:
print "Falling back to the last thing"
# If statements can be nested
if condition1:
if condition2:
print "Nested first thing"
else:
print "Nested fall back"
# Conditionals
print True and False
print True or False
print True == False
print True != False
print True is False
print True is not False
print 'a' in ['a', 'b', 'c']
# Python loop syntax is
for item in collection:
print "Doing task for ", item
# iterating over numbers
for i in xrange(len(mylist)):
print mylist[i]
print '\n'
# easier!
for item in mylist:
print item
print '\n'
# even dictionaries
for key in mydict:
print key, '-->', mydict[key]
# Created using the `def` keyword
# More than one function per file! (unlike MATLAB)
def my_function(arg1, arg2, kwarg1=0.0, kwarg2=None):
if kwarg2 is None:
print arg1 + arg2 * kwarg1
else:
print kwarg2
my_function(1, 2, kwarg1=4)
my_function(1,2,kwarg1=4, kwarg2="no math!")
# List comprehensions for fast list creation
slow_list = list()
for i in xrange(5):
slow_list.append(i**2)
fast_list = [i**2 for i in xrange(5)]
# Collecting elements in different lists: `zip`
numbers = [1,2,3]
letters = ['a', 'b', 'c']
pairs = zip(letters, numbers)
print pairs
# Unzipping: use `explode` operator *
print zip(*pairs)
import os # OS system calls
import os.path # file/directory functions
import sys # other system routines
import time # date-time classes and timing functions
import math # basic math library
# Contains log, exp, sin, cos, pi, etc
# my_script.py
def squares(n):
m = list()
for i in xrange(n):
m.append(i**2)
return m
if __name__ == '__main__':
print "Running squares"
squares_list = squares(7)
print max(squares_list)
# run %magic
%run my_script.py
squares_list
# paste magic
%paste
# timeit magic
%timeit squares(50)
np.zeros((3,2))
np.ones((2,4))
np.array(squares_list)
np.arange(4,16,2)
np.linspace(0,1,10)
np.linspace(0,1,10,endpoint=False)
A = np.arange(9)
print A
print A.shape
print A.ndim
B = A.reshape(3,3)
print B
print B.shape
print B.ndim
print B.flags
print id(A), id(B.base)
# Python is zero-indexed!
B[1,1] = 100
print B
print A
C = np.linspace(0,1,10,False)
print C
# Slices start:stop:step
C[3:6]
# Slices start:stop:step
C[0:10:2]
# Slices start:stop:step
B[0:2, 1:3]
# Scalar arithmetic
C[3:6] + 1 # also -, *, /
# Element-wise arithmetic
C[3:6] + np.ones(3) # also -, *, /
# * is element-wise product
D = np.random.rand(10)
C*D
# Scalar product/ matvec for ARRAYS
np.dot(C,D)
# Array-array products with * are broadcast operations
B*C[3:6]
# Matvec with arrays
np.dot(B,C[3:6])
# Matvec with np.matrix object
B_mat = np.matrix(B)
C_vec = C[3:6].reshape(3,1)
B_mat*C_vec
print B, '\n\n', B.T
E = ones((3,1)) + 1j*np.random.rand(3,1)
print E
print E.real
print E.imag
np.pi
np.sin(C)
np.exp(C)
import scipy as sp
import scipy.linalg #avoid numpy.linalg!!!
import scipy.linalg as spla
# Matrix and vector norms
print E
scipy.linalg.norm(E)
# Invert a matrix
scipy.linalg.inv(B) # pinv
# Solve a linear system
scipy.linalg.solve(B, C[3:6]) #lstsq
# Compute A = PLU
scipy.linalg.lu(B)
# To use, use
factors = scipy.linalg.lu_factor(B)
scipy.linalg.lu_solve(factors, C[3:6])
# Eigenvalues
scipy.linalg.eig(B)
# Singluar Value Decomposition
scipy.linalg.svd(B)
FFT: scipy.fftpack
(for historical reasons)
ODEs & Quadrature: scipy.integrate
Interpolation: scipy.interpolate
Signal Processing: scipy.signal
Sparse matrices: scipy.sparse
Sparse linear algebrea: scipy.sparse.linalg
And more ... see online documentation
import matplotlib.pyplot as plt # Basic plotting tools
ts = linspace(0,2*pi,1000)
plt.figure()
plt.plot(ts,sin(ts))
ts = linspace(0,2*pi,1000)
plt.figure()
plt.plot(ts,sin(ts))
plt.plot(ts,sin(4*ts))
ts = linspace(0,2*pi,1000)
plt.figure()
plt.plot(ts,sin(ts), label='lambda=2pi')
plt.plot(ts,sin(4*ts), label='lambda=0.5pi')
plt.legend()
ts = linspace(0,2*pi,1000)
plt.figure()
plt.plot(ts,sin(ts), label=r'$\lambda=2\pi$', linestyle='-.')
plt.plot(ts,sin(4*ts), label=r'$\lambda=\frac{\pi}{2}$')
plt.legend()
ts = linspace(0,2*pi,1000)
plt.figure()
plt.plot(ts,sin(ts), label=r'$\lambda=2\pi$', linestyle='-.')
plt.plot(ts,sin(4*ts), label=r'$\lambda=\frac{\pi}{2}$')
plt.legend()
plt.title('Some Sine Functions')
plt.xlabel(r'$t$')
plt.ylabel('Amplitude')
ts = linspace(0,2*pi,1000)
plt.figure()
plt.plot(ts,sin(ts), label=r'$\lambda=2\pi$', linestyle='-.', linewidth=2)
plt.plot(ts,sin(4*ts), label=r'$\lambda=\frac{\pi}{2}$', linewidth=2)
plt.legend(fontsize=18)
plt.title('Some Sine Functions', fontsize=22)
plt.xlabel(r'$t$', fontsize=18)
plt.ylabel('Amplitude', fontsize=18)
data = np.random.rand(10,10)
plt.figure()
plt.imshow(data)
plt.figure()
plt.imshow(data, interpolation='nearest')
plt.figure()
plt.imshow(data, interpolation='nearest')
plt.colorbar()
Check them out: matplotlib Gallery