Practice: Plane Waves, Slowness, and the Seismic Wave Equation
Colab note: This notebook is designed to run on Google Colab. The first code cell installs dependencies.
Learning Objectives¶
This notebook is designed to help you build intuition for:
plane waves and how they vary in space and time
the roles of frequency, wavenumber, and slowness
how wave properties control wave speed and propagation
the physical meaning of P and S wave motion
The goal is to help you work with these ideas and equations, not just read them.
Prerequisites: Calculus; basic familiarity with vectors and matrices
Reference: Shearer, Chapter 3, The Wave Equation
Notebook Outline:
Source
# Install dependencies (for Google Colab or missing packages)
import sys
# Check if running in Colab
try:
import google.colab
IN_COLAB = True
print("Running in Google Colab")
except:
IN_COLAB = False
print("Running in local environment")
# Install required packages if needed
required_packages = {
'numpy': 'numpy',
'matplotlib': 'matplotlib',
'scipy': 'scipy',
'obspy': 'obspy'
}
missing_packages = []
for package, pip_name in required_packages.items():
try:
__import__(package)
print(f"✓ {package} is already installed")
except ImportError:
missing_packages.append(pip_name)
print(f"✗ {package} not found")
if missing_packages:
print(f"\nInstalling missing packages: {', '.join(missing_packages)}")
import subprocess
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q"] + missing_packages)
print("✓ Installation complete!")
else:
print("\n✓ All required packages are installed!")Running in local environment
✓ numpy is already installed
✓ matplotlib is already installed
✓ scipy is already installed
✓ obspy is already installed
✓ All required packages are installed!
Source
import numpy as np
import matplotlib.pyplot as pltPart (a): Waves in Time and Space¶
In lecture, we wrote a harmonic wave as
This wave depends on both position and time.
A useful way to build intuition is to look at the same wave in two different ways:
Fix a position (x) and look at how the wave changes with time
Fix a time (t) and look at how the wave changes with space
This helps separate the roles of:
: controls oscillation in time
: controls oscillation in space
In this exercise, we will plot both views of the same wave with Hz and m.
# Compute the angular frequency, omega, and wavenumber, k, using the values above
omega = # Determine this from the information given and Table 3.1
k = # Determine this from the information given and Table 3.1
# Grids
x = np.linspace(0, 2, 1000)
t = np.linspace(0, 2, 1000)
# Two views of the same wave
x0 = 0.0
t0 = 0.0
# Plot wave as a function of time at a fixed point in space
u_time = np.sin(k * x0 - omega * t)
# Plot wave as a function of space at a fixed point in time
u_space = np.sin(k * x - omega * t0)
plt.figure(figsize=(12,8))
plt.subplot(2,1,1)
plt.plot(t, u_time)
plt.xlabel("Time t")
plt.ylabel("u(0,t)")
plt.title("Fixed position")
plt.grid(True)
plt.subplot(2,1,2)
plt.plot(x, u_space)
plt.xlabel("Position x")
plt.ylabel("u(x,0)")
plt.title("Fixed time")
plt.grid(True)
plt.tight_layout()
plt.show()
Questions¶
In the first plot, what quantity seems to control how rapidly the wave oscillates in time?
In the second plot, what quantity seems to control how rapidly the wave oscillates in space?
Which plot would change if we increased but kept fixed?
Which plot would change if we increased but kept fixed?
In your own words, what is the difference between frequency and wavenumber?
Part (b): Measure Wave Speed¶
Now we will estimate the wave speed by tracking the motion of a peak. Below is code that plots the wave at several different times. A peak will move across the figure as time increases. Your task is to modify the code to estimate the wave speed.
Tasks¶
Run the code and observe how the peak moves.
Choose one peak (for example, the first maximum).
Modify the code to:
record the position of that peak at two different times
compute the change in position
compute the change in time
Estimate the wave speed using:
# Parameters (try changing these)
k = 2 * np.pi
omega = 4 * np.pi
# Spatial grid
x = np.linspace(0, 4, 1000)
# Times to plot
times = [0.0, 0.25, 0.5]
plt.figure(figsize=(8,4))
for t in times:
u = np.sin(k * x - omega * t)
plt.plot(x, u, label=f"t = {t}")
plt.xlabel("Position x")
plt.ylabel("u(x,t)")
plt.title("Wave at different times")
plt.legend()
plt.grid(True)
plt.show()
Questions¶
What value of wave speed do you estimate from the plot?
How does your estimate compare to the theoretical value: ?
What happens to the speed if you change but keep fixed?
What happens to the speed if you change but keep fixed?
Part (c): Slowness = Travel Time¶
In lecture, we wrote a plane wave as So what does the quantity represent physically?
Recall that slowness is defined as so represents the time it takes the wave to travel a distance .
The wave
can be interpreted as:
the wave at position
is the same as the wave at the origin
but shifted in time by the travel time
In the code below, we will compare the wave at two different positions.
Tasks¶
Modify the code to verify that the wave at position is just a time-shifted version of the wave at .
# Parameters
c = 2.0 # wave speed
x1 = 0.0 # first position
x2 = 1.5 # second position
# Time array
t = np.linspace(0, 4, 1000)
# Compute wave at two positions
u1 = np.sin(2 * np.pi * (t - x1 / c))
u2 = np.sin(2 * np.pi * (t - x2 / c))
# Plot
plt.figure(figsize=(8,4))
plt.plot(t, u1, label=f"x = {x1}")
plt.plot(t, u2, label=f"x = {x2}")
plt.xlabel("Time")
plt.ylabel("u(x,t)")
plt.title("Wave at Two Positions")
plt.legend()
plt.grid(True)
plt.show()
Questions¶
How are the two waves related?
Estimate the time shift between them using the plot.
Compare your estimate to
Modify the value of ( x_2 ). How does the time shift change?
Modify the wave speed ( c ). What happens to the time shift?
Part (d): Plane Waves in Two Dimensions¶
So far, we have looked at waves in one dimension. Now we extend this to two dimensions. A 2D plane wave can be written as The values and control how the wave varies in space while controls how the wave varies in time.
Key Idea¶
The combination controls how the phase changes across the plane. Points where
have the same phase. These form straight lines called wavefronts.
In the code below, we will plot the wave in the - plane at a fixed time.
Your goal is to explore how changing and affects the orientation of the wavefronts and how tightly spaced they are.
# Parameters (try changing these)
kx = 2 * np.pi
ky = 1 * np.pi
omega = 2 * np.pi
# Grid
x = np.linspace(0, 4, 200)
y = np.linspace(0, 4, 200)
X, Y = np.meshgrid(x, y)
# Time
t = 0.0
# Wave
U = np.sin(kx * X + ky * Y - omega * t)
# Plot
plt.figure(figsize=(6,5))
plt.contourf(X, Y, U, levels=50)
plt.colorbar(label="u(x,y)")
plt.xlabel("x")
plt.ylabel("y")
plt.title("2D Plane Wave at Fixed Time")
plt.show()
Questions¶
Describe the pattern you see. What do the bands in the plot represent?
Change while keeping fixed. What happens to the pattern?
Change while keeping fixed. What happens?
Set . What direction is the wave varying in now?
Set . What direction is the wave varying in now?
Try different values of and . How do they control the orientation of the wavefronts?
Part (e): Polarization of a Real Earthquake¶
In this exercise, we will download 3-component waveform data from a real California earthquake, rotate the horizontal components into radial and transverse, and compare the resulting waveforms.
Our goal is to see how wave polarization appears in real data:
P waves are expected to be strongest on the radial and vertical components
S waves are often stronger on the transverse component, though real Earth structure can distribute energy across multiple components
We will use the 2014 South Napa earthquake.
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import matplotlib.pyplot as plt
from obspy import UTCDateTime
from obspy.clients.fdsn import Client
from obspy.geodetics import gps2dist_azimuth, locations2degrees1. Find the South Napa earthquake¶
We query an event catalog for the 2014 South Napa earthquake.
client = Client("NCEDC")
# Approximate South Napa earthquake search window
t0 = UTCDateTime("2014-08-24T10:00:00")
t1 = UTCDateTime("2014-08-24T11:00:00")
catalog = client.get_events(
starttime=t0,
endtime=t1,
minmagnitude=5.5,
latitude=38.2,
longitude=-122.3,
maxradius=1.0
)
event = catalog[0]
origin = event.preferred_origin() or event.origins[0]
magnitude = event.preferred_magnitude() or event.magnitudes[0]
print("Event time:", origin.time)
print("Latitude:", origin.latitude)
print("Longitude:", origin.longitude)
print("Depth (km):", origin.depth / 1000)
print("Magnitude:", magnitude.mag)Event time: 2014-08-24T10:20:44.070000Z
Latitude: 38.2151667
Longitude: -122.3123333
Depth (km): 11.12
Magnitude: 6.02
2. Search for a nearby 3-component station¶
We now look for a nearby station with a full vertical, north, and east set of components.
search_start = origin.time
search_end = origin.time + 3600 # 1 hour window
inventory = client.get_stations(
latitude=origin.latitude,
longitude=origin.longitude,
minradius=0.3, # avoid very near stations if possible
maxradius=10.0, # regional distances
channel="BH?,HH?",
level="channel",
starttime=search_start,
endtime=search_end
)
# Print a few candidate stations
candidates = []
for net in inventory:
for sta in net:
channels = sorted({ch.code for ch in sta.channels})
dist_deg = locations2degrees(origin.latitude, origin.longitude,
sta.latitude, sta.longitude)
candidates.append((net.code, sta.code, dist_deg, channels))
candidates = sorted(candidates, key=lambda x: x[2])
for row in candidates[:15]:
print(row)('BK', 'BRIB', np.float64(0.3221382348397748), ['BHE', 'BHN', 'BHZ', 'HHE', 'HHN', 'HHZ'])
('BK', 'VAK', np.float64(0.3413177739158169), ['BHE', 'BHN', 'BHZ', 'HHE', 'HHN', 'HHZ'])
('BK', 'BRK', np.float64(0.34403148861739674), ['BHE', 'BHN', 'BHZ', 'HHE', 'HHN', 'HHZ'])
('BK', 'BKS', np.float64(0.34429307488492866), ['BHE', 'BHN', 'BHZ', 'HHE', 'HHN', 'HHZ'])
('BK', 'BL67', np.float64(0.34457767708241727), ['BHE', 'BHN', 'BHZ', 'HHE', 'HHN', 'HHZ'])
('NP', 'DIX', np.float64(0.4027961270034579), ['HHE', 'HHN', 'HHZ'])
('BK', 'BDM', np.float64(0.43805786008339026), ['BHE', 'BHN', 'BHZ', 'HHE', 'HHN', 'HHZ'])
('BK', 'MCCM', np.float64(0.4518838157511917), ['BHE', 'BHN', 'BHZ', 'HHE', 'HHN', 'HHZ'])
('NP', 'SIA', np.float64(0.48187930893570113), ['HHE', 'HHN', 'HHZ'])
('NP', 'EMR', np.float64(0.6579082985403774), ['HHE', 'HHN', 'HHZ'])
('BK', 'MNRC', np.float64(0.6713670807292971), ['BHE', 'BHN', 'BHZ', 'HHE', 'HHN', 'HHZ'])
('NC', 'GDXB', np.float64(0.7030144722703362), ['HHE', 'HHN', 'HHZ'])
('BK', 'WENL', np.float64(0.7373316463494597), ['BHE', 'BHN', 'BHZ', 'HHE', 'HHN', 'HHZ'])
('BK', 'FARB', np.float64(0.7500492322793465), ['BHE', 'BHN', 'BHZ', 'HHE', 'HHN', 'HHZ'])
('NP', 'ELK', np.float64(0.7623736321135588), ['HHE', 'HHN', 'HHZ'])
3. Download waveforms¶
The helper function below tries candidate stations until it finds one with usable 3-component data.
def download_three_component_waveforms(client, origin, t_before=20, t_after=120):
"""
Download 3-component waveform data from a short list of known California stations.
Tries BH? first, then HH?.
Accepts either Z/N/E or Z/1/2 component naming.
Returns
-------
st : obspy Stream
network : str
station : str
"""
start = origin.time - t_before
end = origin.time + t_after
# Shortlist of California broadband stations to try
candidates = [
("BK", "FARB"),
("BK", "MNRC"),
("BK", "ORV"),
("NC", "MCV"),
("NC", "JCC"),
("CI", "PASC"),
]
for net, sta in candidates:
for chan in ["BH?", "HH?"]:
try:
st = client.get_waveforms(
network=net,
station=sta,
location="*",
channel=chan,
starttime=start,
endtime=end,
attach_response=True
)
st.merge(fill_value="interpolate")
# Check component naming
comps = sorted({tr.stats.channel[-1] for tr in st})
has_z = "Z" in comps
has_ne = ("N" in comps and "E" in comps)
has_12 = ("1" in comps and "2" in comps)
if has_z and (has_ne or has_12):
print(f"Using station {net}.{sta}")
print("Channels found:", sorted({tr.stats.channel for tr in st}))
return st, net, sta
except Exception as e:
print(f"Skipping {net}.{sta} {chan}: {e}")
raise RuntimeError("Could not find a usable 3-component station.")st_raw, net_code, sta_code = download_three_component_waveforms(
client, origin
)
print(st_raw)Using station BK.FARB
Channels found: ['BHE', 'BHN', 'BHZ']
3 Trace(s) in Stream:
BK.FARB.00.BHE | 2014-08-24T10:20:24.094538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5600 samples
BK.FARB.00.BHN | 2014-08-24T10:20:24.094538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5600 samples
BK.FARB.00.BHZ | 2014-08-24T10:20:24.094538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5600 samples
4. Preprocess the data¶
We remove the instrument response, filter the data, and prepare the traces for rotation.
st = st_raw.copy()
# Detrend and taper
st.detrend("linear")
st.detrend("demean")
st.taper(max_percentage=0.05)
# Remove response to velocity (often a good choice for regional body waves)
st.remove_response(output="VEL", water_level=60)
# Bandpass filter
st.filter("bandpass", freqmin=0.5, freqmax=5.0, corners=4, zerophase=True)
# Make sure we have a common time window
st.trim(origin.time - 10, origin.time + 120)
print(st)3 Trace(s) in Stream:
BK.FARB.00.BHE | 2014-08-24T10:20:34.069538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5201 samples
BK.FARB.00.BHN | 2014-08-24T10:20:34.069538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5201 samples
BK.FARB.00.BHZ | 2014-08-24T10:20:34.069538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5201 samples
5. Make sure horizontal components are N and E¶
Some stations store horizontal channels as 1/2 instead of N/E. If needed, we rotate 1/2 to N/E using the metadata.
# If channels are Z12 instead of ZNE, rotate to ZNE
channel_suffixes = sorted([tr.stats.channel[-1] for tr in st])
if "1" in channel_suffixes and "2" in channel_suffixes:
st.rotate(method="->ZNE", inventory=inventory)
print("Rotated 1/2 channels to Z/N/E")
print(st)3 Trace(s) in Stream:
BK.FARB.00.BHE | 2014-08-24T10:20:34.069538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5201 samples
BK.FARB.00.BHN | 2014-08-24T10:20:34.069538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5201 samples
BK.FARB.00.BHZ | 2014-08-24T10:20:34.069538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5201 samples
6. Compute back azimuth and rotate N/E to R/T¶
The radial direction points from the station toward the source-receiver path, and the transverse direction is perpendicular to it.
# Get station coordinates from inventory
station_lat = None
station_lon = None
for net in inventory:
if net.code == net_code:
for sta in net:
if sta.code == sta_code:
station_lat = sta.latitude
station_lon = sta.longitude
break
dist_m, az, baz = gps2dist_azimuth(
origin.latitude, origin.longitude,
station_lat, station_lon
)
print(f"Station: {net_code}.{sta_code}")
print(f"Distance: {dist_m/1000:.1f} km")
print(f"Azimuth: {az:.1f}°")
print(f"Back azimuth: {baz:.1f}°")
st_rtz = st.copy()
st_rtz.rotate(method="NE->RT", back_azimuth=baz)
print(st_rtz)Station: BK.FARB
Distance: 83.4 km
Azimuth: 226.7°
Back azimuth: 46.3°
3 Trace(s) in Stream:
BK.FARB.00.BHT | 2014-08-24T10:20:34.069538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5201 samples
BK.FARB.00.BHR | 2014-08-24T10:20:34.069538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5201 samples
BK.FARB.00.BHZ | 2014-08-24T10:20:34.069538Z - 2014-08-24T10:22:44.069538Z | 40.0 Hz, 5201 samples
7. Plot the rotated Z, R, T waveforms¶
After rotation, compare the radial, transverse, and vertical components.
def get_trace_by_suffix(stream, suffix):
for tr in stream:
if tr.stats.channel.endswith(suffix):
return tr
return None
trZ_rtz = get_trace_by_suffix(st_rtz, "Z")
trR = get_trace_by_suffix(st_rtz, "R")
trT = get_trace_by_suffix(st_rtz, "T")
t = trZ_rtz.times(reftime=origin.time)
fig, axes = plt.subplots(3, 1, figsize=(10, 7), sharex=True)
axes[0].plot(t, trZ_rtz.data, "b")
axes[0].set_ylabel("Z")
axes[1].plot(t, trR.data, "b")
axes[1].set_ylabel("R")
axes[2].plot(t, trT.data, "b")
axes[2].set_ylabel("T")
axes[2].set_xlabel("Time after origin (s)")
# Add grid for easier zoom interpretation
for ax in axes:
ax.grid(True)
8. Compare component amplitudes¶
A simple way to compare polarization is to look at normalized traces.
def normalize(data):
m = np.max(np.abs(data))
return data / m if m > 0 else data
fig, axes = plt.subplots(3, 1, figsize=(10, 7), sharex=True)
axes[0].plot(t, normalize(trZ_rtz.data), label="Z")
axes[0].set_ylabel("Z")
axes[0].legend()
axes[1].plot(t, normalize(trR.data), label="R")
axes[1].set_ylabel("R")
axes[1].legend()
axes[2].plot(t, normalize(trT.data), label="T")
axes[2].set_ylabel("T")
axes[2].set_xlabel("Time after origin (s)")
axes[2].legend()
fig.suptitle("Normalized Z, R, T Components")
plt.tight_layout()
plt.show()
# Add grid for easier zoom interpretation
for ax in axes:
ax.grid(True)
Questions¶
Which components contain the strongest early-arriving energy? Does that look more like a P wave or an S wave?
Is the transverse component relatively quiet near the first arrival?
At later times, does the transverse component become stronger? What type of motion does that suggest?
Are the polarizations perfectly clean? If not, what might cause energy to appear on multiple components?
Key Takeaway¶
Rotating 3-component data into radial, transverse, and vertical makes wave polarization much easier to interpret.
P-wave energy is often strongest on radial and vertical
S-wave energy is often more prominent on the transverse component, though real data are not always perfectly clean
Summary¶
Plane waves describe how seismic energy propagates through space and time.
Frequency controls how fast a wave oscillates in time, while wavenumber controls how quickly it varies in space.
Slowness provides a convenient way to think about travel time and wave propagation.
P waves involve motion in the direction of propagation, while S waves involve motion perpendicular to it.
Together, these concepts provide a foundation for understanding how seismic waves move through the Earth and how we interpret seismic data.