📍 In-situ sensor · 🪨 Solid Earth · 📈 Seismology
🖥️ Lecture slides: Manipulating real data streams (Session 08)
Archived records arrive with filter effects, gaps and timing errors. In this section you test three repairs on one real seismogram. The record is complete and correctly timed, so you damage a copy on purpose and grade every repair against the intact record with a number. Parts 2 to 4 each open with a short synthetic warm-up, a signal built in a few lines whose true times, gap or shift you set, so that you see each effect before you look for it in the real record.
The record. On 29 July 2021 at 06:15:49 UTC the Mww 8.2 Chignik earthquake ruptured the plate interface between the Pacific and North America plates south of the Alaska Peninsula (USGS event ak0219neiszm; Mww: moment magnitude from the W phase). Broadband station UW.RATT of the Pacific Northwest Seismic Network (PNSN), at Rattlesnake Lake in the Cascade foothills east of Seattle, Washington, recorded it 2,627 km away on the WGS84 ellipsoid (World Geodetic System 1984), 23.56° of arc; the slides give 2,620 km, the same angle on a sphere at 111.2 km per degree. You use its vertical channel HHZ, 100 samples per second, from 06:15 to 08:15 UTC, the same record as section 2.8. The values are raw digitizer counts: no instrument correction. The station metadata (StationXML) give the sensitivity, 5.04 × 10⁸ counts per m/s at 1 Hz, so 1,000 counts is about 2 µm/s of ground velocity.
Learning outcomes. After this section you can:
tell a step in a raw record from a seismic arrival, with a travel-time model;
choose a causal or a zero-phase filter for a task, and measure what each does to an onset of known time;
filter a record with a gap segment by segment, leave the gap marked as missing, and set a guard interval at its edges;
measure a clock offset by cross-correlation against a reference, to a fraction of a sample;
say which of these problems affects your own data, which repair you would apply, and what you would record about it.
Objectives for today. You will:
load the course copy of the record and confirm its fingerprint;
locate the P arrival and the first step in the raw record;
measure filter phase, gap damage and a clock shift first on synthetic signals whose answers you know;
filter the record causally and with zero phase, and compare the two at the step and at the P wave;
plant a 20 s gap and a 0.5 s clock error on copies, repair each, and grade the repair against the intact record;
write a short repair note for your project data.
How to run this notebook. In your clone of the course book, run pixi run -e core jupyter lab: a lean environment, about 850 MB, with the packages this notebook needs. If you downloaded this notebook alone, run pixi exec --spec python=3.12 --spec numpy --spec scipy --spec matplotlib --spec obspy --spec pandas --spec jupyterlab -- jupyter lab 2.9_filtering_data.ipynb in its folder; the notebook downloads the course data it needs into snapshots/ and checks their fingerprints.
| Part | Topic | Time |
|---|---|---|
| 1 | The record and its own problems | about 8 min |
| 2 | Filter phase: synthetic warm-up, then the record | about 14 min |
| 3 | Gaps: synthetic warm-up, then the record | about 16 min |
| 4 | Clock error: synthetic warm-up, then the record | about 12 min |
| 5 | Your project’s records | about 5 min |
The times are rough estimates of how long each part takes, not a schedule. The parts add to about 55 minutes and the lecture leaves about 38 for the notebook. The real-gap cell in Part 3, the parabola step in Part 4 and the exercises are optional; without them the parts take about 50 minutes, so plan to finish Part 4 or Part 5 after class.
Your-turn cells. Write your code between # --- your code and # --- end. The last line checks it: it prints correct or a hint. Unless the answer is correct, the check puts the reference result in place of each name, keeps your own value as <name>_yours for comparison, and says so in one line, so the cells after it run from the reference. If your cell raises an error, comment out your lines and run it again. A worked solution, hidden, follows each one.
import hashlib
import json
import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import obspy
from obspy.geodetics import gps2dist_azimuth, locations2degrees
from obspy.taup import TauPyModel
from scipy import signal
import pandas as pd
import urllib.request
SNAP = Path("snapshots") # course copies, committed with the book
OFFLINE = bool(os.environ.get("CI")) or os.environ.get("MLGEO_OFFLINE") == "1"
BOOK_URL = "https://raw.githubusercontent.com/geo-smart/mlgeo-book/main/book/Chapter2-DataManipulation/snapshots/"
DOWNLOADED = []
def course_file(name):
# path of a course file in snapshots/; downloaded from the book repository only if it is missing
if not (SNAP / name).exists():
SNAP.mkdir(exist_ok=True)
urllib.request.urlretrieve(BOOK_URL + name, SNAP / name)
DOWNLOADED.append(name)
return SNAP / name
read_json = lambda name: json.loads(course_file(name).read_text())
PROV = read_json("ratt_chignik_2021-07-29.provenance.json")
FILES = dict(PROV["files"]) # name -> source and fingerprint, for the five RATT files and the two map files
FILES["naturalearth_npacific_coast.csv"] = read_json("naturalearth_npacific_coast.provenance.json")
FILES["naturalearth_pnw_map.csv"] = read_json("uscrn_WA_Spokane_17_SSW_2015-2024.provenance.json")["files"]["naturalearth_pnw_map.csv"]
for name in FILES:
course_file(name)
if DOWNLOADED:
print(f"downloaded {len(DOWNLOADED)} missing course files from the book repository into snapshots/; fingerprints checked in Part 1")
ev, sta = PROV["event"], PROV["station"]
plt.rcParams.update({"figure.dpi": 90, "axes.grid": True, "grid.alpha": 0.3})
print(f"{ev['title']}: {ev['origin_time_utc']}, {ev['latitude']:.2f}° N, {-ev['longitude']:.2f}° W, {ev['depth_km']} km deep")
print(f"UW.RATT, {sta['site']}: {sta['latitude']:.4f}° N, {-sta['longitude']:.4f}° W, {sta['elevation_m']} m")
print("offline mode:", OFFLINE)M 8.2 - 2021 Chignik, Alaska Earthquake: 2021-07-29T06:15:49.188000Z, 55.36° N, 157.89° W, 35 km deep
UW.RATT, Rattlesnake Lake, King County, WA: 47.4255° N, 121.8025° W, 442.4 m
offline mode: True
Source
# Checks for the Your-turn cells. You do not need to read this cell; run it once.
# your_turn(key, globals()) prints "correct", a hint that says where to look, or "not answered yet". Unless the
# answer is correct, it puts the reference result in place of each name, keeps yours as <name>_yours, and says so.
HINTS = {
"1.step": "np.diff(raw) is largest where the surface waves are steepest, not at a step. A step is where the "
"slope changes most abruptly: look at the second difference after 700 s (np.diff(raw, n=2) of "
"samples i, i+1, i+2 belongs to sample i+1).",
"1.time": "t_step should be a time in seconds after 06:15:00, between 700 and 7200, not a sample index: "
"index the time axis t with the position you found.",
"1.other": "look for the largest absolute second difference after 700 s, and take its time from t.",
"2.sos": "butter takes the order, the two corners in Hz, the band type, fs=fs and output='sos'.",
"2.zp": "the zero-phase result comes from signal.sosfiltfilt(sos, z), forward then backward.",
"2.causal": "the causal result comes from signal.sosfilt(sos, z), forward only.",
"2.lead": "both are times relative to t_step, so subtract t_step. lead_zp uses the window t_step - 1 to "
"t_step + 0.5 s and the threshold on np.abs(zf); delay_c uses the 0.5 s after the step and np.abs(zc).",
"3.seg": "start from an array of NaN of the same length, find the indices that are not NaN with np.isnan and "
"np.flatnonzero, cut them where consecutive indices jump by more than one (np.split), and filter each "
"piece of z_nan with signal.sosfiltfilt.",
"3.grade": "keep the samples 0 to 2 s outside each edge (before gap[0] and from gap[1] on), take the RMS of the "
"intact filtered record zf there as the signal, and the RMS of the difference from zf for each method; "
"divide each error by the signal (np.sqrt, np.mean).",
"4.shift": "a later copy has each sample at a larger index; the shift in samples is an integer; filter the "
"copy the same way as zf.",
"4.lag": "cc and lags must come from the same order of b and a and the same mode; lags in seconds, so divide "
"by fs; lag_peak is the lag where cc is largest.",
"2.syn": "both are times relative to T0_STEP, so subtract T0_STEP. lead_syn: the first sample between T0_STEP - 1 "
"and T0_STEP + 0.5 s where abs(syn_zp) exceeds 25% of its largest value there; delay_syn: the largest "
"abs(syn_c) in the 0.5 s after T0_STEP.",
"3.across": "across is signal.sosfiltfilt(sos, ...) of syn_gap with its NaN set to zero by np.nan_to_num.",
"3.apart": "apart starts as np.full(len(syn_gap), np.nan); then apart[:n0] and apart[n1:] each receive "
"signal.sosfiltfilt(sos, ...) of the matching piece of syn_gap.",
"4.syn": "signal.correlate(late4, ref4, mode='full') with the late train first, signal.correlation_lags with the "
"same order and mode, divided by fs for seconds; lag4 is the lag where cc4 is largest.",
"4.sub": "check the sign and the denominator of the correction against the formula above it; the correction "
"is in samples, so divide by fs, and add it to lag_peak.",
}
TURNS = {"2.syn": ["lead_syn", "delay_syn"], "3.syn": ["across", "apart"], "4.syn": ["cc4", "lags4", "lag4"],
"1.step": ["t_step"], "2.filter": ["sos", "zf", "zc"], "2.lead": ["lead_zp", "delay_c"],
"3.segments": ["zf_seg"], "3.grade": ["ratio_naive", "ratio_seg"], "4.shift": ["z_late", "zf_late"],
"4.lag": ["cc", "lags", "lag_peak"], "4.sub": ["lag_sub"]}
_REF = {}
def _reference(ns):
# reference results from the notebook's record (raw, z, t, fs), computed once, with the values the tasks state:
# 1-10 Hz band, 2 poles; gap 850-870 s; shift 0.5 s; correlation window 355-415 s
if _REF.get("z") is ns["z"]:
return _REF
raw, z, t, fs = ns["raw"], ns["z"], ns["t"], ns["fs"]
r = {"z": z}
late = t[1:-1] > 700
r["t_step"] = ts = float(t[1:-1][late][np.argmax(np.abs(np.diff(raw, 2))[late])])
r["t_d1"] = float(t[1:][t[1:] > 700][np.argmax(np.abs(np.diff(raw))[t[1:] > 700])])
r["sos"] = sos = signal.butter(2, [1, 10], "bandpass", fs=fs, output="sos")
r["zf"], r["zc"] = zf, zc = signal.sosfiltfilt(sos, z), signal.sosfilt(sos, z)
w, post = (t >= ts - 1) & (t < ts + 0.5), (t >= ts) & (t < ts + 0.5)
r["lead_zp"] = float(t[w][np.argmax(np.abs(zf[w]) > 0.25 * np.abs(zf[w]).max())] - ts)
r["delay_c"], r["peak_zp"] = (float(t[post][np.argmax(np.abs(y[post]))] - ts) for y in (zc, zf))
i0, i1 = int(850 * fs), int(870 * fs)
z_gap = z.copy(); z_gap[i0:i1] = 0.0
r["zf_seg"] = np.full(len(z), np.nan)
r["zf_seg"][:i0], r["zf_seg"][i1:] = signal.sosfiltfilt(sos, z[:i0]), signal.sosfiltfilt(sos, z[i1:])
near = ((t >= 848) & (t < 850)) | ((t >= 870) & (t < 872))
rms = lambda x: np.sqrt(np.mean(x[near] ** 2))
r["ratio_naive"], r["ratio_seg"] = rms(signal.sosfiltfilt(sos, z_gap) - zf) / rms(zf), rms(r["zf_seg"] - zf) / rms(zf)
r["z_late"] = np.roll(z, int(round(0.5 * fs)))
r["zf_late"] = signal.sosfiltfilt(sos, r["z_late"])
a, b = zf[int(355 * fs):int(415 * fs)], r["zf_late"][int(355 * fs):int(415 * fs)]
r["cc"] = cc = signal.correlate(b, a, mode="full")
r["lags"] = signal.correlation_lags(len(b), len(a), mode="full") / fs
j = int(np.argmax(cc))
r["lag_peak"] = float(r["lags"][j])
r["lag_sub"] = r["lag_peak"] + 0.5 * (cc[j - 1] - cc[j + 1]) / (cc[j - 1] - 2 * cc[j] + cc[j + 1]) / fs
_REF.clear(); _REF.update(r)
return _REF
def _syn_reference(key, ns):
# reference results for a synthetic warm-up, from the signals its given cells built
fs, r = ns["fs"], {}
sos = signal.butter(2, [1, 10], "bandpass", fs=fs, output="sos")
if key == "2.syn":
ts, t0, zp, c = ns["ts"], ns["T0_STEP"], ns["syn_zp"], ns["syn_c"]
w, post = (ts >= t0 - 1) & (ts < t0 + 0.5), (ts >= t0) & (ts < t0 + 0.5)
r["lead_syn"] = float(ts[w][np.argmax(np.abs(zp[w]) > 0.25 * np.abs(zp[w]).max())] - t0)
r["delay_syn"], r["peak_syn_zp"] = (float(ts[post][np.argmax(np.abs(y[post]))] - t0) for y in (c, zp))
if key == "3.syn":
x, n0, n1 = ns["syn_gap"], ns["n0"], ns["n1"]
r["across"] = signal.sosfiltfilt(sos, np.nan_to_num(x))
r["apart"] = np.full(len(x), np.nan)
r["apart"][:n0], r["apart"][n1:] = signal.sosfiltfilt(sos, x[:n0]), signal.sosfiltfilt(sos, x[n1:])
if key == "4.syn":
r["cc4"] = signal.correlate(ns["late4"], ns["ref4"], mode="full")
r["lags4"] = signal.correlation_lags(len(ns["late4"]), len(ns["ref4"]), mode="full") / fs
r["lag4"] = float(r["lags4"][np.argmax(r["cc4"])])
return r
def _arr(v):
try:
return np.asarray(v, dtype=float)
except (TypeError, ValueError):
return None
def _close(v, ref, rtol=1e-6):
# same shape, NaN in the same places, and close elsewhere
a, m = _arr(v), ~np.isnan(ref)
if a is None or a.shape != np.shape(ref) or not np.array_equal(np.isnan(a), ~m):
return False
return bool(np.allclose(a[m], ref[m], rtol=rtol, atol=1e-6 * np.nanmax(np.abs(ref))))
def _number(v):
return isinstance(v, (int, float, np.integer, np.floating))
def _pair(cc, lags):
# two one-dimensional arrays of the same length (None is tested first: _arr(None) is array(nan), not None)
if cc is None or lags is None:
return False
a, b = _arr(cc), _arr(lags)
return a is not None and b is not None and a.ndim == 1 and a.shape == b.shape
def _verdict(key, v, r):
hint = lambda k: "not yet. Hint: " + HINTS.get(k, k)
if key == "2.syn":
lz, dc = v["lead_syn"], v["delay_syn"]
if not (_number(lz) and _number(dc)):
return hint("lead_syn and delay_syn should be two numbers in seconds. " + HINTS["2.syn"])
if abs(lz + r["lead_syn"]) < 0.015 and abs(lz) > 0.1:
return hint("the sign of lead_syn: subtract T0_STEP from the time you found.")
if abs(dc - r["peak_syn_zp"]) < 0.005 and abs(dc - r["delay_syn"]) >= 0.005:
return hint("delay_syn is the peak of the zero-phase output; use the causal output syn_c.")
ok = abs(lz - r["lead_syn"]) < 0.015 and abs(dc - r["delay_syn"]) < 0.005
return "correct" if ok else hint("2.syn")
if key == "3.syn":
if _close(v["across"], r["apart"]) and _close(v["apart"], r["across"]):
return hint("across and apart are swapped; across is filtered straight over the zero-filled gap.")
if not _close(v["across"], r["across"], rtol=1e-4):
return hint("3.across")
a = _arr(v["apart"])
if a is not None and a.shape == r["apart"].shape and not np.array_equal(np.isnan(a), np.isnan(r["apart"])):
return hint("the gap should stay NaN in apart: fill only the samples before n0 and from n1 on.")
return "correct" if _close(v["apart"], r["apart"], rtol=1e-4) else hint("3.apart")
if key == "4.syn":
lp = v["lag4"]
if not _pair(v["cc4"], v["lags4"]):
return hint("cc4 and lags4 should be two arrays of the same length. " + HINTS["4.syn"])
if np.shape(v["lags4"]) != np.shape(r["lags4"]):
return hint("cc4 should be the full cross-correlation: mode='full' in signal.correlate and in signal.correlation_lags.")
if not _close(v["lags4"], r["lags4"]):
return hint("lags4 should be in seconds: signal.correlation_lags with the same order and mode, divided by fs.")
if not _number(lp):
return hint("lag4 should be one number in seconds. " + HINTS["4.syn"])
if abs(lp + r["lag4"]) < 0.011:
return hint("the sign is reversed: put the late train first in signal.correlate and in correlation_lags.")
return "correct" if abs(lp - r["lag4"]) < 0.011 else hint("4.syn")
if key == "1.step":
ts = v["t_step"]
if not _number(ts) or isinstance(ts, (int, np.integer)) or not 700 <= ts <= 7200:
return hint("1.time")
if abs(ts - r["t_step"]) <= 0.005:
return "correct"
if abs(ts - r["t_step"]) <= 0.015:
return hint("one sample off: np.diff(raw, n=2)[i] is centred on sample i + 1, so take its time from t[1:-1].")
return hint("1.step" if abs(ts - r["t_d1"]) <= 0.015 else "1.other")
if key == "2.filter":
if not _close(v["sos"], r["sos"]):
return hint("2.sos")
if _close(v["zf"], r["zc"]) and _close(v["zc"], r["zf"]):
return hint("zf and zc are swapped; zf is the zero-phase result, zc the causal one.")
if not _close(v["zf"], r["zf"]):
return hint("2.zp")
return "correct" if _close(v["zc"], r["zc"]) else hint("2.causal")
if key == "2.lead":
lz, dc = v["lead_zp"], v["delay_c"]
if not (_number(lz) and _number(dc)):
return hint("lead_zp and delay_c should be two numbers in seconds. " + HINTS["2.lead"])
if abs(lz + r["lead_zp"]) < 0.015 and abs(lz) > 0.1:
return hint("the sign of lead_zp: subtract t_step from the time you found.")
if abs(dc - r["peak_zp"]) < 0.005 and abs(dc - r["delay_c"]) >= 0.005:
return hint("delay_c is the peak of the zero-phase output; use the causal output zc.")
ok = abs(lz - r["lead_zp"]) < 0.015 and abs(dc - r["delay_c"]) < 0.005
return "correct" if ok else hint("2.lead")
if key == "3.segments":
a = _arr(v["zf_seg"])
if a is None or a.shape != r["zf_seg"].shape:
return hint("zf_seg should be one array as long as z_nan. " + HINTS["3.seg"])
if not np.array_equal(np.isnan(a), np.isnan(r["zf_seg"])):
return hint("the gap should stay NaN in zf_seg: fill only the indices of the valid segments.")
return "correct" if _close(a, r["zf_seg"], rtol=1e-4) else hint("3.seg")
if key == "3.grade":
rn, rs = v["ratio_naive"], v["ratio_seg"]
if not (_number(rn) and _number(rs)):
return hint("ratio_naive and ratio_seg should be two numbers. " + HINTS["3.grade"])
ok = abs(rn / r["ratio_naive"] - 1) < 0.02 and abs(rs / r["ratio_seg"] - 1) < 0.02
return "correct" if ok else hint("3.grade")
if key == "4.shift":
ok = _close(v["z_late"], r["z_late"]) and _close(v["zf_late"], r["zf_late"])
return "correct" if ok else hint("4.shift")
if key == "4.lag":
lp = v["lag_peak"]
if not _pair(v["cc"], v["lags"]):
return hint("cc and lags should be two arrays of the same length. " + HINTS["4.lag"])
if np.shape(v["lags"]) != np.shape(r["lags"]):
return hint("cc should be the full cross-correlation: mode='full' in signal.correlate and in signal.correlation_lags.")
if not _close(v["lags"], r["lags"]):
return hint("lags should be in seconds: signal.correlation_lags with the same order and mode, divided by fs.")
if not _number(lp):
return hint("lag_peak should be one number in seconds. " + HINTS["4.lag"])
if abs(lp + r["lag_peak"]) < 0.011:
return hint("the sign is reversed: put the late copy first in signal.correlate and in correlation_lags.")
return "correct" if abs(lp - r["lag_peak"]) < 0.011 else hint("4.lag")
if key == "4.sub":
ls = v["lag_sub"]
if not _number(ls):
return hint("lag_sub should be one number in seconds. " + HINTS["4.sub"])
if abs(ls - r["lag_peak"]) < 1e-9:
return hint("that is the peak sample itself; " + HINTS["4.sub"])
# grade the parabola correction itself: with a whole-sample shift it is tiny, so the value alone would pass
# a flipped sign or a reversed denominator
dc, dr = ls - r["lag_peak"], r["lag_sub"] - r["lag_peak"]
return "correct" if abs(dc - dr) < 0.1 * abs(dr) + 1e-7 else hint("4.sub")
def your_turn(key, ns):
r = _syn_reference(key, ns) if key.endswith(".syn") else _reference(ns)
v = {n: ns.get(n) for n in TURNS[key]}
verdict = "not answered yet" if all(x is None for x in v.values()) else _verdict(key, v, r)
print(f"[{key}] {verdict}")
if verdict == "correct":
return
kept = []
for n in TURNS[key]:
if ns.get(n) is not None:
ns[n + "_yours"] = ns[n]
kept.append(n + "_yours")
ns[n] = r[n]
note = f"; yours kept as {', '.join(kept)}" if kept else ""
print(f"[{', '.join(TURNS[key])}] using the reference result so the next cells run{note}.")
def check_text(qid, text):
# written answers are recorded, not graded
words = " ".join(str(text or "").split())
print(f"[{qid}] " + (f"recorded ({len(words.split())} words)" if words else "not answered yet"))# great-circle path from the station to the epicentre, as points on the unit sphere
lat1, lon1, lat2, lon2 = np.radians([sta["latitude"], sta["longitude"], ev["latitude"], ev["longitude"]])
p1 = np.array([np.cos(lat1) * np.cos(lon1), np.cos(lat1) * np.sin(lon1), np.sin(lat1)])
p2 = np.array([np.cos(lat2) * np.cos(lon2), np.cos(lat2) * np.sin(lon2), np.sin(lat2)])
om = np.arccos(p1 @ p2)
frac = np.linspace(0, 1, 100)[:, None]
p = (np.sin((1 - frac) * om) * p1 + np.sin(frac * om) * p2) / np.sin(om)
gc_lat, gc_lon = np.degrees(np.arcsin(p[:, 2])), np.degrees(np.arctan2(p[:, 1], p[:, 0]))
ne = pd.read_csv(SNAP / "naturalearth_pnw_map.csv") # Washington: coast, borders, places
coast = pd.read_csv(SNAP / "naturalearth_npacific_coast.csv") # Alaska Peninsula to Washington, 1:50m
fig, (a1, a2) = plt.subplots(1, 2, figsize=(10.5, 3.8), gridspec_kw={"width_ratios": [1.7, 1]})
for _, g in coast.groupby("part"):
a1.plot(g["lon"], g["lat"], color="0.3", lw=0.6)
for _, g in ne[ne["kind"] == "border"].groupby("part"):
a1.plot(g["lon"], g["lat"], color="0.65", lw=0.7)
a1.plot(gc_lon, gc_lat, color="0.4", ls="--", lw=1)
a1.annotate("Alaska Peninsula", (-156.5, 56.6), xytext=(-151, 57.2), fontsize=8, color="0.35",
arrowprops=dict(arrowstyle="-", color="0.5", lw=0.6))
for (kind, part), g in ne[ne["kind"] != "place"].groupby(["kind", "part"]):
a2.plot(g["lon"], g["lat"], color="0.3" if kind == "coastline" else "0.65", lw=0.7)
for ax in (a1, a2):
ax.plot(sta["longitude"], sta["latitude"], "^", color="C0", ms=10, mec="k")
a1.plot(ev["longitude"], ev["latitude"], "*", color="C3", ms=16, mec="k")
a1.annotate(f"Chignik {ev['magnitude_type'].capitalize()} {ev['magnitude']}\n{ev['depth_km']} km deep",
(ev["longitude"], ev["latitude"]), xytext=(8, -26), textcoords="offset points", fontsize=9)
a1.annotate("UW.RATT", (sta["longitude"], sta["latitude"]), xytext=(-60, 8), textcoords="offset points", fontsize=9)
a1.set(xlim=(-162, -116), ylim=(44, 60), xlabel="longitude (°)", ylabel="latitude (°)", title="Great-circle path")
a1.set_aspect(1 / np.cos(np.radians(52)))
for _, pl in ne[ne["kind"] == "place"].iterrows():
a2.plot(pl["lon"], pl["lat"], "s", color="0.2", ms=4)
a2.annotate(pl["name"], (pl["lon"], pl["lat"]), xytext=(4, 3), textcoords="offset points", fontsize=8)
a2.annotate("RATT", (sta["longitude"], sta["latitude"]), xytext=(6, -12), textcoords="offset points", fontsize=9)
a2.set(xlim=(-125, -116.5), ylim=(45, 49.5), xlabel="longitude (°)", title="Washington")
a2.set_aspect(1 / np.cos(np.radians(47.4)))
fig.text(0.01, 0.0, "Coast and borders: Natural Earth 1:50m (course copies). "
"Station: EarthScope StationXML. Epicentre: USGS ComCat.", fontsize=7, color="0.4")
fig.tight_layout(rect=(0, 0.04, 1, 1))
Part 1. The record and its own problems (about 8 min)¶
Do: load the course copy, check it, locate the P wave, find the first step.
The course copy was downloaded from the EarthScope FDSN web services (FDSN: International Federation of Digital Seismograph Networks) on 13 October 2026. Its provenance file records each file’s source URL and its fingerprint (SHA-256, Secure Hash Algorithm), a 64-character code computed from every byte. The next cell recomputes the fingerprints, then reads the waveform. You never write to the file: every damage below is done to a copy in memory.
for name, rec in FILES.items(): # the five RATT files and the two map files
sha = hashlib.sha256((SNAP / name).read_bytes()).hexdigest()
print("matches" if sha == rec["sha256"] else "DIFFERS", sha[:16] + "...", name)
st = obspy.read(str(SNAP / "ratt_chignik_2021-07-29_UW.RATT.HHZ_0615-0815.mseed"))
raw = st[0].data.astype(float) # raw counts, as archived
tr = st[0].copy()
tr.detrend("linear"); tr.taper(max_percentage=0.05)
z = tr.data.astype(float) # trend removed, 5% taper at each end: the record we filter
fs = tr.stats.sampling_rate
t = np.arange(len(z)) / fs # seconds after 06:15:00 UTC
print(tr.id, tr.stats.starttime, f"{len(z):,} samples at {fs:.0f} Hz")matches 725e3b798e3a260c... ratt_chignik_2021-07-29_UW.RATT.HHZ_0415-0615.mseed
matches 3714a18f90478fbb... ratt_chignik_2021-07-29_UW.RATT.HHZ_0615-0815.mseed
matches ed6c4e695fd23694... ratt_chignik_2021-07-29_UW.RATT.3C_062630-062830.mseed
matches f3b9111403e4924e... ratt_chignik_2021-07-29_UW.RATT.stationxml.xml
matches 5712d99e125b4098... ratt_chignik_2021-07-29_usgs_ak0219neiszm.geojson
matches 78cc93cc44ecb725... naturalearth_npacific_coast.csv
matches 7ed9da2e9ac642e9... naturalearth_pnw_map.csv
UW.RATT..HHZ 2021-07-29T06:15:00.000001Z 720,001 samples at 100 Hz
Where should the P wave be? The iasp91 Earth model (obspy.taup) gives the travel time for the USGS depth and the epicentral distance.
dist_m, _, _ = gps2dist_azimuth(ev["latitude"], ev["longitude"], sta["latitude"], sta["longitude"])
deg = locations2degrees(ev["latitude"], ev["longitude"], sta["latitude"], sta["longitude"])
origin = obspy.UTCDateTime(ev["origin_time_utc"]) - st[0].stats.starttime # s after 06:15:00
arr = TauPyModel("iasp91").get_travel_times(ev["depth_km"], deg, ["P", "S"])
T_P = origin + min(a.time for a in arr if a.name == "P")
T_S = origin + min(a.time for a in arr if a.name == "S")
print(f"distance {dist_m / 1e3:,.0f} km on the ellipsoid, {deg:.2f}° ({deg * 111.195:,.0f} km on a sphere)")
print(f"origin {origin:.2f} s after 06:15:00; iasp91 P travel time {T_P - origin:.1f} s, so P at {T_P:.1f} s and S at {T_S:.1f} s")
print(f"largest raw value {np.abs(raw).max() / 1e6:.2f} million counts")
fig, ax = plt.subplots(figsize=(10, 3.2))
ax.plot(t, raw / 1e6, color="k", lw=0.5)
for tt, name in [(T_P, "P"), (T_S, "S")]:
ax.axvline(tt, color="C0", lw=1.5)
ax.text(tt + 6, 1.5, name, color="C0", fontweight="bold")
ax.set(xlim=(300, 1000), xlabel="seconds after 06:15:00 UTC", ylabel="10⁶ counts", title="UW.RATT HHZ, raw counts");distance 2,627 km on the ellipsoid, 23.56° (2,620 km on a sphere)
origin 49.19 s after 06:15:00; iasp91 P travel time 307.3 s, so P at 356.5 s and S at 608.9 s
largest raw value 1.99 million counts

