Python Scripts

General Idea

You have seen the typical steps in an analysis: reading the data, manipulating arrays, fitting and plotting. In order that you do not have to always type in everything you can type all the commands into a simple text file using your favored editor, save it with the extension .py and then execute it with the command run or %run.

In general all that you can type into ipython at the prompt, can also be stored in a file. This file is called a script or, more precise, a python script. It is basically a program.

A simple script for a few things you did in this short introduction looks like:

# import  the toolbox and call it B
import as B

# read the data
mf = B.get_file('')

# get the data into arrays
t = mf['time']
dexp = mf['dist']
derr = mf['d_err']

# print the values in a for loop
for i, D in enumerate(dexp):
    # indentation is important
    print( 'time = ', t[i], 'distance = ', D, 'error = ', derr[i] )
# end of the loop = end of indentation
# plot the data
B.plot_exp(t, dexp, derr)

# fit a line
fit = B.linefit(t, dexp, derr)

# draw the fit result
B.plot_line(fit.xpl, fit.ypl)

# add the labels't (sec)')'Distance (m)')'Distance vs time exp.')

# save the plot'my_plot.pdf')

# print the covariance matrix:
print( "The Covariance Matrix is : ", fit.cov )

You would run it by doing

In [119]: run

If the plot does not show after a short while you need to enter

In [120]: run
In [121]:

You could for example place the entire analysis of an experiment in one python script. If you need to change something all you have to do in that case is change the corresponding part and run it again.

You can find a few examples in the file: examples.tar.gz.

Problems you might encounter

It is important to realize that when you run a script, what happens inside the script is it’s own python session. So if your script is as follows:

x = array( [1.,2.,3.,4] )
print( x )

save it as and then you do

In [122]: run

you will get

In [122]: run
NameError                                 Traceback (most recent call last)

/Users/boeglinw/Documents/teaching/Classes/phy-3106L/python/sphinx/pyplots/ in <module>()
----> 1
      3 x = array([1,2,3,4,5])
      4 print( x )

NameError: name 'array' is not defined
WARNING: Failure executing file: <>

This means that python does not know what an array is. This is part of numpy and therefore you must import it (see loading modules). So your script should look like:

import numpy as np            # import numpy and call is np
x = np.array( [1.,2.,3.,4] )  # use the array object of np
print( x )

Then the output will be

In [123]: run
[1 2 3 4 5]

If you want to be able to use the functions as in the interactive sessions you need to import things as follows:

from matplotlib.pylab import *

This is however not recommended. You should know from which software package a function comes in order to know exactly what it is doing and how to use it. I therefore recommend to do the following

import numpy as np                 # for math (all names start with np.)
import matplotlib.pyplot as pl     # for plotting (all plot
                                   # functions start with pl.

If you use trigonometric and other functions remember they often act on whole arrays, each element at a time, so you need to use the numpy functions e.g. np.sin, np.cos, np.arctan, np.log etc. Check the numpy documentation for all the details