IRIS-EarthScope Short Course

Bloomington/IN, August 2015

Python/ObsPy Introduction


image by Matthias Meschede

How to Use Python

There are different ways to use Python..

  • write a my_program.py Python file (e.g. using a text editor of choice, or an IDE), run the file with $ python my_program.py
    • easy to give the file to somebody else, basic human readable text file
  • use the interactive IPython shell
    • code can be executed line-by-line, results immediately visible
    • quick interactive playing around / prototyping (tab completion etc.)
  • in browser using the IPython/Jupyter notebook
    • code can be nicely mixed with images, formulas, text, exercise instructions.. good for teaching!
    • current state of variables can be a bit confusing sometimes

The IPython/Jupyter Notebook

The IPython/Jupyter notebook is a good way to combine text/formulas/images/diagrams with executable Python code cells, making it ideal for teaching Python tutorials.

Most Important:

  • on previously assigned variables (after the cell was executed), use tab completion for introspection!
In [1]:
x = "Hello World!"
In [ ]:
x.
  • use question mark for help on functions/methods
In [ ]:
x.lower?

Quick Toolbar Reference

  • Shift + Enter: Execute cell and jump to the next cell
  • Ctrl + Enter: Execute cell and don't jump to the next cell
  • If code execution is not responding anymore: Restart kernel (cache of previously assigned variables gets emptied!)

First things first: you will find these six lines in every notebook. Always execute them! They do three things:

  • Make plots appear in the browser (otherwise a window pops up)
  • Printing things works like this:
print("Hello")
  • Plots look quite a bit nicer (this is optional).

This essentially makes the notebooks work under Python 2 and Python 3.

In [1]:
%matplotlib inline
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = 12, 8

Here is collection of resources to introduce you the scientific Python ecosystem. They cover a number of different packages and topics; way more than we will manage today.

If you have any question regarding some specific Python functionality you can consult the official Python documentation.

Furthermore a large number of Python tutorials, introduction, and books are available online. Here are some examples for those interested in learning more.

Some people might be used to Matlab - this helps:

Additionally there is an abundance of resources introducing and teaching parts of the scientific Python ecosystem.

If you need to create a plot in Python/ObsPy, the quickest way to success is to start from some example that is similar to what you want to achieve. These websites are good starting points:


A) Python Crash Course

This course is fairly non-interactive and just serves to get you up to speed. Nonetheless feel free to play around.

1. Numbers

Python is dynamically typed and assigning something to a variable will give it that type.

In [2]:
# Three basic types of numbers
a = 1             # Integers
b = 2.0           # Floating Point Numbers
c = 3.0 + 4j      # Complex Numbers

# Arithmetics work more or less as expected
d = a + b         # (int + float = float)
e = c ** 2        # c to the second power

2. Boolean values

In [3]:
current_state = True
next_state = not current_state
print(next_state)

print(b > 100)
False
False

3. Strings

In [5]:
# You can use single or double quotes to create strings.
location = "Bloomington"

# Concatenate strings with plus.
where_am_i = "I am in " + location

# Print things with the print() function.
print(location)
print(where_am_i)

# In Python everything is an object..
# Strings have a lot of attached methods for common manipulations.
print(location.upper())

# Access single items with square bracket. Negative indices are from the back.
print(location[0], location[-1])
Bloomington
I am in Bloomington
BLOOMINGTON
B n

4. Lists

In [6]:
# Lists use square brackets and are simple ordered collections of items (of arbitrary type).
everything = [a, c, location, 1, 2, 3, "hello"]
print(everything)

# Access elements with the same slicing/indexing notation as strings.
# Note that Python indices are zero based!
print(everything[0])
print(everything[:3])
print(everything[2:-2])
print(everything[-3:])

# Append things with the append method.
# (Other helper methods are available for lists as well)
everything.append("you")
print(everything)
[1, (3+4j), 'Bloomington', 1, 2, 3, 'hello']
1
[1, (3+4j), 'Bloomington']
['Bloomington', 1, 2]
[2, 3, 'hello']
[1, (3+4j), 'Bloomington', 1, 2, 3, 'hello', 'you']

5. Dictionaries

In [7]:
# Dictionaries have named fields and no inherent order. As is
# the case with lists, they can contain items of any type.
information = {
    "name": "John",
    "surname": "Doe",
    "age": 48,
    "kids": ["Johnnie", "Janie"]
}

# Acccess items by using the key in square brackets.
print(information["kids"])