The P wave arrives about 357 s after 06:15 (307.3 s of travel; the lecture used a depth of 32 km, the USGS gives 35 km, a difference of 0.4 s). The surface waves dominate after 650 s, swinging by up to 2 million counts.
The raw record has a problem of its own. Between 755 and 832 s, on the steepest surface-wave swings, it carries eight steps: jumps of 1,600 to 3,600 counts, each completed within two or three samples and opposite in sign to the local slope. The cause is not identified, likely the instrument or the digitizer. An earlier version of this notebook called the first of them the “P-wave onset”; it comes about 400 s after the P wave.
Your turn: find the first step. Write t_step, the time (s after 06:15:00), after 700 s, where the slope of the raw record changes most abruptly. Try np.diff(raw) first and look where it peaks; then measure the change of slope instead.
Hint: np.diff(raw, n=2) is the change of slope; np.argmax of its absolute value after 700 s gives the step.
# --- your code
t_step = None # seconds after 06:15:00, one number
# --- end
your_turn("1.step", globals())[1.step] not answered yet
[t_step] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
d2_sol = np.abs(np.diff(raw, n=2)) # d2_sol[i] is centred on sample i + 1
after_sol = t[1:-1] > 700
t_step_sol = t[1:-1][after_sol][np.argmax(d2_sol[after_sol])]
d1 = np.abs(np.diff(raw))
print(f"first difference peaks at {t[1:][t[1:] > 700][np.argmax(d1[t[1:] > 700])]:.2f} s, the steepest surface-wave swing")
print(f"second difference peaks at {t_step_sol:.2f} s, the first step")first difference peaks at 803.77 s, the steepest surface-wave swing
second difference peaks at 755.09 s, the first step
print(f"step at {t_step:.2f} s, {t_step - T_P:.0f} s after the P arrival")
k_step = int(round(t_step * fs))
around = slice(k_step - 60, k_step + 60) # 0.6 s on either side of the step
fig, ax = plt.subplots(1, 2, figsize=(10.5, 3.2))
ax[0].plot(t[around], raw[around] / 1e3, ".-", color="k", lw=0.8, ms=3)
ax[0].set(ylabel="10³ raw counts", title="raw record: a steep swing")
ax[1].plot(t[around][1:], np.diff(raw[around]), ".-", color="k", lw=0.8, ms=3)
ax[1].set(ylabel="counts per sample", title="first difference: the step")
for axi in ax:
axi.axvline(t_step, color="C3", lw=1)
axi.set_xlabel("seconds after 06:15:00 UTC")
fig.tight_layout()step at 755.09 s, 399 s after the P arrival

