Python1

Python for Scientists

=Introduction=



With thanks to Simon Metson and Mike Wallace for much of the following material.

=Getting Started on BlueCrystal Phase-2=

After you have logged in, type the following at the command line:

module add languages/python-2.7.2.0 python

This should start up an interactive python session:

Python 2.7.2 (default, Aug 25 2011, 10:51:03) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>

where we can type commands at the >>> prompt.

=Python as a Calculator=

To get started, let's just try a few commands out. If you type:

you'll get:

Hello!

If you try:

you'll get:

14

So far so simple! Here is a copy of a session containing a few more commands where we've set the values of some variables and also defined and run our own function:

You can exit an interactive session at any time by typing Ctrl-D.

=Getting Help=

One of the good things about Python is that it has lots of useful online documentation. (There are good books on the language too.) For example, take a look at: http://docs.python.org/. You can also type help and the interpreter prompt:

>>> help

Welcome to Python 2.7! This is the online help utility.

If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://docs.python.org/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit".

...

help> keywords

Here is a list of the Python keywords. Enter any keyword to get more help.

and                elif                if                  print ...

help> if The ``if`` statement

The ``if`` statement is used for conditional execution:

if_stmt ::= "if" expression ":" suite ( "elif" expression ":" suite )* ["else" ":" suite]

It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true... ...

help> quit

You are now leaving help and returning to the Python interpreter. ... >>>

=Making a Script=

An interactive session can be fun and useful for trying things out. However--to save our fingers--we will typically want to execute a series of commands as a script, created using your favourite text editor. Here are the contents of an example script:

Ensure that your script is executable:

chmod u+x myscript.py

and now you can run it:

[ggdagw@bigblue4 ~]$ ./myscript.py Hello, from a python script!

=Python and Whitespace=

Love it of hate it, Python incorporates whitespace in it's syntax. (It's either that or demarcate blocks with some other syntax, such as ending a line with a semi-colon as it is in C. Pick your poison.)  Spacing is therefore key in creating a valid python script. For example:

will work, but:

will not:

File "./myscript.py", line 7 print "shorter.." ^ IndentationError: expected an indented block

It is therefore a great advantage, when writing to python script, to use a text editor which has a dedicated python mode--such as emacs--and will actively help you to keep your spacing correct. See, http://wiki.python.org/moin/PythonEditors, for an extensive list.

=Some Suggested Exercises=


 * Calculate the volume of a sphere. You can experiment with the following (where r needs to be set to some value):
 * Concatenate two strings
 * Write a recursive function to compute fibonacci numbers (Hint: F(n) = F(n-1) +F(n-2), F(0)=0 and F(1)=1)
 * Concatenate two strings
 * Write a recursive function to compute fibonacci numbers (Hint: F(n) = F(n-1) +F(n-2), F(0)=0 and F(1)=1)
 * Write a recursive function to compute fibonacci numbers (Hint: F(n) = F(n-1) +F(n-2), F(0)=0 and F(1)=1)

=Nuts and Bolts=