# Add new things by just assigning to a key.
print(information)
information["music"] = "jazz"
print(information)
['Johnnie', 'Janie']
{'age': 48, 'kids': ['Johnnie', 'Janie'], 'surname': 'Doe', 'name': 'John'}
{'music': 'jazz', 'age': 48, 'kids': ['Johnnie', 'Janie'], 'surname': 'Doe', 'name': 'John'}

6. Functions

In [8]:
# Functions are defined using the "def" keyword.
# The body of the function is the indented block following the
# call syntax definition and usually ends with a "return" statement.
def do_stuff(a, b):
    return a * b

# Functions calls are denoted by round brackets.
print(do_stuff(2, 3))
6
In [9]:
# Arguments to functions can have a default value..
def traveltime(distance, speed=80.0):
    return distance / speed

# If not specified otherwise, the default value is used..
print(traveltime(1000))
12.5

7. Imports

To use functions and objects not part of the default namespace, you have to import them. You will have to do this a lot so its worth to learn how to do it.

In [10]:
# Import the math module, and use it's contents with the dot accessor.
import math

a = math.cos(4 * math.pi)

# You can also selectively import specific things.
from math import pi

b = 2.0 * pi

# And even rename them if you don't like their name.
from math import cos as cosine
c = cosine(b)
print(c)
1.0

8. Control Flow

Loops and conditionals are needed for any non-trivial task. Please note that whitespace matters in Python. Everything that is indented at the same level is part of the same block!

In [11]:
temp = ["a", "b", "c"]

# The typical Python loop is a for-each loop, e.g.
for item in temp:
    print(item)
a
b
c
In [12]:
# Useful to know is the range() function.
for i in range(5):
    print(i)
0
1
2
3
4
In [13]:
# If/else works as expected.
age = 77

if age >= 0 and age < 10:
    print("Younger than ten.")
elif age >= 10:
    print("Older than ten.")
else:
    print("wait.. what??")
Older than ten.
In [14]:
# List comprehensions are a nice way to write compact loops.

a = list(range(10))
print(a)
b = [i ** 2 for i in a]
print(b)

# Equivalent for-loop to generate b.
b = []
for i in a:
    b.append(i ** 2)
print(b)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [15]:
# while-loops get executed over and over again,
# as long as the condition evaluates to "True"..

happy = False
candies = 0
print(candies)

while not happy:
    candies += 1
    if candies >= 100:
        happy = True

print(candies)
0
100

9. Exceptions

In automated processing scripts, sometimes unexpected things happen at runtime and Python stops code execution by raising an Exception (think of it as an "Error"). Sometimes we want to continue the program, nevertheless.

In [ ]:
for earthquake in my_earthquake_list:
    try:
        download_data(event)
    except:
        print("Warning: Failed to download data for event:", event)
        continue

But beware, just catching any type of Exception can mask errors in the code:

In [ ]:
for earthquake in my_earthquake_list:
    try:
        donwload_daat(event)
    except:
        print("Warning: Failed to download data for event:", event)
        continue

10. NumPy

Large parts of the scientific Python ecosystem use NumPy. The heart of NumPy is the "ndarray" type (n-dimensional array, in our course usually 1-D arrays). Operations on NumPy arrays are both economical in memory use and computationally fast (internally computations are done in C).

In [16]:
import numpy as np

# Create a large array with with 1 million samples, equally spaced from 0 to 100
x = np.linspace(0, 100, 1E6)

# Most operations work per-element.
y = x ** 2

# Uses C and Fortran under the hood for speed.
print(y.sum())
3333335000.0

11. Plotting

Plotting is (most often) done using matplotlib. It has an interface that essentially works like Matlab.

In [17]:
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 2000)
y = np.sin(x)

plt.plot(x, y, color="green", label="sine wave")
plt.legend()
plt.ylim(-1.1, 1.1)
plt.show()

Exercises

Functions, NumPy, and Matplotlib

a) Write a function that takes a NumPy array x and three float values a, b, and c as arguments and returns

$$ f(x) = a x^2 + b x + c $$

b) Use the function and plot its graph using matplotlib, for an arbitrary choice of parameters for x values between -3 and +3.

In [18]:
def f(x, a, b, c):
    return a * x ** 2 + b * x + c

x = np.linspace(-3, 3, 100)
y = f(x, -3, 10, 1)
plt.plot(x, y)
plt.show()

99 Bottles of Beer