Look at the first difference just before the jump: from about 754.95 s it wiggles by about ±100 counts per sample. It looks like the ringing of the digitizer’s own linear-phase anti-alias filter ahead of a sharp change, as on the Ali and others (2025) slide of the lecture; that cause is a reading of the figure, not tested here.
Part 2. Filter phase (about 14 min)¶
Do: filter a synthetic signal with known onset times two ways, then the record, and compare each output with the known time.
A causal filter uses only the present and past samples (signal.sosfilt, one pass forward): its output cannot start before the input, but it shifts each frequency by a different amount, later above the band’s centre and earlier below it. A zero-phase filter runs forward and then backward over the record (signal.sosfiltfilt): no delay, but its response is symmetric in time, so energy appears before a sharp onset. Both use the 1 to 10 Hz band of the lecture 8 figures, a 2-pole Butterworth filter written as second-order sections (sos), which is numerically stable.
Warm-up: a synthetic record (about 4 min)¶
The next cell builds 20 s of signal at 100 samples per second, like RATT: a unit step at 5 s and a 5 Hz Ricker wavelet (a symmetric pulse) centred at 12 s, in white noise 1% of the step.
ts = np.arange(0, 20, 1 / fs) # 20 s at fs = 100 samples per second
T0_STEP, T0_PULSE = 5.0, 12.0 # s, the true times
arg = (np.pi * 5.0 * (ts - T0_PULSE)) ** 2 # 5 Hz Ricker wavelet centred at T0_PULSE
syn = (ts >= T0_STEP) + (1 - 2 * arg) * np.exp(-arg) + 0.01 * np.random.default_rng(0).standard_normal(len(ts))sos_syn = signal.butter(2, [1, 10], "bandpass", fs=fs, output="sos") # 2-pole Butterworth, 1-10 Hz
syn_zp = signal.sosfiltfilt(sos_syn, syn) # zero-phase: forward, then backward
syn_c = signal.sosfilt(sos_syn, syn) # causal: forward only
fig, ax = plt.subplots(1, 2, figsize=(11, 3.4))
for axi, t0, name in [(ax[0], T0_STEP, "step"), (ax[1], T0_PULSE, "Ricker pulse")]:
axi.plot(ts, syn, color="0.6", lw=1, label="synthetic")
axi.plot(ts, syn_zp, color="C0", lw=1.5, label="zero-phase")
axi.plot(ts, syn_c, color="C1", lw=1.5, label="causal")
axi.axvline(t0, color="k", lw=1)
axi.set(xlim=(t0 - 1, t0 + 1), xlabel="time (s)", title=f"{name}, true time {t0:.0f} s")
ax[0].legend(loc="upper left", fontsize=8)
fig.tight_layout()
Your turn: measure on the synthetic. Write lead_syn, the time relative to T0_STEP (negative before it) of the first sample between T0_STEP - 1 and T0_STEP + 0.5 s where abs(syn_zp) exceeds 25% of its largest value there; and delay_syn, the time relative to T0_STEP of the largest abs(syn_c) in the 0.5 s after the step.
Hint: a boolean time window such as (ts >= T0_STEP - 1) & (ts < T0_STEP + 0.5), and np.argmax (on a boolean array it returns the first True).
# --- your code
lead_syn = None # seconds, your code
delay_syn = None # seconds, your code
# --- end
your_turn("2.syn", globals())[2.syn] not answered yet
[lead_syn, delay_syn] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
w_sol = (ts >= T0_STEP - 1) & (ts < T0_STEP + 0.5)
lead_syn_sol = ts[w_sol][np.argmax(np.abs(syn_zp[w_sol]) > 0.25 * np.abs(syn_zp[w_sol]).max())] - T0_STEP
post_sol = (ts >= T0_STEP) & (ts < T0_STEP + 0.5)
delay_syn_sol = ts[post_sol][np.argmax(np.abs(syn_c[post_sol]))] - T0_STEPnear_pulse = (ts > T0_PULSE - 0.5) & (ts < T0_PULSE + 0.5)
print(f"step at {T0_STEP:.0f} s: zero-phase output starts {lead_syn:+.2f} s from it, causal output peaks {delay_syn:+.2f} s")
pre_s, post_s = (ts >= T0_STEP - 0.5) & (ts < T0_STEP), (ts >= T0_STEP) & (ts < T0_STEP + 0.5)
lobe_s = (ts >= T0_STEP - 1) & (ts < T0_STEP - 0.4)
print(f"zero-phase output, largest absolute value: {np.abs(syn_zp[pre_s]).max():.2f} in the 0.5 s before the step, "
f"{np.abs(syn_zp[post_s]).max():.2f} in the 0.5 s after; {np.abs(syn_zp[lobe_s]).max():.2f} from 1 to 0.4 s before")
for name, y in [("zero-phase", syn_zp), ("causal", syn_c)]:
print(f"pulse at {T0_PULSE:.0f} s: {name} output peaks {ts[near_pulse][np.argmax(np.abs(y[near_pulse]))] - T0_PULSE:+.2f} s from it")step at 5 s: zero-phase output starts -0.22 s from it, causal output peaks +0.05 s
zero-phase output, largest absolute value: 0.46 in the 0.5 s before the step, 0.46 in the 0.5 s after; 0.05 from 1 to 0.4 s before
pulse at 12 s: zero-phase output peaks +0.00 s from it
pulse at 12 s: causal output peaks +0.02 s from it
The zero-phase output starts about 0.2 s before the step, where the input is flat, and just before the step it is as large as just after it (0.46 against 0.46, printed above): the zero-phase response to a step is symmetric about it, with opposite signs. Ahead of that, a smaller lobe of the opposite sign, about a tenth of the peak, reaches back to about 0.9 s before the step; a lower threshold, such as 10%, would catch it and give a lead set by the noise. The causal output stays flat until the step and peaks a few samples after it. On the symmetric pulse the zero-phase peak sits exactly at the true time and the causal peak comes a couple of samples late.
The RATT record¶
The same filter and the same two measurements now go on the real record, where the step at t_step takes the place of the known time. A P wave is emergent and buried in noise; the step is sharp and its time is known from the raw samples, so it measures what each filter does.
Your turn: filter two ways. Write sos, a 2-pole Butterworth band-pass from 1 to 10 Hz as second-order sections; zf, the zero-phase filtered z; and zc, the causal filtered z.
Hint: signal.butter with output="sos" and fs=fs; then signal.sosfiltfilt and signal.sosfilt.
# --- your code
sos = None # your code
zf = None # zero-phase, your code
zc = None # causal, your code
# --- end
your_turn("2.filter", globals())[2.filter] not answered yet
[sos, zf, zc] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
sos_sol = signal.butter(2, [1, 10], "bandpass", fs=fs, output="sos")
zf_sol = signal.sosfiltfilt(sos_sol, z)
zc_sol = signal.sosfilt(sos_sol, z)fig, ax = plt.subplots(1, 2, figsize=(11, 3.6))
for axi, (t0, x0, x1, title) in zip(ax, [(t_step, 0.9, 0.9, f"step at {t_step:.2f} s"), (T_P, 6, 10, f"iasp91 P, {T_P:.1f} s")]):
axi.plot(t, zf, color="C0", lw=1.5, label="zero-phase")
axi.plot(t, zc, color="C1", lw=1.5, alpha=0.9, label="causal")
axi.axvline(t0, color="k", lw=1)
near_t0 = (t > t0 - x0) & (t < t0 + x1)
top = 1.1 * max(np.abs(zf[near_t0]).max(), np.abs(zc[near_t0]).max())
axi.set(xlim=(t0 - x0, t0 + x1), ylim=(-top, top), xlabel="seconds after 06:15:00 UTC", ylabel="counts", title=title)
ax[0].legend(loc="lower right")
fig.tight_layout()
Measure what you see. The zero-phase output should start before the step; the causal output should peak after it.
Your turn: measure the lead and the delay. Write lead_zp, the time relative to t_step (negative before it) of the first sample between t_step - 1 and t_step + 0.5 s where abs(zf) exceeds 25% of its largest value there; and delay_c, the time relative to t_step of the largest abs(zc) in the 0.5 s after the step.
Hint: a boolean time window and np.argmax (on a boolean array it returns the first True).
# --- your code
lead_zp = None # seconds, your code
delay_c = None # seconds, your code
# --- end
your_turn("2.lead", globals())[2.lead] not answered yet
[lead_zp, delay_c] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
w_sol = (t >= t_step - 1) & (t < t_step + 0.5)
lead_zp_sol = t[w_sol][np.argmax(np.abs(zf[w_sol]) > 0.25 * np.abs(zf[w_sol]).max())] - t_step
post_sol = (t >= t_step) & (t < t_step + 0.5)
delay_c_sol = t[post_sol][np.argmax(np.abs(zc[post_sol]))] - t_step# time, relative to t0, of the largest absolute value of y in the `after` seconds from t0
def peak_after(t, y, t0, after=0.5):
w = (t >= t0) & (t < t0 + after)
return float(t[w][np.argmax(np.abs(y[w]))] - t0)
pre, bg = (t >= t_step - 0.5) & (t < t_step - 0.01), (t >= t_step - 3) & (t < t_step - 1)
post_step = (t >= t_step) & (t < t_step + 0.5)
print(f"zero-phase output starts {lead_zp:+.2f} s from the step")
print(f"peaks after the step: zero-phase {peak_after(t, zf, t_step):+.2f} s, causal {delay_c:+.2f} s")
print(f"in the 0.5 s before the step: zero-phase up to {np.abs(zf[pre]).max():,.0f} counts, causal "
f"{np.abs(zc[pre]).max():,.0f}; in the 0.5 s after it, zero-phase up to {np.abs(zf[post_step]).max():,.0f}; "
f"background RMS {zf[bg].std():.0f} counts")zero-phase output starts -0.20 s from the step
peaks after the step: zero-phase +0.05 s, causal +0.06 s
in the 0.5 s before the step: zero-phase up to 1,718 counts, causal 112; in the 0.5 s after it, zero-phase up to 1,582; background RMS 45 counts
At the step, the zero-phase output starts about 0.2 s early and reaches 1,718 counts before the step, more than the 1,582 after it, against a background of 45: a picker run on it would place the onset early. The lecture figure shows zero-phase energy about 0.5 s ahead of the step: that is the smaller lobe of opposite sign, about a tenth of the peak, which the 25% threshold leaves out. The causal output stays at the background level until the step and peaks a few samples after it, reshaped. Its peak comes only about 0.01 s after the zero-phase one, because the sharp rise of the filtered step is set by the band’s upper corner, near 10 Hz, where a causal filter delays by only 0.03 s (group delay printed below). The delay is different at each frequency, as the next cell shows.
BAND, POLES = (1.0, 10.0), 2 # the Part 2 filter: corners in Hz, Butterworth order passed to butter (a band-pass doubles it)
# phase delay and group delay (s) of a causal filter at the given frequencies; negative means earlier
def filter_delays(sos, fs, freqs):
w, h = signal.sosfreqz(sos, worN=np.asarray(freqs, float), fs=fs)
phase = -np.unwrap(np.angle(h)) / (2 * np.pi * w)
_, gd = signal.group_delay(signal.sos2tf(sos), w=np.asarray(freqs, float), fs=fs)
return phase, gd / fs
# first time after `start` where |y| exceeds k times the standard deviation of y over the `noise` window
def onset_above(t, y, noise=(300.0, 350.0), k=5.0, start=350.0):
sd = float(np.std(y[(t >= noise[0]) & (t < noise[1])]))
i = np.flatnonzero((t >= start) & (np.abs(y) > k * sd))
return (float(t[i[0]]) if len(i) else float("nan")), sd
freqs = [0.625, 1, 3, 5, 10]
phase, group = filter_delays(sos, fs, freqs)
print(f"causal {BAND[0]:g}-{BAND[1]:g} Hz filter, order {POLES}; negative means earlier")
for f_, ph, gd in zip(freqs, phase, group):
print(f" {f_:5.3f} Hz: phase delay {ph:+.3f} s, group delay {gd:+.3f} s")
# lag of x behind y (s; negative means earlier), from the cross-correlation peak within max_lag
def lag_within(x, y, max_lag=0.6):
c_ = signal.correlate(x - x.mean(), y - y.mean(), mode="full")
l_ = signal.correlation_lags(len(x), len(y), mode="full") / fs
keep = np.abs(l_) <= max_lag
return float(l_[keep][np.argmax(c_[keep])])
p_win = (t >= 356) & (t < 376) # the P wave train
spec_f = np.fft.rfftfreq(p_win.sum(), 1 / fs)
f_peak = spec_f[np.argmax(np.abs(np.fft.rfft(zf[p_win] * np.hanning(p_win.sum()))))]
envelope = lambda y: np.abs(signal.hilbert(y))
print(f"P wave train, 356-376 s: filtered spectrum peaks at {f_peak:.1f} Hz; causal output against zero-phase: "
f"cycles {lag_within(zc[p_win], zf[p_win]):+.2f} s, envelope {lag_within(envelope(zc)[p_win], envelope(zf)[p_win]):+.2f} s")
on_c, n_c = onset_above(t, zc)
on_z, n_z = onset_above(t, zf)
print(f"first sample above 5 times its noise (standard deviation over 300-350 s): causal {on_c:.2f} s "
f"(noise {n_c:.1f} counts), zero-phase {on_z:.2f} s (noise {n_z:.1f} counts); iasp91 P {T_P:.2f} s")causal 1-10 Hz filter, order 2; negative means earlier
0.625 Hz: phase delay -0.570 s, group delay +0.274 s
1.000 Hz: phase delay -0.250 s, group delay +0.273 s
3.000 Hz: phase delay -0.003 s, group delay +0.052 s
5.000 Hz: phase delay +0.015 s, group delay +0.038 s
10.000 Hz: phase delay +0.025 s, group delay +0.029 s
P wave train, 356-376 s: filtered spectrum peaks at 1.0 Hz; causal output against zero-phase: cycles -0.21 s, envelope +0.23 s
first sample above 5 times its noise (standard deviation over 300-350 s): causal 359.47 s (noise 4.9 counts), zero-phase 359.97 s (noise 3.5 counts); iasp91 P 356.49 s
At the P wave the two outputs differ more than at the step. Most P energy passed by this band lies near 1 Hz, at the lower corner (the filtered spectrum of the P wave train peaks at 1.0 Hz), well below the band’s centre, about 3.2 Hz (the geometric mean of the corners). There a causal band-pass moves the signal by two different delays, printed above. A short pulse moves with the group delay (+0.27 s at 1 Hz), so its peak comes late, as the 5 Hz pulse of the warm-up did, by 0.02 s. The cycles of a long wave train near 1 Hz move with the phase delay (−0.25 s), so they come early. On the RATT P wave train, 356 to 376 s, the causal cycles lead the zero-phase ones by 0.21 s and the envelope lags by 0.23 s. Energy above 3 Hz is delayed by a few hundredths of a second. The causal output still never starts before the input.
The first P energy above five times the noise comes at 359.5 s in the causal output and 360.0 s in the zero-phase output (printed above), about 3 s after the iasp91 time. A one-dimensional Earth model can miss by that much, and the onset is emergent, its first wiggles the size of the noise. That is why the step, sharp and of known time, is the better test of a filter. The rule from the lecture: do not interpret small wiggles just before a sharp onset in zero-phase output, since the filter itself puts energy there.
Which to use depends on the task: real-time detection and studies of what happens before an onset (precursors, first motions) need a causal filter; aligning or stacking waveforms offline is done with zero phase. Either way, record the filter type, corners, number of poles, and causal or zero-phase with the data.
Part 3. Gaps (about 16 min)¶
Do: plant a gap in a synthetic signal and in the record, filter across it, repair it, grade both against the intact signal.
Telemetry drops out, disks fill, stations reboot. A careless merge fills the missing samples with zeros, which turns each edge into a step the size of the record’s value there.
Warm-up: a synthetic gap (about 4 min)¶
The next cell builds 60 s at 100 samples per second: three sines at 1.5, 3.7 and 7.2 Hz, inside the 1 to 10 Hz band, on a slow 40 s swell 50 times larger, below the band, as the 1 to 10 Hz signal at RATT rides on surface waves of much larger amplitude. Then it marks 25 to 30 s as missing (NaN).
t3 = np.arange(0, 60, 1 / fs) # 60 s at fs = 100 samples per second
clean = (np.sin(2 * np.pi * 1.5 * t3) + 0.6 * np.sin(2 * np.pi * 3.7 * t3 + 1) + 0.3 * np.sin(2 * np.pi * 7.2 * t3 + 2)
+ 50 * np.sin(2 * np.pi * t3 / 40)) # three sines in the band, on a 40 s swell
n0, n1 = int(25 * fs), int(30 * fs) # a 5 s gap, 25 to 30 s
syn_gap = clean.copy(); syn_gap[n0:n1] = np.nan # the gap marked as missingYour turn: filter across the gap, then around it. With sos from Part 2, write across: syn_gap with its NaN set to zero, filtered with zero phase straight across the gap; and apart: an array as long as syn_gap, NaN inside the gap, with the samples before n0 and from n1 on each filtered on their own with zero phase.
Hint: np.nan_to_num sets NaN to zero; np.full(len(syn_gap), np.nan) starts apart; fill apart[:n0] and apart[n1:].
# --- your code
across = None # your code
apart = None # your code
# --- end
your_turn("3.syn", globals())[3.syn] not answered yet
[across, apart] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
across_sol = signal.sosfiltfilt(sos, np.nan_to_num(syn_gap))
apart_sol = np.full(len(syn_gap), np.nan)
apart_sol[:n0] = signal.sosfiltfilt(sos, syn_gap[:n0])
apart_sol[n1:] = signal.sosfiltfilt(sos, syn_gap[n1:])# RMS of (test - ref) over 0 to `width` s outside each gap edge, and the RMS of ref there (the local signal)
def edge_error(test, ref, t, gap, width=2.0):
near = ((t >= gap[0] - width) & (t < gap[0])) | ((t >= gap[1]) & (t < gap[1] + width))
return float(np.sqrt(np.mean((test[near] - ref[near]) ** 2))), float(np.sqrt(np.mean(ref[near] ** 2)))
clean_f = signal.sosfiltfilt(sos, clean) # the clean signal filtered the same way: the truth
for name, test in [("across the zero-filled gap", across), ("each segment alone", apart)]:
err, local3 = edge_error(test, clean_f, t3, (25.0, 30.0))
print(f"{name}: edge error {err / local3:.2f} times the local signal ({local3:.2f} RMS) over 2 s outside each edge")
fig, ax = plt.subplots(figsize=(10, 3))
ax.plot(t3, clean_f, color="0.5", lw=1.5, label="clean signal, filtered")
ax.plot(t3, across, color="C3", lw=1, label="filtered across the zero-filled gap")
ax.plot(t3, apart, color="C0", lw=1, label="each segment filtered alone")
ax.axvspan(25, 30, color="k", alpha=0.08)
ax.set(xlim=(20, 35), xlabel="time (s)", title="Synthetic gap, 1-10 Hz")
ax.legend(loc="upper left", fontsize=8);across the zero-filled gap: edge error 5.49 times the local signal (0.79 RMS) over 2 s outside each edge
each segment alone: edge error 0.20 times the local signal (0.79 RMS) over 2 s outside each edge

