Python Introduction for Seismologists
Here we want to give a small, incomplete introduction to the Python programming language, with links to useful packages and further resources. The key features are explained via the following Python script:
1#!/usr/bin/env python 2import glob 3from obspy.core import read 4 5for file in glob.glob('*.z'): 6 st = read(file) 7 tr = st 8 msg = "%s %s %f %f" % (tr.stats.station, str(tr.stats.starttime), 9 tr.data.mean(), tr.data.std()) 10 print(msg)
Description of each line of the example above:
- Line 1
Shebang, specifying the location of the Python interpreter for Unix-like operating systems.
- Lines 2-3
Import modules/libraries/packages in the current namespace. The
globmodule, which allows wildcard matching on filenames, is imported here. All functions inside this module can be accessed via
glob.function()afterwards, such as
glob.glob(). Furthermore, a single function
obspy.coremodule is imported, which is used to read various different seismogram file formats.
- Line 5
for-loop using the
glob()function of the module
globon all files ending with
The length of all loops in Python is determined by the indentation level. Do not mix spaces and tabs in your program code for indentation, this produces bugs that are not easy to identify.
- Line 6
read()function from the
obspy.coremodule to read in the seismogram to a
- Line 7
Assigns the first
Traceobject of the list-like
Streamobject to the variable
- Line 8-9
A Python counterpart for the well-known C function
%operator acting on a format string. Here we print the header attributes
starttimeas well as the return value of the methods
std()acting on the data sub-object of the
Trace(which are of type
- Line 10
Prints content of variable
msgto the screen.
As Python is an interpreter language, we recommend to use the IPython shell
for rapid development and trying things out. It supports tab completion,
history expansion and various other features. E.g.
glob.glob? to see the help of the
glob() function (the module must be imported beforehand).
Official Python tutorial.
Python library reference
Very instructive video lectures on various computer related topics. A good starting point for learning Python and Version Control with Git.
An enhanced interactive Python shell.
NumPy and SciPy are the matrix based computation modules of Python. The allow fast array manipulation (functions in C). NumPy and SciPy provide access to FFTW, LAPACK, ATLAS or BLAS. That is svd, eigenvalues… ObsPy uses the numpy.ndarrays for storing the data (e.g. tr.data).
matplotlib is the 2-D plotting package for Python. The gallery is the market place which allows you to go shopping for all kind of figures. The source code for each figure is linked. Note matplotlib has even its own latex renderer.
Package plotting 2D data on maps in Python. Similar to GMT.
Package which allows to directly read a GeoTiff which then can be plotted with the Cartopy package.
Multitaper spectrum bindings for Python