Types
Python has intrinsic types including, integers, floats, booleans and complex numbers. It is dynamically typed (meaning that you don't have to have a block of variable declarations at the top of your script), but it is not weakly typed, for example:

Strings
The eagle-eyed will have spotted in a previous examples that we could ask the length a character string--straight off the bat. No need to write a counting routine ourselves:

We also take slices of our character string. In my case

Since a string is an object (in the object oriented programming sense of the word, but more of that another time...) we can call a number of methods that operate on a string. A selected sample include:

Lists and Tuples
An example of a list is:

and we can inquire about the length of that using the same function as before:

We can also take slices of a list, as we did with a string:

and even reset a portion of the list that way:

Since a list is also an object, we have more handy methods, including:

Tuples are very similar to lists and support many of the same operations (indexing, slicing, concatenation etc.) but differ in that they are not mutable after creation:

List comprehension:

Dictionaries
A dictionary is an associative array or hash table, containing key-value pairs:

We can write much more user-friendly and intuitive code using dictionaries, rather than arbitrary indexes into a list.

Some example dictionary methods are:

Control Structures
Of course, we'll need conditionals and loops etc. to go beyond the simplest of scripts. Here is an if-then-else, python style:

and a classic for loop:

1 ... 9 >>>

We'll also see a while loop shoehorned into the next example.

For our control statements, we can use comparison operators such as, ==, !=, >, <, <=, >=, and logical operators, such as, and, or,not

File Input and Output
Here's some code for printing the contents of a text file:

We could open a file for writing with:

and use:

to write to that file.

=Object Oriented Programming in Python=

Here is an example of using a class in python:

Running the script gives us:

car tuned to: 0.0 kitchen tuned to: 91.5 car tuned to: 89.3 A simple radio car Traceback (most recent call last): File "./foo.py", line 27, in    print car.__frequency AttributeError: Radio instance has no attribute '__frequency'

=Using Packages=

Python packages are great because they provide us with a whole lot of extra functionality--above and beyond the core language--that we didn't have to write and debug ourselves.

Let's walk through a simple example using a package. At an interactive prompt type:

This will give us access to the randint(x,y) function, which returns a randomly chosen integer from the given range [x,y]:

OK, so far so good. One thing to note is that the above import statement has drawn the name randint into our current namespace. What if we had already defined a function named randint. That could cause problems. In order to protect ourselves from this kind of problem, there are several import variants.

By default, functions will be added to a namespace with the same name as the package. In order to call the functions we will, in this case, have to prefix them with there namespace:

Should we desire, we can apply a little more control and specify the namespace for the import ourselves:

Another--more 'devil-may-care'--approach is to do away with the separate namespace and pull everything from a given package into the current namespace:

(The random function returns a randomly selected floating point number in the range [0, 1)--that is, between 0 and 1, including 0.0 but always smaller than 1.0.)

Interrogating a Module
To find all the functions that are in a particular module, type dir.

If you have the pip package installed, you can easily see which other packages are installed using pip list on the linux command line.

A Namespace Collision
=Python for Shell Scripting=

= Python as a Glue Languge=


 * Calling R from python is possible using: http://rpy.sourceforge.net/index.html.
 * Calling Matlab from python: http://mlabwrap.sourceforge.net.
 * With SWIG you can make many bindings, including Python to C and C++: http://www.swig.org/.
 * Or if Fortran is more your cup-of-tea, you can use f2py: http://cens.ioc.ee/projects/f2py2e/.
 * There are many more examples.

=Command Line Parsing=

gethin@gethin-desktop:~$ ./cmdline.py usage: to use this script... gethin@gethin-desktop:~$ ./cmdline.py fred ginger arg 0 is: ./cmdline.py arg 1 is: fred arg 2 is: ginger

=Databases=

Simple Databases
Python provides access to some database packages through some standard packages. The bsddb module allows you to access the highly popular Berkeley DB database from your python code.

The interface to the database provided by this module is very similar to the way in which we access a dictionary. First, let's populate a database:

Now let's open the database again and query it's contents:

Relational Databases
Relational databases give us more oomph. SQLite is a useful relational database to consider as it is light, in that it requires hardly anything in terms of setup or management, yet still understands queries formulated in SQL. As such it is useful for creating relatively simple examples of SQL access to a database in python and is a stepping stone toward more powerful database packages.

Here is a script which will create a table called planets in the file pytest.db and populate with details of the planets in our solar system:

And here is a short example script showing a couple of ways to interrogate the database:

Where the results of running the script are:

All the records in the table, ordered by Name:

(3, 3, u'Earth', 1.0, 1.0, 1.0) (5, 5, u'Jupiter', 11.209, 317.80000000000001, 5.2000000000000002) (4, 4, u'Mars', 0.53200000000000003, 0.11, 1.52) (1, 1, u'Mercury', 0.38200000000000001, 0.059999999999999998, 0.23999999999999999) (8, 8, u'Neptune', 3.883, 17.199999999999999, 30.059999999999999) (6, 6, u'Saturn', 9.4489999999999998, 95.200000000000003, 9.5399999999999991) (7, 7, u'Uranus', 4.0069999999999997, 14.6, 19.219999999999999) (2, 2, u'Venus', 0.94899999999999995, 0.81999999999999995, 0.71999999999999997)

All the planets with a mass greater than or equal to that of Earth:

(3, u'Earth', 1.0, 1.0, 1.0), (5, u'Jupiter', 11.209, 317.80000000000001, 5.2000000000000002), (6, u'Saturn', 9.4489999999999998, 95.200000000000003, 9.5399999999999991), (7, u'Uranus', 4.0069999999999997, 14.6, 19.219999999999999), (8, u'Neptune', 3.883, 17.199999999999999, 30.059999999999999)

For more information on using SQLite with Python, see, e.g.:
 * http://zetcode.com/db/sqlitepythontutorial/
 * http://www.blog.pythonlibrary.org/2012/07/18/python-a-simple-step-by-step-sqlite-tutorial/

You can also connect to a MySQL database from python using, e.g. the python-mysqldb package. A snippet of python code for connecting to a database is:

=Numpy=

OK, let's move onto looking at python's numerical processing capabilities. We will start by looking at the numpy package:

Now that we have access to the functions from numpy, let's create an array. Note that a numpy array is an object of a different type to an intrinsic array in Python. A simple approach is to use the array function. For example we might enter:

Given an array, we may inquire about it's shape:

and we are told that it is a 2-dimensional array (i.e. an array of rank 2) and that the length of both dimensions is 3:

We can also apply operators to array objects. For example:

Note, however, that most operations on numpy arrays are done element-wise, which is different to a linear algebra operation that you may have been expecting. We will return to linear algebra operations when we look at the scipy package.

Should we so desire, we could re-shape the array. One way to do this is to to set it's shape attribute directly:

As with the list example, it can be useful to read or change the value of an element (or sub array) individually. Let's turn the array back to it's rank-2 form and try it out:

This is all pretty handy so far, but specifying the value of each element explicitly could become a chore. Happily some helper functions exist to give you a head start with some building blocks. For example, your can use:

The use of resize in the last example illustrates a useful replicating feature.

A list of all the functions and operations contained within numpy is: http://scipy.org/Numpy_Example_List.

=Pylab and Matplotlib=

The above examples are quite natty, but we have deliberately kept the array sizes small so that we can print the element values easily. In practice, you may find that your array sizes are much larger and printing the values to the screen is impractical. Fear not! Python has many packages which help you plot your data, so that you can explore it.

Using the pylab plotting interface we can create:

Where curves.png looks like:



You can open .png images from the linux command line (inc. bluecrystal) using, e.g.: display -resize 1000 curves.png

We can also use Matplotlib directly for more control:

and you should get a window similar to:



Perhaps the best way next step for matplotlib is to look at the gallery: http://matplotlib.org/gallery.html. Just click on a figure and you will get the code used to generate it--a really great resource!

Input and Output
The foregoing is all very interesting, but life would be rather dull if you had to re-enter all your data by hand whenever you set to work with Python and numpy. Therefore we need a means to save data to a file and load it again. Happily, we can do this rather easily using a couple of routines from the pylab package:

warning, the load function of numpy will be shadowed in the above example. One way to protect yourself against this is to make use of namespaces: Modify your import command to import pylab and then use pylab.load(..).

=Scipy=


 * http://www.scipy.org/
 * ..and good examples on http://scipy-lectures.github.com/intro/scipy.html
 * Many useful features:
 * Integration & Differentiation
 * Optimisation (curve fitting, etc)
 * Fourier transforms
 * Signal processing
 * Statistical algorithms
 * Much, much more...
 * If you know Python you can use SciPy

An example: Differentiation
Google for many more examples pertaining to your favourite numerical procedure!

=A Repository of Packages You Could Use=

Now, we've touched on a couple, but there are thousands of python packages available. Before you start writing your own function for X, check that someone hasn't contributed code for that already at http://pypi.python.org/pypi.

pip, the python package manager will look in pypi by default to install a package. You can use the --user option to install python packages in your own user space. See: for more information on pip.
 * https://pip.readthedocs.org/en/latest/

=Writing Faster Python=

As with other scripting languages, such as MATLAB and R, one of the simplest ways in which you can write faster python code is to eliminate loops by vectorising your code.

Consider the following two scripts. First for-loop.py:

and secondly, vectorised.py:

If we now run these two scripts through the Linux command line time utility, we see that the vectorised code runs a lot faster than the for loop:

gethin@gethin-desktop:~$ time ./for-loop.py

real	0m0.963s user	0m0.952s sys	0m0.012s gethin@gethin-desktop:~$ time ./vectorised.py

real	0m0.116s user	0m0.096s sys	0m0.020s

For some more tips on writing faster python code, and examples of how to use one of the python profiler modules, take a look at:
 * https://wiki.python.org/moin/PythonSpeed/PerformanceTips
 * http://technicaldiscovery.blogspot.co.uk/2011/06/speeding-up-python-numpy-cython-and.html
 * http://www.huyng.com/posts/python-performance-analysis/
 * http://www.appneta.com/2012/05/21/profiling-python-performance-lineprof-statprof-cprofile/

=Further Reading=


 * http://docs.python.org/tutorial/
 * http://wiki.python.org/moin/PythonBooks