The zero-filled edges are steps of about 35 and 49, the value of the swell there, and the band-pass rings at both edges with an error several times the in-band signal. Filtered segment by segment, with the gap left as NaN, the error drops by more than an order of magnitude; what remains near each edge is the filter’s memory of the edge, measured below as the guard interval.
The RATT record¶
The same repair, each segment filtered alone with the gap left as NaN, now goes on the real record, graded by the same edge error (edge_error computes it). Here you plant a 20 s gap from 850 to 870 s, inside the surface waves, on a copy.
GAP = (850.0, 870.0) # s after 06:15:00 UTC, the planted gap
gap = GAP
i0, i1 = int(gap[0] * fs), int(gap[1] * fs)
z_gap = z.copy(); z_gap[i0:i1] = 0.0 # gap filled with zeros
zf_gap = signal.sosfiltfilt(sos, z_gap) # filtered straight across the gap
z_nan = z.copy(); z_nan[i0:i1] = np.nan # gap marked as missing
print(f"record at the edges: {z[i0 - 1]:,.0f} and {z[i1]:,.0f} counts; the 1-10 Hz signal over 2 s outside the edges "
f"is {edge_error(zf, zf, t, gap)[1]:.0f} counts RMS")record at the edges: 95,994 and 156,500 counts; the 1-10 Hz signal over 2 s outside the edges is 70 counts RMS
Your turn: filter segment by segment. Write zf_seg: an array as long as z_nan, NaN inside the gap, and elsewhere each run of valid samples filtered on its own with sos and zero phase. Four to six lines.
Hint: np.flatnonzero(~np.isnan(z_nan)) gives the valid indices; np.split them where np.diff of the indices exceeds 1.
# --- your code
zf_seg = None # your code
# --- end
your_turn("3.segments", globals())[3.segments] not answered yet
[zf_seg] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
zf_seg_sol = np.full(len(z_nan), np.nan)
good_sol = np.flatnonzero(~np.isnan(z_nan))
for seg_sol in np.split(good_sol, np.flatnonzero(np.diff(good_sol) > 1) + 1):
zf_seg_sol[seg_sol] = signal.sosfiltfilt(sos, z_nan[seg_sol])Grade both methods against the intact record zf, over the 2 s outside each edge of the gap, where the damage is largest.
Your turn: grade the two repairs. Write ratio_naive and ratio_seg: the root-mean-square (RMS) difference from zf of zf_gap and of zf_seg, over the samples 0 to 2 s outside either edge, each divided by the RMS of zf over the same samples.
Hint: a boolean mask near of those samples, then np.sqrt(np.mean(...**2)).
# --- your code
ratio_naive = None # your code
ratio_seg = None # your code
# --- end
your_turn("3.grade", globals())[3.grade] not answered yet
[ratio_naive, ratio_seg] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
near_sol = ((t >= gap[0] - 2) & (t < gap[0])) | ((t >= gap[1]) & (t < gap[1] + 2))
sig_sol = np.sqrt(np.mean(zf[near_sol] ** 2))
ratio_naive_sol = np.sqrt(np.mean((zf_gap[near_sol] - zf[near_sol]) ** 2)) / sig_sol
ratio_seg_sol = np.sqrt(np.mean((zf_seg[near_sol] - zf[near_sol]) ** 2)) / sig_solprint(f"edge error: filtered across the zero-filled gap {ratio_naive:.0f} times the local signal; "
f"each segment alone {ratio_seg:.2f} times")
dist_gap = np.where(t < gap[0], gap[0] - t, t - gap[1]) # s from the nearer edge, negative inside the gap
for d0, d1 in [(0, 0.5), (0.5, 1), (1, 2)]:
m = (dist_gap >= d0) & (dist_gap < d1)
print(f" each segment alone, {d0:g} to {d1:g} s from an edge: error {np.sqrt(np.mean((zf_seg[m] - zf[m]) ** 2)):.0f} counts RMS")
near_edge = (dist_gap >= 0) & (dist_gap < 0.5)
print(f"slope of the record within 0.5 s of the edges: up to {np.abs(np.gradient(z, 1 / fs))[near_edge].max():,.0f} counts per second")
fig, ax = plt.subplots(2, 1, figsize=(10, 5), sharex=True)
ax[0].plot(t, zf, color="0.5", lw=1.2, label="intact record, filtered")
ax[0].plot(t, zf_gap, color="C3", lw=1, label="filtered across the zero-filled gap")
ax[1].plot(t, zf, color="0.5", lw=1.2, label="intact record, filtered")
ax[1].plot(t, zf_seg, color="C0", lw=1, label="each segment filtered alone")
ax[1].set(ylim=(-400, 400), xlabel="seconds after 06:15:00 UTC")
for axi in ax:
axi.axvspan(*gap, color="k", alpha=0.08)
axi.set(xlim=(gap[0] - 15, gap[1] + 15), ylabel="counts")
axi.legend(loc="upper left");edge error: filtered across the zero-filled gap 185 times the local signal; each segment alone 1.75 times
each segment alone, 0 to 0.5 s from an edge: error 245 counts RMS
each segment alone, 0.5 to 1 s from an edge: error 27 counts RMS
each segment alone, 1 to 2 s from an edge: error 3 counts RMS
slope of the record within 0.5 s of the edges: up to 159,900 counts per second

