#!/usr/bin/env python
# coding: utf-8
# # Introduction to scientific computing with Python
# ## Basics
#
# We'll start with some basics in the interpreter, covering strings and maths, then come back to this notebook.
#
#
# ## Lists
# Indexing, slicing, `append()`, `in`
# In[ ]:
layers = [0.23, ] # Add some more
# In[ ]:
# Play with lists
# e.g. indexing with layers[4]
# slicing with layers[2:4]
# In[ ]:
uppers = layers[:-1]
lowers = layers# how shall we slice it?
# In[ ]:
rcs = []
for pair in zip(uppers, lowers):
rc = # Compute the contrast
# Now what?
# In[ ]:
rcs
# ## Functions
# Definition, inputs, side-effects, returning, scope, docstrings
# In[ ]:
def add(a, b):
return a + b
# In[ ]:
# Exercise
def compute_rc(layers):
"""
Computes reflection coefficients given
a list of layer impedances.
"""
# Put code here
# In[ ]:
# This should give you what you got before
compute_rc(layers)
# Now we will put this function in a file and import into a new notebook.
#
# * Open a text editor and copy the function definition into it
# * Save the file as `.py` in your current working directory
# * Restart the kernel in this notebook (*Kernel* > *Restart*)
#
# Run this:
# In[ ]:
layers = [0.23, 0.34, 0.45, 0.25, 0.23, 0.35]
compute_rc(layers)
# Why didn't that work?
#
# Change the name here to the name of your file:
# In[ ]:
import something
something.compute_rc(layers)
# ## NumPy
# In[ ]:
import numpy as np # Just like importing file
# In[ ]:
biglog = np.random.random(1000)
get_ipython().run_line_magic('timeit', 'compute_rc(biglog)')
# We need to learn the basics of NumPy arrays.
# In[ ]:
layers + 1
# In[ ]:
layers = np.array(layers)
layers + 1
# Etc.
# In[ ]:
# Exercise
def compute_rc_vector(layers):
# rewrite using NumPy arrays
# In[ ]:
get_ipython().run_line_magic('timeit', 'compute_rc_vector(biglog)')
# Warning signs:
#
#
# * Writing loops on arrays
# * Writing complicated functions on arrays
# ## Plotting
# In[ ]:
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[ ]:
plt.plot(biglog)
# In[ ]:
fig = plt.figure(figsize=(15,2))
ax = fig.add_subplot(111)
ax.plot(biglog)
ax.set_title("big log")
plt.show()
# ## Web
# In[ ]:
url = "http://en.wikipedia.org/wiki/Jurassic"
# Use View Source in your browser to figure out where the age range is on the page, and what it looks like.
#
# Try to find the same string here:
# In[ ]:
import requests
r = requests.get(url)
r.text
# In[ ]:
import re
# Use regex to extract the age range
# Make a function to get the start and end data of any geologic period