Notes and Examples for Python

For Linux the packages numpy, scipy, Gnuplot, and matplotlib should be in usr/lib/Python2.x/site-packages.1-d Arrays,Matrices,Numerical Integration,Numerical Solution of ODEs,Curve Fitting ,Reading and
Writing Array files,Finding zeros of functions,Graphing with Gnuplot,Fast Fourier Transform,
Waveforms: Square, Sawtooth,Time Delay,Noise,Create Postscript Graph,Simple Plots with
matplotlib,Plot Functions and Data,Interactive Plots with matplotlib,Plotting with log or linear axes,
SubplotsInstructions for installing a python-based system for scientific/mathematic use,hereGood references:http://www.scipy.org/Cookbook , for example, to learn plotting:http://www.scipy.org/Cookbook/Matplotlib, for gnuplot, see demo.py and test.py in the gnuplot-pydirectoryTo learn about packages, subpackages, and routines, run python from a terminal, then follow theseexample commands to learn about the scipy package:import scipy {loads package}help(scipy)import scipy.integrate {loads subpackage}help(scipy.integrate)help(scipy.integrate.quad)import scipy.optimize {loads subpackage}help(scipy.optimize)

forLinux 1st line of program is:#! /usr/bin/env python {and change permissions to include execute}May be useful to run as:

from scipy import *from numpy import * # This not necessary since scipy loads numpyfrom numpy.random import * # If need random number generatorimport Gnuplot # If use gnuplot for graphsfrom matplotlib import * # If use matplotlib for graphsfrom pylab import *

Note, if using Gnuplot.py, then gnuplot must also be installed.http://www.gnuplot.info

To enter values interactively

use raw_input(text). (Doesn't work on emacs!! Use Eric)

x = float(raw_input('Enter x value: ')) #converts text input into real.

1-d Arrays

x = arange(0,10) # To make integer array vector of x values.x = linspace(0,10,101) # To make more general array.y = x**2x=zeros(100,float) # creates x array filled with 0

Example: Matrices

from scipy import *from scipy.linalg import *from numpy.random import randn#Example of using 2-dim arrays as matrices#Nr=6;Nc=4 # Number of rows and columnsNr=4;Nc=Nr # Square matrix A=zeros([Nr,Nc]) # Makes a Nr by Nc matrix of zeros#A=ones([Nr,Nc])print A for i in arange(0,Nr):for j in arange(0,Nc):A[i,j]=i+jprint A print ' Now make array of random numbers and do some linear algebra functions' A = randn(Nr,Nc)B = trace(A) #Really only for square matrixC = det(A) #determinantD = inv(A) #inverseprint A print 'Trace = ',B,' determinant = ', Cprint Dprint 'Now should get identity matrix from A x Inv(A)'print dot(A,D) #This does matrix multiplication as opposed to element

Example: To include Time Delay

import timetime.sleep(2.0) #Causes 2.0 second delay.

Example: Numerical integration

from scipy import *from scipy.integrate import quad"""Example of integration of a function using quadDo the exponential function."""result = quad(lambda x: exp(-x),0,5) #Uses anonymous function, lambdadisp(['Numerical result: ',result])analytic = 1-exp(-5)disp(['Analytic result: ',analytic])

Example: Numerical solution of ODEs

from scipy import *from scipy.integrate import odeintfrom pylab import *"""Example of solving system of differential equations using odeint.

Do the damped oscillator, b is damping coefficient"""def damped_osc(u,t,b): #defines the system of odesx=u[0]; v=u[1]return(v,-x-b*v) #the derivatives of ut = linspace(0,30,400)u0 = [1,0]b = 0.3u=odeint(damped_osc,u0,t,args=(b,)) #b is in tuple, needs commafigure(1)plot(t,u) #plots both columns of uxlabel('Time'); title('Damped Oscillator')figure(2)plot(u[:,0],u[:,1])title('Phase-space'); xlabel('Position'); ylabel('Velocity')show()

OR try

from scipy import *from scipy.integrate import odefrom pylab import *"""Example using ode integrator, Lorenz equations"""def foo(t,y,p): #system of 1st order odesigma=p[0]; beta=p[1]; rho=p[2]dy = zeros([3])dy[0] = sigma*(y[1]-y[0])dy[1] = y[0]*(rho - y[2])-y[1]dy[2] = y[0]*y[1]-beta*y[2]return dyt0 = 0; tEnd = 100.0; dt = 0.01y0 = [5,-5,10] #Initial conditionsY=[]; T=[] #create empty listsp = [10.0,8.0/3.0,28.0] #parameters for odes#Set up integrator 'vode'. Non-stiff use Adams, stiff use bdfr = ode(foo).set_integrator('vode',method='adams')#r = ode(foo).set_integrator('vode',method='bdf')#Maybe future version of scipy will have Runge-Kutta methods dopri5 and dop853#r = ode(foo).set_integrator('dopri5')r.set_f_params(p).set_initial_value(y0,t0) while r.successful() and r.t+dt < tEnd:r.integrate(r.t+dt)Y.append(r.y) #makes a list of 1d arraysT.append(r.t)Y = array(Y) #convert from list to 2d arraysubplot(2,1,1)plot(T,Y)subplot(2,1,2)plot(Y[:,0],Y[:,2])show()

Example: Curve-fitting