The zero-filled gap makes the filter ring at both edges: a step contains all frequencies, and the band-pass answers at its corners. Within about 2 s of each edge, on both sides, the output rings at up to 70,000 counts, hundreds of times the local signal; a machine-learning model trained on windows cut across these edges would learn from the ringing. Filtering each segment alone and leaving the gap as NaN cuts the edge error by two orders of magnitude, and the gap stays declared as missing. Segment by segment the error is still 1.75 times the local signal over those 2 s, against 0.20 in the warm-up, but it sits almost entirely within 0.5 s of each edge (printed above), where the record swings by up to 160,000 counts per second: this is why the guard interval exists.
The remaining error near each edge is the filter’s memory of the edge. How far does it reach? The guard interval is the stretch at each edge to leave out of later analysis (feature extraction in 2.11). The next cell measures how far from the gap the error exceeds 1% of the background, the RMS of the intact filtered record 5 to 60 s from the gap.
# seconds before and after the gap over which |test - ref| exceeds frac times the background,
# the RMS of ref 5 to 60 s from the gap; returns (before, after, background)
def guard_interval(test, ref, t, gap, frac=0.01):
dist = np.where(t < gap[0], gap[0] - t, t - gap[1])
out = ~np.isnan(test)
local = np.sqrt(np.mean(ref[out & (dist > 5) & (dist < 60)] ** 2))
bad = out & (np.abs(test - ref) > frac * local) & (dist < 200)
before = float(dist[bad & (t < gap[0])].max()) if (bad & (t < gap[0])).any() else 0.0
after = float(dist[bad & (t > gap[1])].max()) if (bad & (t > gap[1])).any() else 0.0
return before, after, float(local)
before, after, bg = guard_interval(zf_seg, zf, t, gap)
guard, f_low = max(before, after), BAND[0]
print(f"background 5 to 60 s from the gap: {bg:.0f} counts RMS")
print(f"error above 1% of it for {before:.1f} s before and {after:.1f} s after the gap: a guard of about "
f"{np.ceil(guard):.0f} s, {guard * f_low:.1f} periods of the {f_low:g} Hz lower corner")background 5 to 60 s from the gap: 166 counts RMS
error above 1% of it for 1.1 s before and 1.6 s after the gap: a guard of about 2 s, 1.6 periods of the 1 Hz lower corner
Optional, online only: a real gap. On 21 January 2021 at 17:48 UTC, UW.RATT HHZ lost 40 s of data in transmission; the archive holds two segments. The next cell fetches about 21 minutes around it from EarthScope and grades zero-filling against segment-by-segment filtering, as the lecture figure did (a peak edge error about 13 times the local signal, for about 1 s). Its guard is measured against the full local signal, not 1% of it as above, because the real record has no intact copy to grade against, only the segment-wise result. It is skipped when the notebook runs offline.
if OFFLINE:
print("offline mode: skipped (online it downloads about 21 minutes of UW.RATT HHZ from EarthScope)")
else:
try:
# fetch the 40 s telemetry gap and 600 s on either side; grade as the lecture 8 figure did
# (4-pole zero-phase 1-10 Hz band-pass from obspy; each segment demeaned and tapered over 1 s)
from obspy.clients.fdsn import Client
g_guess = obspy.UTCDateTime("2021-01-21T17:48:03")
live = Client("EARTHSCOPE", timeout=60).get_waveforms("UW", "RATT", "--", "HHZ", g_guess - 600, g_guess + 640)
g = max(live.get_gaps(), key=lambda x: x[6])
g0, gdur = g[4], g[6] # gap start and duration (s)
zero = live.copy().merge(fill_value=0)[0] # merged with zeros
tz = zero.times() + (zero.stats.starttime - g0) # s after the gap start
dist = np.where(tz < 0, -tz, tz - gdur) # s from the nearer edge
zero.detrend("demean")
zero.filter("bandpass", freqmin=1.0, freqmax=10.0, corners=4, zerophase=True)
seg = np.full(zero.stats.npts, np.nan) # each segment filtered alone, gap left NaN
for piece in live.copy():
piece.detrend("demean"); piece.taper(max_percentage=None, max_length=1.0)
piece.filter("bandpass", freqmin=1.0, freqmax=10.0, corners=4, zerophase=True)
k0 = int(round((piece.stats.starttime - zero.stats.starttime) * piece.stats.sampling_rate))
seg[k0:k0 + piece.stats.npts] = piece.data
valid = ~np.isnan(seg)
local = float(np.sqrt(np.mean(seg[valid & (dist > 60) & (dist < 300)] ** 2)))
diff = np.abs(zero.data - seg)
peak = float(np.nanmax(diff[valid & (dist < 5)]))
bad = valid & (diff > local) & (dist < 120)
g_before = float(-tz[bad & (tz < 0)].min()) if (bad & (tz < 0)).any() else 0.0
g_after = float(tz[bad & (tz > gdur)].max() - gdur) if (bad & (tz > gdur)).any() else 0.0
fig, ax = plt.subplots(figsize=(10, 3))
ax.plot(tz, zero.data, color="C1", lw=0.8, label="merged with zeros, then filtered")
ax.plot(tz, seg, color="C0", lw=0.8, label="each segment filtered alone")
ax.axvspan(0, gdur, color="k", alpha=0.08)
g_time = g0.strftime("%Y-%m-%d %H:%M:%S.%f")[:-4]
ax.set(xlim=(-20, gdur + 20), xlabel=f"seconds after {g_time} UTC", ylabel="counts",
title="UW.RATT HHZ, real telemetry gap, 1-10 Hz")
ax.legend(loc="upper right", fontsize=8)
print(f"gap: {g_time} UTC, {gdur:.2f} s; local 1-10 Hz signal {local:.1f} counts RMS (60 to 300 s from the gap)")
print(f"peak edge error of the zero-filled record {peak:.0f} counts, {peak / local:.0f} times the local signal; "
f"above the local signal for {g_before:.1f} s before and {g_after:.1f} s after the gap")
except Exception as err:
print("download failed, nothing lost: the planted gap above is the graded test.", err)offline mode: skipped (online it downloads about 21 minutes of UW.RATT HHZ from EarthScope)
Part 4. Clock error (about 12 min)¶
Do: recover a known shift between two synthetic pulse trains, then shift a copy of the record by 0.5 s and recover that shift.
When a station’s GPS clock loses lock, its time stamps drift. The waveform is unchanged and looks perfect; every arrival time, every pick used as a label, every travel time is wrong. The repair measures the lag against a reference and corrects the time stamps.
Warm-up: a shifted pulse train (about 3 min)¶
The next cell builds 30 s at 100 samples per second: four short 5 Hz pulses at irregular times, the reference, and the same train 0.37 s later, the late copy.
t4 = np.arange(0, 30, 1 / fs) # 30 s at fs = 100 samples per second
pulse = lambda t0: np.exp(-((t4 - t0) / 0.1) ** 2) * np.cos(2 * np.pi * 5 * (t4 - t0)) # a 5 Hz pulse at t0 (s)
ref4 = sum(pulse(t0) for t0 in (4.0, 9.5, 13.2, 21.0)) # the reference train
late4 = sum(pulse(t0 + 0.37) for t0 in (4.0, 9.5, 13.2, 21.0)) # the same train, 0.37 s laterYour turn: recover the shift. Write cc4, the full cross-correlation of late4 with ref4; lags4, the lag of each value in seconds; and lag4, the lag of the largest value.
Hint: signal.correlate(late4, ref4, mode="full"), signal.correlation_lags with the same order and mode, divided by fs; np.argmax.
# --- your code
cc4 = None # your code
lags4 = None # seconds, your code
lag4 = None # seconds, your code
# --- end
your_turn("4.syn", globals())[4.syn] not answered yet
[cc4, lags4, lag4] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
cc4_sol = signal.correlate(late4, ref4, mode="full")
lags4_sol = signal.correlation_lags(len(late4), len(ref4), mode="full") / fs
lag4_sol = lags4_sol[np.argmax(cc4_sol)]k4 = np.argmax(cc4)
y0, y1, y2 = cc4[k4 - 1], cc4[k4], cc4[k4 + 1]
lag4_sub = lag4 + 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2) / fs # parabola through the peak and its neighbours
print(f"planted +0.37 s; peak sample {lag4:+.2f} s; parabola {lag4_sub:+.3f} s")
fig, ax = plt.subplots(figsize=(8, 2.8))
ax.plot(lags4, cc4 / cc4.max(), color="C0")
ax.axvline(0.37, color="C3", ls="--")
ax.set(xlim=(-1, 1), xlabel="lag (s)", ylabel="normalized", title="Correlation, late train against reference");planted +0.37 s; peak sample +0.37 s; parabola +0.370 s

