UNIVERSITY OF CAPE TOWN

UCT Physics PHY321F - Computational Physics


Useful Python code fragments

Importing

Normally for numerically oriented programs you will need the math functions:

from math import *

Frequently, the array and other facilities provided by the Numeric extension are useful

from Numeric import *

includes the normal math functions as well.

Animation of the results can also be useful; the visual extensions can be used for this.

from visual import *

also imports Numeric.

Finally, visual can also be used for plotting graphs.

from visual.graph import *

imports visual, etc. as well.


Writing to a file

Is simpler in python V2.

outfile=open("myfile","w")   # open file in write mode
... print >> outfile, x, y, x # print to outfile x,y and z
... outfile.close() # close the file


Plotting a graph

Use the visual.graph module for plottiing simple graphs.

from visual.graph import *    # Fft on Windows ?

... points is an array of Python tuples of x,y values ...
data=array([(x1,y1),(x2,y2), ... ])

myplot=gcurve( pos=data, color=color.blue )  # colour is optional ...

It may be simpler to plot the curve point by point in some loop:

from visual.graph import *    # Fft on Windows ?

myplot=gcurve( color=color.blue )  # colour is optional ...

for ....
    ... calculate x and y
    myplot.plot( pos=(x,y) )


Power spectrum via FFT

Useful to get the frequency distribution in a time series.

from FFT import *    # Fft on Windows ?

... data is Numeric array ...
transform=fft(data)  # transform is complex
powerspectrum=abs(transform*conjugate(transform))/len(data)**2

It may be useful to `window' the data (see Numerical Recipes):

from FFT import fft    # from Fft on Windows ?
from MLab import hanning

... data is Numeric array ...
transform=fft(data*hanning(len(data)))  # transform is complex
powerspectrum=abs(transform*conjugate(transform))/len(data)**2

Note that if the time step is dt and the total time slice of the data is T=N dt, the step size in angular frequency is d omega = 2pi/T and the range of frequencies in the transform is from -(N/2)domega .. (N/2)domega.


RETURN TO: [ PHY321F Computational Physics][ Physics Home Page ][ UCT Home Page ]