(stolen from http://www.ling.gu.se/~lager/python_exercises.html)

"99 Bottles of Beer" is a traditional song in the United States and Canada. It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's simple lyrics are as follows:

99 bottles of beer on the wall, 99 bottles of beer.
Take one down, pass it around, 98 bottles of beer on the wall.

The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero.

Your task here is to write a Python program capable of generating all the verses of the song.

In [19]:
current = 99

line1 = "{} bottles of beer on the wall, {} bottles of beer."
line2 = "Take one down, pass it around, {} bottles of beer on the wall."

while current > 0:
    print(line1.format(current, current))
    print(line2.format(current - 1))
    current = current - 1
99 bottles of beer on the wall, 99 bottles of beer.
Take one down, pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98 bottles of beer.
Take one down, pass it around, 97 bottles of beer on the wall.
97 bottles of beer on the wall, 97 bottles of beer.
Take one down, pass it around, 96 bottles of beer on the wall.
96 bottles of beer on the wall, 96 bottles of beer.
Take one down, pass it around, 95 bottles of beer on the wall.
95 bottles of beer on the wall, 95 bottles of beer.
Take one down, pass it around, 94 bottles of beer on the wall.
94 bottles of beer on the wall, 94 bottles of beer.
Take one down, pass it around, 93 bottles of beer on the wall.
93 bottles of beer on the wall, 93 bottles of beer.
Take one down, pass it around, 92 bottles of beer on the wall.
92 bottles of beer on the wall, 92 bottles of beer.
Take one down, pass it around, 91 bottles of beer on the wall.
91 bottles of beer on the wall, 91 bottles of beer.
Take one down, pass it around, 90 bottles of beer on the wall.
90 bottles of beer on the wall, 90 bottles of beer.
Take one down, pass it around, 89 bottles of beer on the wall.
89 bottles of beer on the wall, 89 bottles of beer.
Take one down, pass it around, 88 bottles of beer on the wall.
88 bottles of beer on the wall, 88 bottles of beer.
Take one down, pass it around, 87 bottles of beer on the wall.
87 bottles of beer on the wall, 87 bottles of beer.
Take one down, pass it around, 86 bottles of beer on the wall.
86 bottles of beer on the wall, 86 bottles of beer.
Take one down, pass it around, 85 bottles of beer on the wall.
85 bottles of beer on the wall, 85 bottles of beer.
Take one down, pass it around, 84 bottles of beer on the wall.
84 bottles of beer on the wall, 84 bottles of beer.
Take one down, pass it around, 83 bottles of beer on the wall.
83 bottles of beer on the wall, 83 bottles of beer.
Take one down, pass it around, 82 bottles of beer on the wall.
82 bottles of beer on the wall, 82 bottles of beer.
Take one down, pass it around, 81 bottles of beer on the wall.
81 bottles of beer on the wall, 81 bottles of beer.
Take one down, pass it around, 80 bottles of beer on the wall.
80 bottles of beer on the wall, 80 bottles of beer.
Take one down, pass it around, 79 bottles of beer on the wall.
79 bottles of beer on the wall, 79 bottles of beer.
Take one down, pass it around, 78 bottles of beer on the wall.
78 bottles of beer on the wall, 78 bottles of beer.
Take one down, pass it around, 77 bottles of beer on the wall.
77 bottles of beer on the wall, 77 bottles of beer.
Take one down, pass it around, 76 bottles of beer on the wall.
76 bottles of beer on the wall, 76 bottles of beer.
Take one down, pass it around, 75 bottles of beer on the wall.
75 bottles of beer on the wall, 75 bottles of beer.
Take one down, pass it around, 74 bottles of beer on the wall.
74 bottles of beer on the wall, 74 bottles of beer.
Take one down, pass it around, 73 bottles of beer on the wall.
73 bottles of beer on the wall, 73 bottles of beer.
Take one down, pass it around, 72 bottles of beer on the wall.
72 bottles of beer on the wall, 72 bottles of beer.
Take one down, pass it around, 71 bottles of beer on the wall.
71 bottles of beer on the wall, 71 bottles of beer.
Take one down, pass it around, 70 bottles of beer on the wall.
70 bottles of beer on the wall, 70 bottles of beer.
Take one down, pass it around, 69 bottles of beer on the wall.
69 bottles of beer on the wall, 69 bottles of beer.
Take one down, pass it around, 68 bottles of beer on the wall.
68 bottles of beer on the wall, 68 bottles of beer.
Take one down, pass it around, 67 bottles of beer on the wall.
67 bottles of beer on the wall, 67 bottles of beer.
Take one down, pass it around, 66 bottles of beer on the wall.
66 bottles of beer on the wall, 66 bottles of beer.
Take one down, pass it around, 65 bottles of beer on the wall.
65 bottles of beer on the wall, 65 bottles of beer.
Take one down, pass it around, 64 bottles of beer on the wall.
64 bottles of beer on the wall, 64 bottles of beer.
Take one down, pass it around, 63 bottles of beer on the wall.
63 bottles of beer on the wall, 63 bottles of beer.
Take one down, pass it around, 62 bottles of beer on the wall.
62 bottles of beer on the wall, 62 bottles of beer.
Take one down, pass it around, 61 bottles of beer on the wall.
61 bottles of beer on the wall, 61 bottles of beer.
Take one down, pass it around, 60 bottles of beer on the wall.
60 bottles of beer on the wall, 60 bottles of beer.
Take one down, pass it around, 59 bottles of beer on the wall.
59 bottles of beer on the wall, 59 bottles of beer.
Take one down, pass it around, 58 bottles of beer on the wall.
58 bottles of beer on the wall, 58 bottles of beer.
Take one down, pass it around, 57 bottles of beer on the wall.
57 bottles of beer on the wall, 57 bottles of beer.
Take one down, pass it around, 56 bottles of beer on the wall.
56 bottles of beer on the wall, 56 bottles of beer.
Take one down, pass it around, 55 bottles of beer on the wall.
55 bottles of beer on the wall, 55 bottles of beer.
Take one down, pass it around, 54 bottles of beer on the wall.
54 bottles of beer on the wall, 54 bottles of beer.
Take one down, pass it around, 53 bottles of beer on the wall.
53 bottles of beer on the wall, 53 bottles of beer.
Take one down, pass it around, 52 bottles of beer on the wall.
52 bottles of beer on the wall, 52 bottles of beer.
Take one down, pass it around, 51 bottles of beer on the wall.
51 bottles of beer on the wall, 51 bottles of beer.
Take one down, pass it around, 50 bottles of beer on the wall.
50 bottles of beer on the wall, 50 bottles of beer.
Take one down, pass it around, 49 bottles of beer on the wall.
49 bottles of beer on the wall, 49 bottles of beer.
Take one down, pass it around, 48 bottles of beer on the wall.
48 bottles of beer on the wall, 48 bottles of beer.
Take one down, pass it around, 47 bottles of beer on the wall.
47 bottles of beer on the wall, 47 bottles of beer.
Take one down, pass it around, 46 bottles of beer on the wall.
46 bottles of beer on the wall, 46 bottles of beer.
Take one down, pass it around, 45 bottles of beer on the wall.
45 bottles of beer on the wall, 45 bottles of beer.
Take one down, pass it around, 44 bottles of beer on the wall.
44 bottles of beer on the wall, 44 bottles of beer.
Take one down, pass it around, 43 bottles of beer on the wall.
43 bottles of beer on the wall, 43 bottles of beer.
Take one down, pass it around, 42 bottles of beer on the wall.
42 bottles of beer on the wall, 42 bottles of beer.
Take one down, pass it around, 41 bottles of beer on the wall.
41 bottles of beer on the wall, 41 bottles of beer.
Take one down, pass it around, 40 bottles of beer on the wall.
40 bottles of beer on the wall, 40 bottles of beer.
Take one down, pass it around, 39 bottles of beer on the wall.
39 bottles of beer on the wall, 39 bottles of beer.
Take one down, pass it around, 38 bottles of beer on the wall.
38 bottles of beer on the wall, 38 bottles of beer.
Take one down, pass it around, 37 bottles of beer on the wall.
37 bottles of beer on the wall, 37 bottles of beer.
Take one down, pass it around, 36 bottles of beer on the wall.
36 bottles of beer on the wall, 36 bottles of beer.
Take one down, pass it around, 35 bottles of beer on the wall.
35 bottles of beer on the wall, 35 bottles of beer.
Take one down, pass it around, 34 bottles of beer on the wall.
34 bottles of beer on the wall, 34 bottles of beer.
Take one down, pass it around, 33 bottles of beer on the wall.
33 bottles of beer on the wall, 33 bottles of beer.
Take one down, pass it around, 32 bottles of beer on the wall.
32 bottles of beer on the wall, 32 bottles of beer.
Take one down, pass it around, 31 bottles of beer on the wall.
31 bottles of beer on the wall, 31 bottles of beer.
Take one down, pass it around, 30 bottles of beer on the wall.
30 bottles of beer on the wall, 30 bottles of beer.
Take one down, pass it around, 29 bottles of beer on the wall.
29 bottles of beer on the wall, 29 bottles of beer.
Take one down, pass it around, 28 bottles of beer on the wall.
28 bottles of beer on the wall, 28 bottles of beer.
Take one down, pass it around, 27 bottles of beer on the wall.
27 bottles of beer on the wall, 27 bottles of beer.
Take one down, pass it around, 26 bottles of beer on the wall.
26 bottles of beer on the wall, 26 bottles of beer.
Take one down, pass it around, 25 bottles of beer on the wall.
25 bottles of beer on the wall, 25 bottles of beer.
Take one down, pass it around, 24 bottles of beer on the wall.
24 bottles of beer on the wall, 24 bottles of beer.
Take one down, pass it around, 23 bottles of beer on the wall.
23 bottles of beer on the wall, 23 bottles of beer.
Take one down, pass it around, 22 bottles of beer on the wall.
22 bottles of beer on the wall, 22 bottles of beer.
Take one down, pass it around, 21 bottles of beer on the wall.
21 bottles of beer on the wall, 21 bottles of beer.
Take one down, pass it around, 20 bottles of beer on the wall.
20 bottles of beer on the wall, 20 bottles of beer.
Take one down, pass it around, 19 bottles of beer on the wall.
19 bottles of beer on the wall, 19 bottles of beer.
Take one down, pass it around, 18 bottles of beer on the wall.
18 bottles of beer on the wall, 18 bottles of beer.
Take one down, pass it around, 17 bottles of beer on the wall.
17 bottles of beer on the wall, 17 bottles of beer.
Take one down, pass it around, 16 bottles of beer on the wall.
16 bottles of beer on the wall, 16 bottles of beer.
Take one down, pass it around, 15 bottles of beer on the wall.
15 bottles of beer on the wall, 15 bottles of beer.
Take one down, pass it around, 14 bottles of beer on the wall.
14 bottles of beer on the wall, 14 bottles of beer.
Take one down, pass it around, 13 bottles of beer on the wall.
13 bottles of beer on the wall, 13 bottles of beer.
Take one down, pass it around, 12 bottles of beer on the wall.
12 bottles of beer on the wall, 12 bottles of beer.
Take one down, pass it around, 11 bottles of beer on the wall.
11 bottles of beer on the wall, 11 bottles of beer.
Take one down, pass it around, 10 bottles of beer on the wall.
10 bottles of beer on the wall, 10 bottles of beer.
Take one down, pass it around, 9 bottles of beer on the wall.
9 bottles of beer on the wall, 9 bottles of beer.
Take one down, pass it around, 8 bottles of beer on the wall.
8 bottles of beer on the wall, 8 bottles of beer.
Take one down, pass it around, 7 bottles of beer on the wall.
7 bottles of beer on the wall, 7 bottles of beer.
Take one down, pass it around, 6 bottles of beer on the wall.
6 bottles of beer on the wall, 6 bottles of beer.
Take one down, pass it around, 5 bottles of beer on the wall.
5 bottles of beer on the wall, 5 bottles of beer.
Take one down, pass it around, 4 bottles of beer on the wall.
4 bottles of beer on the wall, 4 bottles of beer.
Take one down, pass it around, 3 bottles of beer on the wall.
3 bottles of beer on the wall, 3 bottles of beer.
Take one down, pass it around, 2 bottles of beer on the wall.
2 bottles of beer on the wall, 2 bottles of beer.
Take one down, pass it around, 1 bottles of beer on the wall.
1 bottles of beer on the wall, 1 bottles of beer.
Take one down, pass it around, 0 bottles of beer on the wall.

Caesar Cipher

(stolen from http://www.ling.gu.se/~lager/python_exercises.html)

In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it to communicate with his generals. ROT-13 ("rotate by 13 places") is a widely used example of a Caesar cipher where the shift is 13. In Python, the key for ROT-13 may be represented by means of the following dictionary:

key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 
       'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 
       'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
       'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 
       'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 
       'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 
       'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}

Your task in this exercise is to implement an decoder of ROT-13. Once you're done, you will be able to read the following secret message:

Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!

BONUS: Write an encoder!

In [20]:
key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 
       'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 
       'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
       'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 
       'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 
       'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 
       'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}

message = "Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!"

def decode(some_string):
    out = ""
    for char in some_string:
        replacement = key.get(char, char)
        out = out + replacement
    return out

print(decode(message))
Caesar cipher? I much prefer Caesar salad!