The correlation peaks at the planted shift. Around the peak it repeats the 5 Hz period of the pulses, with troughs 0.1 s and smaller peaks 0.2 s on either side: with noise, or with waveforms that differ between the two records, the largest value can jump to a neighbouring peak, one period off. A reference with a broadband signal makes that less likely. The shift of 0.37 s is a whole number of samples (37), so the parabola, explained below, changes nothing here; exercise 3 tries a shift between samples.
The RATT record¶
The same signal.correlate, signal.correlation_lags and peak search now go on the real record, against its intact copy. Here the copy is shifted by 50 samples (np.roll wraps the last 50 samples to the start, far from the window used), and the reference is the intact record, over a 60 s window on the P wave train (355 to 415 s).
Your turn: shift a copy. Write z_late, a copy of z with every sample moved 0.5 s later (50 samples), and zf_late, its zero-phase 1 to 10 Hz filtered version with sos.
Hint: np.roll; 0.5 s is 0.5 * fs samples.
# --- your code
z_late = None # your code
zf_late = None # your code
# --- end
your_turn("4.shift", globals())[4.shift] not answered yet
[z_late, zf_late] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
z_late_sol = np.roll(z, int(round(0.5 * fs)))
zf_late_sol = signal.sosfiltfilt(sos, z_late_sol)P_WINDOW = (355.0, 415.0) # s after 06:15:00, the correlation window on the P wave train
w0, w1 = int(P_WINDOW[0] * fs), int(P_WINDOW[1] * fs)
a, b = zf[w0:w1], zf_late[w0:w1] # reference window and late windowYour turn: cross-correlate. Write cc, the full cross-correlation of the late window b with the reference a; lags, the lag of each value in seconds; and lag_peak, the lag of the largest value.
Hint: signal.correlate, signal.correlation_lags, np.argmax; put the late window first.
# --- your code
cc = None # your code
lags = None # seconds, your code
lag_peak = None # seconds, your code
# --- end
your_turn("4.lag", globals())[4.lag] not answered yet
[cc, lags, lag_peak] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
cc_sol = signal.correlate(b, a, mode="full")
lags_sol = signal.correlation_lags(len(b), len(a), mode="full") / fs
lag_peak_sol = lags_sol[np.argmax(cc_sol)]The peak sample gives the lag to the nearest sample, ±0.005 s. The next step is optional. A parabola through the peak and its two neighbours places the maximum between samples. With y0, y1, y2 the values at j − 1, j, j + 1, the vertex lies 0.5 (y0 − y2) / (y0 − 2 y1 + y2) samples from j.
Your turn: refine with a parabola (optional). Write lag_sub, the lag in seconds at the vertex of the parabola through the three values of cc around its peak.
Hint: np.argmax(cc) gives the peak index j; the formula above gives the offset from j in samples.
# --- your code
lag_sub = None # seconds, your code
# --- end
your_turn("4.sub", globals())[4.sub] not answered yet
[lag_sub] using the reference result so the next cells run.
Worked solution below (click ⋯ to open).
Notebook Cell
# Worked solution, open after you tried
# Names end in _sol so that running this cell keeps your own results.
j_sol = np.argmax(cc)
y0_sol, y1_sol, y2_sol = cc[j_sol - 1], cc[j_sol], cc[j_sol + 1]
lag_sub_sol = lag_peak + 0.5 * (y0_sol - y2_sol) / (y0_sol - 2 * y1_sol + y2_sol) / fsSHIFT_S = 0.5 # s, the clock error planted above (50 samples)
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(lags, cc / cc.max(), color="C0")
ax.axvline(lag_peak, color="C3", ls="--")
ax.set(xlim=(-2, 2), xlabel="lag (s)", ylabel="normalized",
title=f"Correlation of {P_WINDOW[0]:.0f}-{P_WINDOW[1]:.0f} s, late copy against reference")
print(f"planted {SHIFT_S:+.2f} s; peak sample {lag_peak:+.2f} s; parabola {lag_sub:+.3f} s")planted +0.50 s; peak sample +0.50 s; parabola +0.500 s

The recovery is exact by construction: the late copy is the reference itself, shifted, so the waveforms match perfectly. This shows the method, not its accuracy. On real data the reference is a co-located sensor, a neighbour station (after removing the predicted travel-time difference), or the correlation of ambient noise between two stations, tracked day by day. The lecture showed two such cases:
Seafloor clock drift. Naranjo and others (2024, Seismica, Naranjo et al. (2024)) correlated ambient noise (0.2 to 0.4 Hz) between ocean-bottom station O01 and land station RET off Iceland. O01’s clock was already 0.31 s off at deployment, so a straight line from zero to the clock difference measured at recovery (−1.02 s) overcorrects; fitting both an offset and a drift aligns the correlations.
A 270 s timing error at US.HDIL, Illinois. GPS timing was lost from 3 October 2022 to 6 March 2023. Noise correlation with station N4.N41A, 133 km away, shows the lag growing to +270 s by February, and the P wave of the February 2023 Kahramanmaraş earthquake arrives +269.9 s late at HDIL, against +1.2 s at the neighbour P43A.
Part 5. Your project’s records (about 5 min)¶
Do: write three short answers about the data of your team project.
Which of the three problems (filter phase, gaps, clock error) applies to your data, and where would you see it? Which repair would you apply? What would you write down about it so that someone else can redo it: for example the filter type, corners and phase; the start, end and fill value of each gap and the guard interval; the timing reference, the lag or drift found, and the correction applied.
q5_problem = "" # which problem, in which part of your data
q5_repair = "" # the repair you would apply
q5_record = "" # what you would write down about it
check_text("5.problem", q5_problem); check_text("5.repair", q5_repair); check_text("5.record", q5_record)[5.problem] not answered yet
[5.repair] not answered yet
[5.record] not answered yet
Exercises (if you have time)¶
1. A gap in the P wave train. The next cell plants the gap at 360 to 420 s, on the P wave train (task 2 of the lecture), and grades both methods with edge_error, from the Part 3 warm-up. Change gap2 to try other places. Why is the zero-filled error, relative to the local signal, much smaller than in the surface waves?
# zero-phase filter each run of valid (not NaN) samples on its own; the gap stays NaN
def filter_segments(x, sos):
out = np.full(len(x), np.nan)
good = np.flatnonzero(~np.isnan(x))
for seg in np.split(good, np.flatnonzero(np.diff(good) > 1) + 1):
out[seg] = signal.sosfiltfilt(sos, x[seg])
return out
gap2 = (360.0, 420.0)
j0, j1 = int(gap2[0] * fs), int(gap2[1] * fs)
z_gap2 = z.copy(); z_gap2[j0:j1] = 0.0
z_nan2 = z.copy(); z_nan2[j0:j1] = np.nan
for name, test in [("zero-filled", signal.sosfiltfilt(sos, z_gap2)), ("segments", filter_segments(z_nan2, sos))]:
err, local2 = edge_error(test, zf, t, gap2)
print(f"gap {gap2[0]:.0f}-{gap2[1]:.0f} s, {name}: {err / local2:.2f} times the local signal ({local2:.0f} counts RMS)")gap 360-420 s, zero-filled: 2.06 times the local signal (559 counts RMS)
gap 360-420 s, segments: 0.05 times the local signal (559 counts RMS)
2. A longer period band. Redo Part 3 in a 0.1 to 1 Hz band. Write sos2, then run the cell: it refilters the intact record and both repairs in the new band and measures the guard interval. The grading window grows to 20 s (width=20), because a 2 s window would sit inside the new guard. How does the guard scale with the lower corner frequency?
sos2 = None # your code: a 2-pole Butterworth band-pass from 0.1 to 1 Hz, as in Part 2
if sos2 is None:
print("set sos2 first")
else:
zf2 = signal.sosfiltfilt(sos2, z)
for name, test in [("zero-filled", signal.sosfiltfilt(sos2, z_gap)), ("segments", filter_segments(z_nan, sos2))]:
err, local2 = edge_error(test, zf2, t, gap, width=20)
print(f"0.1-1 Hz, {name}: {err / local2:.2f} times the local signal over 0 to 20 s from the edges")
before2, after2, bg2 = guard_interval(filter_segments(z_nan, sos2), zf2, t, gap)
g2 = max(before2, after2)
print(f"guard {before2:.1f} s before and {after2:.1f} s after the gap: {g2 * 0.1:.1f} periods of the 0.1 Hz corner")set sos2 first
Expected, from the worked line sos2 = signal.butter(2, [0.1, 1], "bandpass", fs=fs, output="sos"): zero-filled about 0.6 times and segments about 0.3 times the local signal; a guard of about 11 s before and 10 s after the gap, about one period of the lower corner.
3. A clock error between samples. A shift of exactly 50 samples leaves the parabola little to do. The next cell plants a shift of 0.537 s by multiplying the spectrum by a phase ramp, so that the shift falls between samples. Repeat your Part 4 lines on the window b3 against a: what do the peak sample and the parabola give?
f = np.fft.rfftfreq(len(z), 1 / fs)
z_frac = np.fft.irfft(np.fft.rfft(z) * np.exp(-2j * np.pi * f * 0.537), n=len(z)) # 0.537 s later
b3 = signal.sosfiltfilt(sos, z_frac)[w0:w1]
# your code: cross-correlate b3 with a, take the peak sample, then the parabolaNotebook Cell
# Worked solution, open after you tried
cc3 = signal.correlate(b3, a, mode="full")
lags3 = signal.correlation_lags(len(b3), len(a), mode="full") / fs
k = np.argmax(cc3)
sub3 = lags3[k] + 0.5 * (cc3[k - 1] - cc3[k + 1]) / (cc3[k - 1] - 2 * cc3[k] + cc3[k + 1]) / fs
print(f"planted +0.537 s; peak sample {lags3[k]:+.3f} s; parabola {sub3:+.4f} s")planted +0.537 s; peak sample +0.540 s; parabola +0.5367 s
Data and credit. Waveforms and station metadata: UW network, University of Washington (1963), Pacific Northwest Seismic Network, University of Washington (1963). Data were accessed from the NSF NGF data archive operated by EarthScope Consortium (NSF award 2435260). Earthquake parameters: USGS ComCat event ak0219neiszm, public domain. Coastlines and borders: Natural Earth, public domain; snapshots/naturalearth_npacific_coast.csv is built by snapshots/make_naturalearth_npacific_coast.py. Course copies of the seismic data, their source URLs and fingerprints: snapshots/ratt_chignik_2021-07-29.provenance.json, built by snapshots/make_ratt_chignik_2021-07-29.py.
- Naranjo, D., Parisi, L., Jónsson, S., Jousset, P., Werthmüller, D., & Weemstra, C. (2024). Ocean Bottom Seismometer Clock Correction using Ambient Seismic Noise: OBS Clock Correction. Seismica, 3(1). 10.26443/seismica.v3i1.367
- University of Washington. (1963). Pacific Northwest Seismic Network - University of Washington. International Federation of Digital Seismograph Networks. 10.7914/SN/UW