Generation of synthetic noise and synthetic data for geoscience
To run it. From the repository root, start pixi run -e core jupyter lab. The core environment has every package imported here: numpy, scipy, matplotlib, pandas, obspy and the course package mlgeo_synth. The seismic records are course copies in snapshots/, beside this notebook; a missing file is downloaded once from the book repository, so after that the notebook runs offline.
1. Introduction¶
Noise in geoscientific data comes from the environment, from the instrument, and from human activity. If we can simulate noise, we can build controlled datasets with known ground truth. That lets us test filters, benchmark detectors, and augment training sets for machine learning.
This lesson covers synthetic noise in two settings:
1D time series: seismic records, atmospheric pressure, sea surface temperature.
2D geospatial fields: topography, soil moisture, temperature maps.
We end with a realistic seismological example, an in-class activity in which your team builds a synthetic version of its own data (section 5), and a discussion of when synthetic data is admissible in research.
Types of noise¶
White noise: constant power spectral density at all frequencies. Typical of instrumental noise.
Pink noise: power spectral density proportional to . Common in natural systems such as climate records.
Gaussian noise: noise whose amplitude distribution is normal. White noise is often drawn from a Gaussian.
Spatially correlated noise: noise that varies smoothly over space, as in atmospheric or sensor artifacts in maps.
Throughout this notebook we use numpy’s modern random generator, seeded for reproducibility. Seeding matters: a synthetic dataset that cannot be regenerated is not reproducible.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)2. Noise models in 1D and 2D¶
2.1 White and pink noise (1D)¶
White noise is a sequence of independent Gaussian draws. Pink noise is built in the frequency domain: we impose an amplitude spectrum proportional to (so the power goes as ), draw random phases, and transform back to the time domain. We use np.fft.irfft, which takes the spectrum at non-negative frequencies only and returns a real signal by construction.
n = 1000 # number of time points
time = np.linspace(0, 100, n)
# White noise: independent Gaussian draws, zero mean
white_noise = rng.standard_normal(n)
def generate_pink_noise(size, rng):
"""Pink (1/f) noise: power spectral density proportional to 1/f.
Build the one-sided spectrum with amplitude 1/sqrt(f) and random
phases, then invert with irfft to get a real time series.
"""
freqs = np.fft.rfftfreq(size)
amplitude = np.zeros_like(freqs)
amplitude[1:] = 1.0 / np.sqrt(freqs[1:]) # skip f=0 to avoid division by zero
phases = rng.uniform(0, 2 * np.pi, len(freqs))
spectrum = amplitude * np.exp(1j * phases)
pink = np.fft.irfft(spectrum, n=size)
return pink / np.std(pink)
pink_noise = generate_pink_noise(n, rng)
plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.plot(time, white_noise, label='White Noise')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Synthetic White Noise')
plt.grid()
plt.subplot(2, 1, 2)
plt.plot(time, pink_noise, label='Pink Noise', color='orange')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Synthetic Pink Noise (1/f Noise)')
plt.grid()
plt.tight_layout()
plt.show()
The white noise fluctuates rapidly with no memory from sample to sample. The pink noise wanders: low frequencies carry most of the power, so the series drifts on long time scales.
Applications. White noise simulates instrumental self-noise in seismic or atmospheric records. Pink noise mimics natural variability, which is dominated by low frequencies in many geophysical processes.
2.2 Spatially correlated noise (2D)¶
Geospatial noise is rarely independent from pixel to pixel. Atmospheric interference and sensor drift vary smoothly over space. A simple way to simulate this: generate a 2D field of white noise, then smooth it with a Gaussian filter. The filter width sets the correlation length.
from scipy.ndimage import gaussian_filter
ngrid = 100 # size of the grid
x = np.linspace(0, 10, ngrid)
y = np.linspace(0, 10, ngrid)
X2d, Y2d = np.meshgrid(x, y)
# 2D white noise
white_noise_2d = rng.standard_normal((ngrid, ngrid))
# Spatially correlated noise: smooth the white noise
spatially_correlated_noise = gaussian_filter(white_noise_2d, sigma=3)
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(white_noise_2d, extent=[0, 10, 0, 10], cmap='viridis')
plt.colorbar(label='Amplitude')
plt.title('2D White Noise')
plt.subplot(1, 2, 2)
plt.imshow(spatially_correlated_noise, extent=[0, 10, 0, 10], cmap='viridis')
plt.colorbar(label='Amplitude')
plt.title('2D Spatially Correlated Noise')
plt.tight_layout()
plt.show()
Applications. Spatially correlated noise simulates atmospheric distortion in satellite imagery, interpolation artifacts in gridded products, and smooth sensor errors in geophysical maps.
3. Synthetic transient events¶
We now build a time series that contains one transient event plus noise. This is the basic ingredient of a binary classification problem: does a window contain signal or only noise?
3.1 Event signal: the Ricker wavelet¶
The Ricker wavelet, also called the Mexican-hat wavelet, is a standard model for an impulsive seismic source. It is the negative second derivative of a Gaussian. scipy.signal.ricker was removed from recent scipy versions, so we define it ourselves.
import scipy.signal as sig
def ricker(t, a):
"""Ricker (Mexican-hat) wavelet.
Parameters
----------
t : array
Time axis in seconds, centered on zero.
a : float
Width parameter in seconds. The amplitude spectrum peaks near
sqrt(2) / (2 * pi * a) Hz.
Returns
-------
array
The wavelet 2/(sqrt(3a) * pi**0.25) * (1 - (t/a)**2) * exp(-t**2/(2a**2)).
"""
prefactor = 2.0 / (np.sqrt(3.0 * a) * np.pi**0.25)
return prefactor * (1.0 - (t / a) ** 2) * np.exp(-(t**2) / (2.0 * a**2))fs = 100.0 # sampling rate in Hz
twin = 50.0 # window length in seconds
t = np.linspace(0, twin, int(twin * fs))
a = 0.5 # width parameter in seconds
t_wavelet = np.arange(-2, 2, 1 / fs) # 4 seconds of support
sa = ricker(t_wavelet, a)
# place the wavelet in the middle of the time series
pad = len(t) // 2 - len(sa) // 2
s = np.concatenate((np.zeros(pad), sa, np.zeros(len(t) - pad - len(sa))))
plt.figure()
plt.plot(t, s)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid()
plt.xlim([0, 50])
plt.title('Signal: Ricker wavelet')
plt.show()
The Ricker wavelet is smooth and band-limited. Let’s plot its absolute Fourier amplitude spectrum.
from scipy.fft import fft, fftfreq, next_fast_len
# pad to a fast FFT length
Nfft = next_fast_len(len(s)) # this will be an even number
freqVec = fftfreq(Nfft, d=1 / fs)[: Nfft // 2]
Zhat = fft(s, n=Nfft)
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].plot(freqVec, np.abs(Zhat[: Nfft // 2]))
ax[0].grid()
ax[0].set_title('FFT of the signal')
ax[0].set_xlabel('Frequency in Hz')
ax[1].plot(freqVec, np.abs(Zhat[: Nfft // 2]))
ax[1].set_xscale('log')
ax[1].set_xlabel('Frequency in Hz')
ax[1].set_title('FFT of the signal in log')
ax[1].grid()
What does the event data distribution look like?
plt.hist(sa, bins=10)
plt.xlabel('Amplitude')
plt.ylabel('Counts')
plt.title('Histogram of the wavelet')
plt.show()
3.2 Gaussian noise and signal-to-noise ratio¶
We created a pure signal. Now we create a noise time series to add to it.
One caution: np.random.uniform(0, 1) draws values between 0 and 1, which have a mean of 0.5. Adding that to a signal injects a DC offset — a spurious spike at zero frequency in the spectrum. We use rng.standard_normal instead, which is zero-mean by construction.
One definition, used everywhere. We define the signal-to-noise ratio (SNR) as the peak absolute amplitude of the signal divided by the standard deviation of the noise. This is the definition built into mlgeo_synth and used by the detector experiments of Chapter 4.3. Keeping a single definition matters: a claim like “the detector fails below SNR 1” is meaningless if two chapters measure SNR differently. In code, we normalize the signal to unit peak amplitude and the noise to unit standard deviation, so that s + noise / SNR has exactly the stated SNR.
noise = rng.standard_normal(len(s))
plt.figure()
plt.plot(t, noise)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid()
plt.title('Gaussian noise (zero mean)')
plt.show()
Check the Fourier amplitude spectrum of the noise against the signal spectrum.
nhat = fft(noise, n=Nfft)
plt.plot(freqVec, np.abs(nhat[: Nfft // 2]))
plt.plot(freqVec, np.abs(Zhat[: Nfft // 2]))
plt.xscale('log')
plt.legend(['noise', 'signal'])
plt.xlabel('Frequency in Hz')
plt.ylim([0, 100])
plt.grid()
They look very different in the spectral domain. The noise spreads its energy over all frequencies; the signal concentrates its energy in a narrow band.
Now we add noise to the signal, scaled by a signal-to-noise ratio (SNR). We define SNR here as the ratio of the maximum absolute amplitude of the signal to that of the noise. First normalize both, then divide the noise by the SNR.
SNR = 100 # signal-to-noise ratio
s /= np.max(np.abs(s)) # unit peak amplitude
noise /= noise.std() # unit standard deviation, so s + noise / SNR has the stated SNR
noisy_signal = s + noise / SNR
plt.plot(t, noisy_signal)
plt.grid()
plt.title(f'Noisy signal, SNR = {SNR}')
plt.xlabel('Time in s')
3.3 Noise with a chosen color: randomizing the phase¶
Noise may have different frequency content, or color. A general recipe builds a noise time series from a chosen Fourier amplitude spectrum:
Choose the amplitude at each non-negative frequency (flat for white noise, decay for colored noise, or the spectrum of real data).
Draw a random phase at each frequency, uniform between 0 and .
Invert with
np.fft.irfft.
A real-valued time series requires a Hermitian-symmetric spectrum: the value at must be the complex conjugate of the value at . Hand-coding that symmetry is error prone. irfft takes only the non-negative frequencies and enforces the symmetry by construction, so we use it. The zero-frequency and Nyquist bins must be real, so we set their phases to zero.
n_rfreq = Nfft // 2 + 1 # number of non-negative frequency bins
phases = rng.uniform(0, 2 * np.pi, n_rfreq)
phases[0] = 0.0 # DC bin must be real
phases[-1] = 0.0 # Nyquist bin must be real (Nfft is even)
amplitude = np.ones(n_rfreq) # flat spectrum: white noise
amplitude[0] = 0.0 # no DC component
spectrum = amplitude * np.exp(1j * phases)
noise = np.fft.irfft(spectrum, n=Nfft)[: len(s)]
noise /= noise.std() # unit standard deviation
plt.plot(t, noise)
plt.title('Noise with random phase and white spectrum')
Add the new noise to the signal (Ricker wavelet), this time with a much lower SNR, and plot in the time and frequency domains.
SNR = 1
news = s + noise / SNR
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].plot(t, news)
ax[0].set_title(f'Noisy signal, SNR = {SNR}')
ax[0].set_xlabel('Time in s')
ax[0].grid()
ax[1].plot(freqVec, np.abs(fft(news, n=Nfft)[: Nfft // 2]))
ax[1].set_xscale('log')
ax[1].grid()
ax[1].set_xlabel('Frequency in Hz')
ax[1].set_title('FFT of the noisy signal in log');
Compare the data distributions of the pure signal, the noise, and their sum.
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].hist(noise, bins=20, label='noise')
ax[0].hist(s, bins=20, label='signal')
ax[0].legend()
ax[0].grid()
ax[0].set_title('Signal and noise')
ax[1].hist(news, bins=20)
ax[1].grid()
ax[1].set_title('Noisy signal');
3.4 Statistical moments¶
Calculate the statistical moments of the clean signal and the noise. Which moments discriminate between signal and noise, and how sensitive are they to the noise level?
from scipy.stats import moment
print('The first moment of the signal is:', moment(s, 1))
print('The second moment of the signal is:', moment(s, 2))
print('The third moment of the signal is:', moment(s, 3))
print('The fourth moment of the signal is:', moment(s, 4))
print('The first moment of the noise is:', moment(noise, 1))
print('The second moment of the noise is:', moment(noise, 2))
print('The third moment of the noise is:', moment(noise, 3))
print('The fourth moment of the noise is:', moment(noise, 4))The first moment of the signal is: 0.0
The second moment of the signal is: 0.013293333067181288
The third moment of the signal is: 0.006430940666682904
The fourth moment of the signal is: 0.007489819567378665
The first moment of the noise is: 0.0
The second moment of the noise is: 1.0
The third moment of the noise is: 0.005114776505715537
The fourth moment of the noise is: 3.134334832790316
The first central moment is zero by definition. The second moment (variance) depends on the normalization, so it is a weak discriminant. The fourth moment is the interesting one: a time series that is mostly zeros with one short transient has heavy tails relative to a Gaussian, so its kurtosis is large. Kurtosis is a workhorse feature for detecting impulsive events in noise, and we will use it again in the feature engineering lesson (2.11).
4. Physics-informed synthetic noise from real data¶
White and colored noise are idealizations. Real seismic noise has structure: microseism peaks, cultural noise during the day, the instrument response. To make synthetic noise realistic, we can borrow the amplitude spectrum of real noise and randomize only the phase.
We use two hours of noise recorded at broadband station UW.RATT (Rattlesnake Lake, Washington, Pacific Northwest Seismic Network) from 04:15 to 06:15 UTC on 29 July 2021, just before the Mww 8.2 Chignik, Alaska, earthquake (Mww: moment magnitude from the W phase). It is the vertical channel HHZ at 100 samples per second, in raw digitizer counts, the same station and day as sections 2.8 and 2.9. The course copy in snapshots/ was downloaded from the EarthScope FDSN web services (FDSN: International Federation of Digital Seismograph Networks). The next cell recomputes each file’s fingerprint (SHA-256, Secure Hash Algorithm) and compares it with the provenance file; a file that is missing is downloaded from the book repository first. Section 5 also uses the following two hours, which contain the earthquake.
import hashlib
import json
import urllib.request
from pathlib import Path
import obspySNAP = Path("snapshots") # course copies, read only
BOOK_URL = "https://raw.githubusercontent.com/geo-smart/mlgeo-book/main/book/Chapter2-DataManipulation/snapshots/"
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)
print("downloaded", name, "from the book repository")
return SNAP / name
PROV = json.loads(course_file("ratt_chignik_2021-07-29.provenance.json").read_text())
NOISE_FILE = "ratt_chignik_2021-07-29_UW.RATT.HHZ_0415-0615.mseed" # 04:15 to 06:15 UTC, before the earthquake
QUAKE_FILE = "ratt_chignik_2021-07-29_UW.RATT.HHZ_0615-0815.mseed" # 06:15 to 08:15 UTC, used in section 5
for name in (NOISE_FILE, QUAKE_FILE):
sha = hashlib.sha256(course_file(name).read_bytes()).hexdigest()
print("matches" if sha == PROV["files"][name]["sha256"] else "DIFFERS", sha[:16] + "...", name)
N = obspy.read(str(SNAP / NOISE_FILE))
N.merge()
N.detrend(type='linear')
N[0].taper(max_percentage=0.05)
print(N)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
1 Trace(s) in Stream:
UW.RATT..HHZ | 2021-07-29T04:15:00.000000Z - 2021-07-29T06:14:59.990000Z | 100.0 Hz, 720000 samples
4.1 Spectrum-matched noise¶
We now generate synthetic noise whose amplitude spectrum matches the real RATT noise. The course package mlgeo_synth provides spectrum_matched_noise, which keeps the amplitude spectrum of a reference record and draws random phases. It uses rfft/irfft, so the Hermitian symmetry needed for a real-valued output is guaranteed by construction. Run help(mlgeo_synth.spectrum_matched_noise) to see the signature.
import mlgeo_synth
real_noise = N[0].data.astype(float)
real_noise -= real_noise.mean()
fs_real = N[0].stats.sampling_rate
synthetic_noise = mlgeo_synth.spectrum_matched_noise(real_noise, seed=42)
print(real_noise.shape, synthetic_noise.shape)(720000,) (720000,)
Compare the two in the time domain and in the frequency domain. The time series should look different — the phases are different, so the waveforms line up nowhere. The amplitude spectra should overlap exactly, because the synthetic spectrum is a copy of the real one.
t_real = np.arange(len(real_noise)) / fs_real
fig, ax = plt.subplots(2, 1, figsize=(10, 6), sharex=True)
ax[0].plot(t_real, real_noise, lw=0.5)
ax[0].set_title('Real noise (UW.RATT.HHZ)')
ax[0].set_ylabel('Counts')
ax[0].grid()
ax[1].plot(t_real, synthetic_noise, lw=0.5, color='orange')
ax[1].set_title('Spectrum-matched synthetic noise (random phase)')
ax[1].set_xlabel('Time in s')
ax[1].set_ylabel('Counts')
ax[1].grid()
plt.tight_layout()
plt.show()
Nfft_real = next_fast_len(len(real_noise))
freq_real = np.fft.rfftfreq(Nfft_real, d=1 / fs_real)
spec_real = np.abs(np.fft.rfft(real_noise, n=Nfft_real))
spec_synth = np.abs(np.fft.rfft(synthetic_noise, n=Nfft_real))
plt.figure(figsize=(10, 5))
plt.loglog(freq_real[1:], spec_real[1:], lw=2, label='real noise')
plt.loglog(freq_real[1:], spec_synth[1:], lw=0.7, label='synthetic noise')
plt.xlabel('Frequency in Hz')
plt.ylabel('Fourier amplitude')
plt.title('Amplitude spectra: real vs spectrum-matched synthetic noise')
plt.legend()
plt.grid()
plt.show()
The two spectra lie on top of each other: the amplitude information is identical. The phase information is not. We can check that directly.
phase_real = np.angle(np.fft.rfft(real_noise, n=Nfft_real))
phase_synth = np.angle(np.fft.rfft(synthetic_noise, n=Nfft_real))
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
ax[0].plot(freq_real[1:200], phase_real[1:200], '.', label='real')
ax[0].plot(freq_real[1:200], phase_synth[1:200], '.', label='synthetic')
ax[0].set_xlabel('Frequency in Hz')
ax[0].set_ylabel('Phase [rad]')
ax[0].set_title('Phase spectra (first 200 bins)')
ax[0].legend()
ax[0].grid()
ax[1].hist(phase_synth, bins=30)
ax[1].set_xlabel('Phase [rad]')
ax[1].set_ylabel('Counts')
ax[1].set_title('Synthetic phases: uniform')
ax[1].grid()
plt.tight_layout()
plt.show()
4.2 Augmenting an event with realistic noise at varying SNR¶
Now we combine the two ideas: a synthetic event (the Ricker wavelet) plus spectrum-matched realistic noise, at a range of SNR levels. This is a standard data augmentation strategy: one clean event template yields many training samples with controlled noise levels.
spectrum_matched_noise accepts an output length n, so we can draw a noise realization of the same length as the signal window.
matched_noise = mlgeo_synth.spectrum_matched_noise(real_noise, n=len(s), seed=7)
matched_noise /= matched_noise.std() # unit standard deviation, per our SNR definition
snr_levels = [np.power(10, i / 5) for i in range(10)]
fig, ax = plt.subplots(10, 1, figsize=(10, 20), sharex=True)
for i, snr in enumerate(snr_levels):
ax[i].plot(t, s + matched_noise / snr)
ax[i].set_title(f'SNR = {snr:.2f}')
ax[i].grid()
ax[-1].set_xlabel('Time in s')
plt.tight_layout()
plt.show()
At low SNR the event disappears into the noise. Somewhere along this ladder, any detector — human or algorithmic — starts to fail. Finding that failure point is exactly what we do next, with the oldest detector in the seismological toolbox.
4.3 The course synthetic-data generator¶
The mlgeo_synth package used above is the course’s synthetic-data generator. Besides spectrum_matched_noise, it can generate full synthetic seismograms with a P wave, an S wave, a coda, and colored noise, plus labeled datasets for classification exercises. We will rely on it in later chapters when we need data with known ground truth.
t_syn, trace, meta = mlgeo_synth.synthetic_seismogram(
duration_s=30.0, fs=100.0, magnitude=3.0, distance_km=30.0, snr=5.0, seed=3)
plt.figure(figsize=(10, 4))
plt.plot(t_syn, trace, lw=0.7)
plt.xlabel('Time in s')
plt.ylabel('Amplitude')
plt.title('mlgeo_synth.synthetic_seismogram: M3.0 at 30 km, SNR 5')
plt.grid()
plt.show()
print(meta)
{'t_p': 10.0, 't_s': 13.571428571428571, 'peak_amplitude': np.float64(0.48413257576129515), 'snr': 5.0}
4.4 Worked example: the STA/LTA detection floor¶
Before any neural network touches traces like these (Chapter 4.3 trains one), we owe them a classical baseline. The STA/LTA detector (short-term average over long-term average; Allen, 1978) slides two windows over the trace: a short window (here 1 s) tracks the instantaneous signal level, a long window (10 s) tracks the background, and their ratio spikes when a transient arrives. It has run in observatory triggering pipelines for decades, it has nothing to train, and any learned detector must beat it to justify its complexity.
A detector needs a threshold, and the threshold must come from noise alone. We generate 200 noise-only windows, record the peak STA/LTA of each, and set the threshold at the 99th percentile of that distribution: a 1% false-alarm rate by construction, before we ever look at a signal. Then we run the detector on s + noise / SNR across the SNR ladder np.logspace(-1, 2, 20), with 60 fresh noise realizations per SNR, and count the fraction of trials in which the peak STA/LTA crosses the threshold. Each point is 60 Bernoulli trials, so we attach a binomial (Wilson) interval to it.
from obspy.signal.trigger import classic_sta_lta
nsta, nlta = int(1 * fs), int(10 * fs) # 1 s short window, 10 s long window
def peak_stalta(trace, nsta=nsta, nlta=nlta):
"""Peak STA/LTA of a trace, ignoring the first LTA window (not yet filled)."""
cft = classic_sta_lta(trace, nsta, nlta)
return cft[nlta:].max()
# Threshold choice: peak STA/LTA of 200 windows that contain no signal at all
n_noise_trials = 200
noise_peaks = np.array([
peak_stalta(mlgeo_synth.spectrum_matched_noise(real_noise, n=len(s), seed=50_000 + k))
for k in range(n_noise_trials)])
threshold = np.quantile(noise_peaks, 0.99)
print(f"noise-only peak STA/LTA: median {np.median(noise_peaks):.2f}, "
f"99th percentile {threshold:.2f}")noise-only peak STA/LTA: median 4.34, 99th percentile 6.09
def wilson_interval(k, n, z=1.0):
"""Wilson score interval for a binomial proportion (z=1: roughly 68% coverage)."""
p = k / n
denom = 1 + z**2 / n
center = (p + z**2 / (2 * n)) / denom
half = z * np.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denom
return center - half, center + half
snrs_ex = np.logspace(-1, 2, 20)
n_trials = 60
detect_prob_stalta = np.zeros(len(snrs_ex))
err_lo, err_hi = np.zeros(len(snrs_ex)), np.zeros(len(snrs_ex))
for i, snr in enumerate(snrs_ex):
hits = 0
for k in range(n_trials):
noise_k = mlgeo_synth.spectrum_matched_noise(real_noise, n=len(s), seed=1000 * i + k)
noise_k /= noise_k.std() # unit noise std; s has unit peak, so the SNR is exact
hits += peak_stalta(s + noise_k / snr) >= threshold
detect_prob_stalta[i] = hits / n_trials
lo, hi = wilson_interval(hits, n_trials)
err_lo[i], err_hi[i] = detect_prob_stalta[i] - lo, hi - detect_prob_stalta[i]
snr50 = np.interp(0.5, detect_prob_stalta, snrs_ex)
for snr, dp in zip(snrs_ex, detect_prob_stalta):
print(f"SNR {snr:6.2f}: detection probability {dp:.2f}")
print(f"detection probability crosses 50% near SNR {snr50:.2f}")
fig, ax = plt.subplots(1, 2, figsize=(11, 4))
ax[0].hist(noise_peaks, bins=30, color='tab:gray')
ax[0].axvline(threshold, color='tab:red', ls='--',
label=f'threshold = {threshold:.2f} (99th pct)')
ax[0].set_xlabel('Peak STA/LTA of noise-only windows')
ax[0].set_ylabel('Count')
ax[0].set_title('Threshold choice from noise alone')
ax[0].legend()
ax[1].errorbar(snrs_ex, detect_prob_stalta, yerr=[err_lo, err_hi], marker='o',
capsize=3, label=f'STA/LTA ({n_trials} trials per SNR)')
ax[1].axvline(snr50, color='tab:red', ls=':', label=f'50% crossing, SNR = {snr50:.2f}')
ax[1].set_xscale('log')
ax[1].set_xlabel('SNR (peak signal amplitude / noise standard deviation)')
ax[1].set_ylabel('Detection probability')
ax[1].set_title('STA/LTA detection floor')
ax[1].grid(alpha=0.3, which='both')
ax[1].legend(loc='lower right')
fig.tight_layout()SNR 0.10: detection probability 0.02
SNR 0.14: detection probability 0.02
SNR 0.21: detection probability 0.02
SNR 0.30: detection probability 0.02
SNR 0.43: detection probability 0.05
SNR 0.62: detection probability 0.00
SNR 0.89: detection probability 0.02
SNR 1.27: detection probability 0.03
SNR 1.83: detection probability 0.00
SNR 2.64: detection probability 0.07
SNR 3.79: detection probability 0.22
SNR 5.46: detection probability 0.62
SNR 7.85: detection probability 0.85
SNR 11.29: detection probability 0.98
SNR 16.24: detection probability 1.00
SNR 23.36: detection probability 1.00
SNR 33.60: detection probability 1.00
SNR 48.33: detection probability 1.00
SNR 69.52: detection probability 1.00
SNR 100.00: detection probability 1.00
detection probability crosses 50% near SNR 4.97

The left panel is the threshold logic: pure noise produces a distribution of peak STA/LTA values (median about 4.3 for this microseism-rich noise), and placing the threshold at its 99th percentile, 6.1, fixes the false-alarm rate at 1% before any signal enters the experiment. The right panel is the detection floor: the curve sits at the designed 1-2% false-alarm level up to SNR of about 2.6, climbs through its 50% crossing near SNR 5, and saturates at 1 above SNR of about 16 — a transition under a decade wide. The takeaway: with its false-alarm rate pinned at 1%, this classical detector needs a peak amplitude of roughly five noise standard deviations before it triggers reliably on this event. That number is the baseline any learned detector has to beat; in Chapter 4.3 we overlay this curve on the detection floor of a trained CNN, measured the same way.
5. Build a synthetic version of your own data¶
In-class team activity, about 25 minutes. Run the whole notebook first (Run All, about 10 seconds): section 5 uses rng, ricker, real_noise, fs_real and SNAP from sections 1 to 4.
What counts as noise depends on the question. The ocean microseism that section 4 treats as noise is the signal of ambient-noise imaging, which correlates it between stations to map the crust. Traffic is noise for an earthquake detector and a measure of human activity during the 2020 lockdowns (Lecocq and others, 2020, Science). Ocean tide loading is noise for a GNSS (Global Navigation Satellite System) station tracking plate motion. Water vapour delay is noise for InSAR (interferometric synthetic aperture radar) ground deformation and signal for a weather model. Starspots are noise for a planet hunter and signal for a stellar physicist. A wrong label in a catalog is noise in the class column. In each case the noise is a real contribution, physical or human, that overlaps the signal in time, frequency, space or class, so a filter cannot simply remove it.
A synthetic version of your data makes the separation explicit: you decide what is signal, you write down its parameters, and you measure how each kind of noise changes what you would conclude.
Recipe. Write each ingredient down before you code it.
A signal of interest with known parameters, kept in a separate variable (
truth): event times and amplitudes, a drydown time scale, a trend in °C per decade, a transit depth, the true class of each sample.Realistic noise: white (independent draws), colored (an autoregressive process, in which each value keeps a fraction of the previous one, or a power-law spectrum ), or spectrum-matched to a real record as in section 4.1.
One nuisance signal from another real source that overlaps yours: a distant earthquake under a volcano record, soil temperature acting on a soil moisture probe, El Niño in a temperature field, starspots in a light curve, cultural noise in a catalog.
One instrument problem from lecture 8: a gap, a step offset, a clock or time-convention error.
The distribution of the noise values: Gaussian, or heavy-tailed (large values more frequent than a Gaussian allows).
Timing. 3 min: pick the template (sections 5.2 to 5.6) closest to your team’s data and read it. 10 min: change the noise color, level or distribution and run the measurement in its Your-turn cell. 7 min: compare with the truth and write one number per setting in your team notes. 5 min: the reflection in section 5.7.
5.1 Color and distribution are two different properties¶
A noise record has two independent properties. Its spectrum, or color, says how values are correlated in time or space. White noise has equal power at all frequencies. An autoregressive process of order 1, AR(1), with , is flat (white) at long periods and falls off as about above a corner frequency near (0.017 cycles per sample for ); climate papers call it red noise. A power law has no corner: is pink or flicker noise, common in GNSS position series and climate records, and is Brownian noise, a random walk (called red in physics).
Its distribution says how large single values can be. A Gaussian is what you get when many small independent contributions add up; its tails fall as . Real records often hold more large values: transients, glitches, passing trucks, gusts. A Student t distribution with 3 degrees of freedom has power-law tails: the chance of exceeding falls as . Some geoscience quantities follow a power law above a lower cutoff, such as earthquake energies (the Gutenberg-Richter law), landslide areas and fault lengths.
The next cell defines one generator, make_noise, used by every template, and a plotting helper show. In make_noise, dist sets the distribution of the independent draws before coloring. Coloring filters the draws, and a filter output is a weighted sum of many draws, so a colored series is closer to Gaussian than its draws (central limit theorem). To keep heavy tails in colored noise, add the spikes after coloring. The cell after it compares four colors and four distributions, among them the real RATT noise in the 1 to 20 Hz band and its random-phase twin from section 4.1. Look for one thing: random phases copy the spectrum of a record but not the distribution of its values, which comes out Gaussian whatever the reference.
import pandas as pd
from scipy.signal import lfilter, welch
from scipy.stats import kurtosis, norm
def make_noise(n, color="white", dist="gaussian", rng=rng, phi=0.9):
"""Zero-mean noise with unit standard deviation (white: in theory; colored: in the sample).
color: "white"; "ar1" (each value is phi times the previous one plus a new draw);
or a number beta, for a power spectrum proportional to 1/f**beta.
dist: distribution of the independent draws: "gaussian", "student-t" (3 degrees
of freedom, power-law tails) or "laplace" (exponential tails). It applies to the
draws before coloring; coloring sums many draws, so colored noise comes out
closer to Gaussian. For heavy-tailed colored noise, add spikes after coloring.
"""
draws = {"gaussian": lambda: rng.standard_normal(n),
"student-t": lambda: rng.standard_t(3, n) / np.sqrt(3.0), # variance of t with 3 dof is 3
"laplace": lambda: rng.laplace(size=n) / np.sqrt(2.0)}[dist]()
if color == "white":
return draws
if color == "ar1":
x = lfilter([1.0], [1.0, -phi], draws)
else: # power law: reshape the spectrum of the draws and keep their phases
f = np.fft.rfftfreq(n)
gain = np.zeros_like(f)
gain[1:] = f[1:] ** (-color / 2)
x = np.fft.irfft(np.fft.rfft(draws) * gain, n=n)
return (x - x.mean()) / x.std()
def show(t, observed, clean, marks=(), title="", xlabel="", ylabel=""):
"""Plot a synthetic record over its known signal, with dotted lines at known times."""
fig, ax = plt.subplots(figsize=(10, 3))
ax.plot(t, observed, color="0.45", lw=0.6, label="synthetic record")
ax.plot(t, clean, color="C3", lw=1.0, label="signal (truth)")
for m in marks:
ax.axvline(m, color="C0", lw=0.8, ls=":")
ax.set(title=title, xlabel=xlabel, ylabel=ylabel)
ax.legend(loc="upper right", fontsize=8)
return axdemo_rng = np.random.default_rng(10)
n_demo = 2**16
fig, ax = plt.subplots(1, 3, figsize=(13, 3.8))
for k, (name, c) in enumerate({"white": "white", "AR(1), phi = 0.95": "ar1",
"power law, beta = 1": 1.0, "power law, beta = 2": 2.0}.items()):
ax[0].plot(make_noise(1000, c, rng=demo_rng, phi=0.95) - 6 * k, lw=0.6, label=name)
x = make_noise(n_demo, c, rng=demo_rng, phi=0.95)
f, p = welch(x, nperseg=4096)
ax[1].loglog(f[1:], p[1:], label=name)
ax[0].set(title="Color: four series, offset", xlabel="sample", yticks=[])
ax[1].set(title="Power spectral density", xlabel="frequency (cycles per sample)")
ax[1].legend(fontsize=8)
band = sig.butter(4, [1, 20], "bandpass", fs=fs_real, output="sos") # 1 to 20 Hz, used again in section 5.2
ratt_band = sig.sosfiltfilt(band, real_noise)[36_000:-36_000] # drop the tapered first and last 6 minutes
values = {"Gaussian": make_noise(n_demo, rng=demo_rng),
"Student t, 3 degrees of freedom": make_noise(n_demo, dist="student-t", rng=demo_rng),
"RATT noise, 1 to 20 Hz": ratt_band / ratt_band.std(),
"RATT, random-phase twin": mlgeo_synth.spectrum_matched_noise(ratt_band, seed=1) / ratt_band.std()}
a = np.logspace(-0.5, 1.5, 80)
for name, v in values.items():
v_abs = np.sort(np.abs(v))
surv = 1 - np.searchsorted(v_abs, a) / len(v_abs) # fraction of values with |value| > a
ax[2].loglog(a, np.where(surv > 0, surv, np.nan), label=name)
print(f"{name}: excess kurtosis {round(kurtosis(v), 1) + 0.0}")
ax[2].loglog(a, 2 * norm.sf(a), "k:", lw=1, label="Gaussian, exact")
ax[2].set(title="Distribution: chance that |value| > a", xlabel="a (standard deviations)", ylim=(1e-6, 1.5))
ax[2].legend(fontsize=7, loc="lower left")
print("(Student t with 3 degrees of freedom has infinite kurtosis in theory, so its sample value jumps between draws.)")
fig.tight_layout()
print(f"Gaussian: |value| > 5 standard deviations once in {1 / (2 * norm.sf(5)):,.0f} samples")
print(f"RATT 1 to 20 Hz: {np.sum(np.abs(values['RATT noise, 1 to 20 Hz']) > 5):,} "
f"of {len(ratt_band):,} samples beyond 5 standard deviations")Gaussian: excess kurtosis 0.0
Student t, 3 degrees of freedom: excess kurtosis 18335.5
RATT noise, 1 to 20 Hz: excess kurtosis 3.7
RATT, random-phase twin: excess kurtosis 0.0
(Student t with 3 degrees of freedom has infinite kurtosis in theory, so its sample value jumps between draws.)
Gaussian: |value| > 5 standard deviations once in 1,744,278 samples
RATT 1 to 20 Hz: 1,030 of 648,000 samples beyond 5 standard deviations

On a log-log plot a power-law tail is a straight line and a Gaussian tail drops off a cliff. The real RATT noise in the 1 to 20 Hz band, where cultural and wind noise live, has more large values than a Gaussian; its random-phase twin does not. A detector tuned on the twin will see fewer false alarms than it meets on the real record. Section 5.2 measures that.
5.2 Template A: a volcano or local seismic record (1D, 100 samples per second)¶
Signal: four impulsive events, Ricker pulses peaking near 4.5 Hz, like small volcano-tectonic earthquakes. The truth is their centre times and peak amplitudes.
Noise:
noise="ratt"is a random minute of the real RATT noise in the 1 to 20 Hz band with randomized phases (section 4.1);noise="real"is the real minute itself;noise="white","ar1"or a number callsmake_noise, withdistfor the distribution.noise_levelis the noise standard deviation in units of the largest event’s peak, the inverse of the SNR of section 3.2.Nuisance: the P-wave coda of the Chignik earthquake at RATT, 06:21 to 06:22 UTC, in the same band. For a volcano observatory in Washington, a great earthquake in Alaska is noise.
Instrument problem: a 2 s telemetry gap filled with zeros (lecture 8).
quake = obspy.read(str(SNAP / QUAKE_FILE))[0].data.astype(float)
p_coda = sig.sosfiltfilt(band, quake - quake.mean())[36_000:42_000] # Chignik P coda at RATT, 06:21 to 06:22 UTC
def make_seismic(noise_level=0.2, noise="ratt", dist="gaussian", nuisance_level=0.5, gap=(30.0, 32.0), seed=1):
r = np.random.default_rng(seed)
tv = np.arange(6000) / 100.0 # 60 s at 100 samples per second
truth = {"centres_s": np.array([8.0, 23.5, 41.0, 52.0]), "peaks": np.array([1.0, 0.5, 0.3, 0.8])}
clean = sum(a0 * ricker(tv - t0, 0.05) / ricker(0.0, 0.05) for t0, a0 in zip(truth["centres_s"], truth["peaks"]))
k0 = r.integers(len(ratt_band) - 6000)
minute = ratt_band[k0:k0 + 6000] # a random minute of real noise, in band
if noise == "real":
nz = minute
elif noise == "ratt":
nz = mlgeo_synth.spectrum_matched_noise(minute, seed=seed) # same spectrum, random phases
else:
nz = make_noise(6000, noise, dist, rng=r)
rec = clean + noise_level * nz / nz.std() + nuisance_level * p_coda / np.abs(p_coda).max()
if gap is not None:
rec[(tv >= gap[0]) & (tv < gap[1])] = 0.0 # telemetry gap filled with zeros
return tv, rec, clean, truth
tv, rec_seis, clean_seis, truth_seis = make_seismic()
show(tv, rec_seis, clean_seis, truth_seis["centres_s"], "Template A: four events, RATT-like noise, Chignik P coda, 2 s gap",
"time (s)", "amplitude (largest event = 1)");
Your turn (team A): detection rate against the known event times. The cell runs an STA/LTA detector (short 0.2 s, long 3 s, threshold 4) on synthetic records. Fill in detected: the fraction of true events whose STA/LTA reaches the threshold within 1 s of the event centre. The settings start without the Chignik coda and without the gap, and each setting is averaged over 10 synthetic minutes (seeds 0 to 9). Then change the list: noise color, level, distribution, noise="real", add the nuisance (nuisance_level=0.5) or the gap (gap=(30.0, 32.0)), and compare detection rates and false triggers per minute.
Hint: near[:, j] selects the samples within 1 s of event j; an event is detected if (cft[near[:, j]] >= thr).any(). Average that over the events. What to look for: does the real minute give more false triggers than its random-phase twin, and what does the zero-filled gap do to the STA/LTA ratio just after it ends? A worked solution follows the code cell (hidden; click ⋯ to open).
from obspy.signal.trigger import classic_sta_lta, trigger_onset
def score_seismic(rec, tv, truth, thr=4.0):
cft = classic_sta_lta(rec, 20, 300) # 0.2 s short window, 3 s long window
near = np.abs(tv[:, None] - truth["centres_s"][None, :]) <= 1.0 # samples within 1 s of each true centre
# --- your code
detected = None # fraction of the true events detected, one number between 0 and 1
# --- end
false = sum(not near[on].any() for on, _ in trigger_onset(cft, thr, thr / 2)) # triggers far from every event
return detected, false
settings = [dict(nuisance_level=0.0, gap=None), # RATT spectrum, random phases
dict(noise="real", nuisance_level=0.0, gap=None), # the real RATT minutes
dict(noise="white", dist="student-t", nuisance_level=0.0, gap=None)] # white, heavy-tailed
for kw in settings:
det_k, false_k = [], []
for s in range(10): # 10 synthetic minutes per setting
tv_k, rec_k, _, truth_k = make_seismic(seed=s, **kw)
d_k, f_k = score_seismic(rec_k, tv_k, truth_k)
det_k.append(np.nan if d_k is None else d_k)
false_k.append(f_k)
print(kw, "-> detected:", "not answered yet" if np.isnan(det_k).all() else round(float(np.mean(det_k)), 2),
"| false triggers per minute:", round(float(np.mean(false_k)), 2))
tv_k, rec_k, _, truth_k = make_seismic(noise_level=0.01, nuisance_level=0.0, gap=None)
check = score_seismic(rec_k, tv_k, truth_k)
print("self-check, almost no noise:", "not answered yet" if check[0] is None
else ("correct" if check == (1.0, 0) else f"{check}, expected (1.0, 0)")){'nuisance_level': 0.0, 'gap': None} -> detected: not answered yet | false triggers per minute: 0.5
{'noise': 'real', 'nuisance_level': 0.0, 'gap': None} -> detected: not answered yet | false triggers per minute: 1.1
{'noise': 'white', 'dist': 'student-t', 'nuisance_level': 0.0, 'gap': None} -> detected: not answered yet | false triggers per minute: 4.4
self-check, almost no noise: not answered yet
Notebook Cell
# Worked solution, team A. Names end in _sol so that running this cell keeps your own results.
def score_seismic_sol(rec, tv, truth, thr=4.0):
cft = classic_sta_lta(rec, 20, 300)
near = np.abs(tv[:, None] - truth["centres_s"][None, :]) <= 1.0
detected = np.mean([(cft[near[:, j]] >= thr).any() for j in range(near.shape[1])])
false = sum(not near[on].any() for on, _ in trigger_onset(cft, thr, thr / 2))
return detected, false
base_sol = dict(noise="ratt", nuisance_level=0.0, gap=None) # change one ingredient at a time from this
settings_sol = {"1 RATT spectrum, random phase": {},
"2 real RATT minute": dict(noise="real"),
"3 white, Student t": dict(noise="white", dist="student-t"),
"4 + Chignik P coda": dict(nuisance_level=0.5),
"5 + 2 s zero-filled gap": dict(gap=(30.0, 32.0))}
rows_sol = []
for name, change in settings_sol.items():
kw = {**base_sol, **change}
for level in [0.05, 0.1, 0.2]:
scores = []
for s in range(20):
tv_s, rec_s, _, truth_s = make_seismic(noise_level=level, seed=s, **kw)
scores.append(score_seismic_sol(rec_s, tv_s, truth_s))
scores = np.array(scores)
rows_sol.append({"noise": name, "noise level": level, "detection rate": scores[:, 0].mean(),
"false triggers per minute": scores[:, 1].mean()})
table_seis_sol = pd.DataFrame(rows_sol).pivot(index="noise", columns="noise level")
print("20 synthetic minutes per cell")
print(table_seis_sol.round(2).to_string())20 synthetic minutes per cell
detection rate false triggers per minute
noise level 0.05 0.10 0.20 0.05 0.10 0.20
noise
1 RATT spectrum, random phase 1.00 0.82 0.50 0.35 0.35 0.35
2 real RATT minute 1.00 0.89 0.45 0.75 0.80 0.80
3 white, Student t 0.99 0.85 0.57 4.25 4.60 4.65
4 + Chignik P coda 0.74 0.60 0.39 5.20 1.90 0.20
5 + 2 s zero-filled gap 1.00 0.82 0.50 1.75 1.75 1.75
5.3 Template B: daily soil moisture (1D, one value per day)¶
Signal: a bucket. Each rainy day adds water in proportion to the rain; between rains the water above a residual content drains exponentially with a drydown time scale. The truth is that time scale (12 days), the residual and the gain. Rain falls more often in winter than in summer, as east of the Cascades, so the bucket makes its own seasonal cycle.
Noise: probe noise, white or AR(1), Gaussian or heavy-tailed.
Nuisance: dielectric probes read differently in warm and cold soil;
temp_coefadds a soil-temperature term (m³/m³ per °C) that follows the seasons, as the water content does.Instrument problem: days with frozen soil are left blank, as monitoring networks flag them, because the probe cannot measure liquid water in frozen soil.
def make_soil(noise_sd=0.01, color="white", dist="gaussian", temp_coef=0.001, frozen_gap=True, seed=2):
r = np.random.default_rng(seed)
days = pd.date_range("2018-01-01", periods=3 * 365, freq="D")
season = np.cos(2 * np.pi * (days.dayofyear.to_numpy() - 15) / 365.25) # +1 in mid-January
truth = {"tau_days": 12.0, "residual": 0.08, "gain_per_mm": 0.004} # days, m3/m3, m3/m3 per mm
rain = np.where(r.random(len(days)) < 0.35 + 0.25 * season, r.exponential(4.0, len(days)), 0.0) # mm per day
clean = np.full(len(days), 0.25)
for i in range(1, len(days)):
clean[i] = min(0.45, truth["residual"] + (clean[i - 1] - truth["residual"]) * np.exp(-1 / truth["tau_days"])
+ truth["gain_per_mm"] * rain[i])
temp = 9.0 - 12.0 * season + 3.0 * make_noise(len(days), "ar1", rng=r, phi=0.7) # soil temperature, deg C
obs = clean + temp_coef * (temp - temp.mean()) + noise_sd * make_noise(len(days), color, dist, rng=r)
if frozen_gap:
obs[temp < 0] = np.nan # frozen soil: left blank
return days, obs, clean, rain, truth
days, sm_obs, sm_clean, rain, truth_soil = make_soil()
ax = show(days, sm_obs, sm_clean, (), "Template B: bucket soil moisture, probe noise, temperature effect, frozen days blank",
"", "soil moisture (m³/m³)")
ax_rain = ax.twinx()
ax_rain.bar(days, rain, width=1, color="C0", alpha=0.5)
ax_rain.set(ylim=(80, 0), ylabel="rain (mm/day), from the top");
Your turn (team B): the drydown time scale and its error. On a day without rain, the excess water above the residual shrinks by the factor . Fill in tau_hat from the median of that ratio over all such pairs of days, then change settings: noise level, color="ar1", dist="student-t", temp_coef, and compare tau_hat with the truth, 12 days.
Hint: ratio = excess[1:][pairs] / excess[:-1][pairs], then tau_hat = -1 / np.log(np.median(ratio)). What to look for: which ingredient biases the estimate, and which only spreads it? A worked solution follows the code cell (hidden).
def drydown_tau(obs, rain, residual=0.08, min_excess=0.03):
excess = obs - residual
pairs = (rain[1:] == 0) & (excess[:-1] > min_excess) & (excess[1:] > 0) # NaN compares False: blanks drop out
# --- your code
tau_hat = None # drydown time scale in days, one number
# --- end
return tau_hat
settings = [dict(noise_sd=0.0, temp_coef=0.0), dict(noise_sd=0.005), dict(noise_sd=0.005, color="ar1")]
for kw in settings:
_, obs_k, _, rain_k, truth_k = make_soil(**kw)
tau_k = drydown_tau(obs_k, rain_k)
print(kw, "-> tau_hat:", tau_k if tau_k is None else f"{tau_k:.2f}", "days; truth:", truth_k["tau_days"])
check = drydown_tau(*make_soil(noise_sd=0.0, temp_coef=0.0)[1::2]) # obs and rain
print("self-check, no noise and no temperature effect:", "not answered yet" if check is None
else ("correct" if abs(check - 12.0) < 1e-6 else f"{check:.3f}, expected 12.000")){'noise_sd': 0.0, 'temp_coef': 0.0} -> tau_hat: None days; truth: 12.0
{'noise_sd': 0.005} -> tau_hat: None days; truth: 12.0
{'noise_sd': 0.005, 'color': 'ar1'} -> tau_hat: None days; truth: 12.0
self-check, no noise and no temperature effect: not answered yet
Notebook Cell
# Worked solution, team B. Names end in _sol so that running this cell keeps your own results.
def drydown_tau_sol(obs, rain, residual=0.08, min_excess=0.03):
excess = obs - residual
pairs = (rain[1:] == 0) & (excess[:-1] > min_excess) & (excess[1:] > 0)
return -1 / np.log(np.median(excess[1:][pairs] / excess[:-1][pairs]))
rows_sol = []
for label, kw in {"white, Gaussian": dict(), "AR(1), phi = 0.9": dict(color="ar1"),
"white, Student t": dict(dist="student-t")}.items():
for temp_coef in [0.0, 0.001]:
for sd in [0.0, 0.002, 0.005, 0.01]:
taus = [drydown_tau_sol(*make_soil(noise_sd=sd, color=kw.get("color", "white"), dist=kw.get("dist", "gaussian"),
temp_coef=temp_coef, seed=s)[1::2]) for s in range(20)]
rows_sol.append({"noise": label, "temp_coef": temp_coef, "noise_sd": sd,
"tau_hat mean": np.mean(taus), "tau_hat spread": np.std(taus)})
table_soil_sol = pd.DataFrame(rows_sol).pivot(index=["noise", "temp_coef"], columns="noise_sd", values="tau_hat mean")
print("mean tau_hat (days) over 20 synthetic records; truth 12 days")
print(table_soil_sol.round(1).to_string())mean tau_hat (days) over 20 synthetic records; truth 12 days
noise_sd 0.000 0.002 0.005 0.010
noise temp_coef
AR(1), phi = 0.9 0.000 12.0 12.0 12.0 11.9
0.001 12.6 12.6 12.7 12.6
white, Gaussian 0.000 12.0 11.8 10.9 8.9
0.001 12.6 12.3 11.4 9.1
white, Student t 0.000 12.0 11.9 11.5 10.3
0.001 12.6 12.5 12.1 10.8
5.4 Template C: a monthly gridded temperature field (2D in space, plus time)¶
Signal: 30 years of monthly surface temperature on a 5° by 7.5° grid from 60° S to 75° N: a warming trend that grows toward the poles (the truth is its map, in °C per decade) and a seasonal cycle that grows with latitude and has opposite sign in the two hemispheres.
Noise: weather anomalies, spatially correlated (white noise smoothed over
corr_cellsgrid cells, as in section 2.2) and persistent from month to month (AR(1) with coefficientphi).Nuisance: an El Niño-like pattern, warm in the eastern equatorial Pacific, driven by an irregular index with periods of 44 and 63 months (3.7 and 5.3 years).
Instrument problem: a step offset of
step°C from January 2006 in one region (35° N to 70° N, 0° E to 40° E), as after a change of instruments or of station network; lecture 8 showed an antenna offset on Mount St. Helens.
from scipy.ndimage import gaussian_filter
lat, lon = np.arange(-60, 76, 5.0), np.arange(0, 360, 7.5)
months = np.arange(360) # month 0 is January 1991
def make_field(noise_sd=0.8, phi=0.5, corr_cells=2.0, enso=0.6, step=0.5, seed=3):
r = np.random.default_rng(seed)
truth = {"trend_c_per_decade": np.repeat((0.15 + 0.35 * (lat / 75) ** 2)[:, None], len(lon), axis=1)}
amp = (2 + 12 * np.abs(np.sin(np.radians(lat)))) * np.sign(lat) # warmest in July north, January south
seasonal = -amp[:, None] * np.cos(2 * np.pi * months / 12)[:, None, None]
clean = truth["trend_c_per_decade"] * months[:, None, None] / 120 + seasonal
e = gaussian_filter(r.standard_normal(clean.shape), (0, corr_cells, corr_cells), mode=("nearest", "nearest", "wrap"))
e = lfilter([1.0], [1.0, -phi], e / e.std(), axis=0) * np.sqrt(1 - phi**2) # persistence from month to month
index = np.sin(2 * np.pi * months / 44) + 0.7 * np.sin(2 * np.pi * months / 63 + 1.0)
pattern = np.exp(-(lat[:, None] / 10) ** 2 - ((lon[None, :] - 240) / 40) ** 2) # eastern equatorial Pacific
region = ((lat >= 35) & (lat <= 70))[:, None] & (lon <= 40)[None, :]
obs = clean + noise_sd * e + enso * index[:, None, None] * pattern + step * region * (months >= 180)[:, None, None]
return obs, clean, truth
field_obs, field_clean, truth_field = make_field()
fig, ax = plt.subplots(1, 3, figsize=(14, 3.6))
for axi, img, title in [(ax[0], truth_field["trend_c_per_decade"], "truth: trend (°C per decade)"),
(ax[1], field_obs[200] - field_clean[200], "noise + nuisance + step, September 2007 (°C)")]:
plt.colorbar(axi.pcolormesh(lon, lat, img, cmap="RdBu_r", shading="nearest"), ax=axi)
axi.set(title=title, xlabel="longitude (°E)", ylabel="latitude (°N)")
years = 1991 + np.arange(30)
ax[2].plot(years, field_obs[:, 22, 2].reshape(30, 12).mean(1), "o-", color="0.45", ms=3, label="synthetic, 50° N 15° E")
ax[2].plot(years, field_clean[:, 22, 2].reshape(30, 12).mean(1), color="C3", lw=1, label="signal (truth)")
ax[2].set(title="annual means, one cell in the step region", ylabel="°C")
ax[2].legend(fontsize=8)
fig.tight_layout()
Your turn (team C): the fitted trend and its error. fit_trends fits, at every grid cell at once, a constant, a trend and an annual sine and cosine by least squares, and returns the naive standard error of the trend, the one that assumes white noise. Fill in the least-squares solve, then change settings: phi (0 is white in time), corr_cells, enso, step, and compare the actual trend error, known because you know the truth, with the naive error bar.
Hint: m = np.linalg.lstsq(G, y, rcond=None)[0] solves for every column of y at once. What to look for: when phi grows, does the naive error bar keep up with the actual error? Where on the map does the step or the El Niño pattern bias the trend? A worked solution follows the code cell (hidden).
def fit_trends(field):
G = np.column_stack([np.ones(360), months / 120, np.cos(2 * np.pi * months / 12), np.sin(2 * np.pi * months / 12)])
y = field.reshape(360, -1) # one column per grid cell
# --- your code
m = None # least-squares coefficients, shape (4, number of cells); row 1 is the trend per decade
# --- end
if m is None:
return None, None
resid = y - G @ m
se = np.sqrt((resid**2).sum(0) / (360 - 4) * np.linalg.inv(G.T @ G)[1, 1]) # naive: assumes white noise
return m[1].reshape(field.shape[1:]), se.reshape(field.shape[1:])
settings = [dict(phi=0.0, enso=0.0, step=0.0), dict(phi=0.8, enso=0.0, step=0.0), dict()]
for kw in settings:
trend_k, se_k = fit_trends(make_field(**kw)[0])
if trend_k is not None:
err_k = trend_k - truth_field["trend_c_per_decade"]
print(kw, f"-> RMS trend error {np.sqrt(np.mean(err_k**2)):.3f}, mean naive error bar {se_k.mean():.3f} °C per decade")
check = fit_trends(make_field(noise_sd=0.0, enso=0.0, step=0.0)[0])[0]
print("self-check, no noise:", "not answered yet" if check is None else
("correct" if np.allclose(check, truth_field["trend_c_per_decade"]) else "the fitted trend differs from the truth"))self-check, no noise: not answered yet
Notebook Cell
# Worked solution, team C. Names end in _sol so that running this cell keeps your own results.
G_sol = np.column_stack([np.ones(360), months / 120, np.cos(2 * np.pi * months / 12), np.sin(2 * np.pi * months / 12)])
def fit_trends_sol(field):
y = field.reshape(360, -1)
m = np.linalg.lstsq(G_sol, y, rcond=None)[0]
se = np.sqrt(((y - G_sol @ m) ** 2).sum(0) / (360 - 4) * np.linalg.inv(G_sol.T @ G_sol)[1, 1])
return m[1].reshape(field.shape[1:]), se.reshape(field.shape[1:])
rows_sol = []
for phi in [0.0, 0.5, 0.8, 0.95]:
trend_s, se_s = fit_trends_sol(make_field(phi=phi, enso=0.0, step=0.0)[0])
rows_sol.append({"phi": phi, "actual RMS error": np.sqrt(np.mean((trend_s - truth_field["trend_c_per_decade"]) ** 2)),
"mean naive error bar": se_s.mean()})
print(pd.DataFrame(rows_sol).round(3).to_string(index=False))
trend_full_sol, _ = fit_trends_sol(make_field()[0]) # default: phi 0.5, El Nino 0.6, step 0.5
fig, ax = plt.subplots(figsize=(6, 3.4))
plt.colorbar(ax.pcolormesh(lon, lat, trend_full_sol - truth_field["trend_c_per_decade"], cmap="RdBu_r",
vmin=-0.4, vmax=0.4, shading="nearest"), ax=ax, label="°C per decade")
ax.set(title="fitted minus true trend, default settings", xlabel="longitude (°E)", ylabel="latitude (°N)"); phi actual RMS error mean naive error bar
0.00 0.043 0.048
0.50 0.073 0.048
0.80 0.123 0.047
0.95 0.235 0.043

5.5 Template D: a planetary transit light curve (1D, 2-minute cadence)¶
Signal: box-shaped transits of a planet in front of its star. The truth is the period, the first mid-transit time, the duration and the depth (the fraction of starlight blocked, 1%).
Noise: photon noise, white by default;
coloranddistchange it.Nuisance: the star itself. Spots rotating with the star make a quasi-periodic modulation (6.3-day period here), and granulation, a red process with a time scale of about an hour (an AR(1) process here), adds short-term flicker;
star_ampsets their size.Instrument problem: the data downlink gap in the middle of one 27-day TESS (Transiting Exoplanet Survey Satellite) sector, when the spacecraft sends its data to Earth near the closest point of its 13.7-day orbit.
def make_lightcurve(photon_sd=1e-3, color="white", dist="gaussian", star_amp=4e-3, gap=(13.2, 14.3), seed=4):
r = np.random.default_rng(seed)
t = np.arange(0, 27.0, 2 / 1440) # days, 2-minute cadence
truth = {"period_d": 3.52, "t0_d": 1.2, "duration_d": 0.125, "depth": 0.010}
phase = (t - truth["t0_d"] + truth["period_d"] / 2) % truth["period_d"] - truth["period_d"] / 2
clean = 1.0 - truth["depth"] * (np.abs(phase) < truth["duration_d"] / 2)
star = star_amp * (np.sin(2 * np.pi * t / 6.3) * (1 + 0.3 * np.sin(2 * np.pi * t / 17))
+ 0.3 * make_noise(len(t), "ar1", rng=r, phi=np.exp(-2 / 60))) # spots; granulation, ~1 h
flux = clean + star + photon_sd * make_noise(len(t), color, dist, rng=r)
if gap is not None:
flux[(t >= gap[0]) & (t < gap[1])] = np.nan # data downlink gap
return t, flux, clean, truth
t_lc, flux_lc, clean_lc, truth_lc = make_lightcurve()
transits = truth_lc["t0_d"] + truth_lc["period_d"] * np.arange(8)
show(t_lc, flux_lc, clean_lc, transits[transits < 27], "Template D: transits, starspots and granulation, photon noise, downlink gap",
"time (days)", "relative flux");
Your turn (team D): the transit depth. The cell removes the stellar variability with a running median over window_d days and folds the record at the known period. Fill in depth_hat: the median detrended flux just outside the transits minus the mean inside. Then change settings: star_amp, photon_sd, color of the photon noise, window_d, and compare depth_hat with the truth, 0.010.
Hint: np.nanmedian(detr[outside]) - np.nanmean(detr[inside]). What to look for: a window too short follows the transit and eats part of it; a window too long leaves the starspots in. A worked solution follows the code cell (hidden).
def transit_depth(t, flux, truth, window_d=0.75):
trend = pd.Series(flux).rolling(int(window_d * 720), center=True, min_periods=50).median().to_numpy() # 720 per day
detr = flux / trend - 1
phase = (t - truth["t0_d"] + truth["period_d"] / 2) % truth["period_d"] - truth["period_d"] / 2
inside = np.abs(phase) < 0.4 * truth["duration_d"]
outside = (np.abs(phase) > truth["duration_d"]) & (np.abs(phase) < 3 * truth["duration_d"])
# --- your code
depth_hat = None # transit depth, a fraction, one number
# --- end
return depth_hat
settings = [dict(star_amp=0.0), dict(), dict(star_amp=0.01), dict(color=1.0)]
for kw in settings:
t_k, flux_k, _, truth_k = make_lightcurve(**kw)
depth_k = transit_depth(t_k, flux_k, truth_k)
print(kw, "-> depth_hat:", depth_k if depth_k is None else f"{depth_k:.5f}", "; truth:", truth_k["depth"])
check = transit_depth(t_lc, make_lightcurve(photon_sd=0.0, star_amp=0.0)[1], truth_lc)
print("self-check, no noise and a quiet star:", "not answered yet" if check is None
else ("correct" if abs(check - 0.010) < 1e-9 else f"{check:.5f}, expected 0.01000")){'star_amp': 0.0} -> depth_hat: None ; truth: 0.01
{} -> depth_hat: None ; truth: 0.01
{'star_amp': 0.01} -> depth_hat: None ; truth: 0.01
{'color': 1.0} -> depth_hat: None ; truth: 0.01
self-check, no noise and a quiet star: not answered yet
Notebook Cell
# Worked solution, team D. Names end in _sol so that running this cell keeps your own results.
def transit_depth_sol(t, flux, truth, window_d=0.75):
trend = pd.Series(flux).rolling(int(window_d * 720), center=True, min_periods=50).median().to_numpy()
detr = flux / trend - 1
phase = (t - truth["t0_d"] + truth["period_d"] / 2) % truth["period_d"] - truth["period_d"] / 2
inside = np.abs(phase) < 0.4 * truth["duration_d"]
outside = (np.abs(phase) > truth["duration_d"]) & (np.abs(phase) < 3 * truth["duration_d"])
return np.nanmedian(detr[outside]) - np.nanmean(detr[inside])
rows_sol = []
for star_amp in [0.0, 0.004, 0.01, 0.02]:
for window_d in [0.2, 0.75, 3.0]:
depths = [transit_depth_sol(t_lc, make_lightcurve(star_amp=star_amp, seed=s)[1], truth_lc, window_d) for s in range(10)]
rows_sol.append({"star_amp": star_amp, "window_d": window_d, "depth_hat mean": np.mean(depths)})
table_lc_sol = pd.DataFrame(rows_sol).pivot(index="star_amp", columns="window_d", values="depth_hat mean")
print("mean depth_hat over 10 synthetic sectors; truth 0.010; columns: running-median window (days)")
print(table_lc_sol.round(4).to_string())mean depth_hat over 10 synthetic sectors; truth 0.010; columns: running-median window (days)
window_d 0.20 0.75 3.00
star_amp
0.000 0.0009 0.0100 0.0100
0.004 0.0013 0.0101 0.0101
0.010 0.0024 0.0102 0.0103
0.020 0.0036 0.0102 0.0106
5.6 Template E: categorical source labels in a local catalog¶
Signal: the true class of each of 900 events: earthquake, quarry blast or noise trigger. Two features describe each event: the log ratio of S-wave to P-wave amplitude (explosions make weaker S waves than earthquakes) and the local hour of the day, entered as so that 23 h and 1 h are neighbours, a transform of the data.
Noise in the labels: a fraction
flipof the labels is wrong.flipis the fraction of the whole catalog; structured flips are taken from the blasts only, soflip=0.15relabels 135 of the 900 events, most of the blasts. Random flips (structured=False) pick any event and any other class; structured flips call quarry blasts earthquakes, a known contamination of seismicity catalogs (Wiemer and Baer, 2000, Bulletin of the Seismological Society of America).Nuisance: noise triggers from traffic and other cultural sources cluster in the daytime, during the blasting hours.
Instrument problem: with
mixed_clock=True, the second half of the catalog stores hours in UTC while the first half used Pacific Standard Time, an 8-hour shift: a time-convention error, like lecture 8’s clock errors.
CLASSES = np.array(["earthquake", "quarry blast", "noise trigger"])
def make_catalog(flip=0.1, structured=False, mixed_clock=False, n=900, seed=1):
r = np.random.default_rng(seed)
y_true = r.choice(3, n, p=[0.5, 0.2, 0.3]) # truth: class index of each event
s_to_p = r.normal(np.array([0.6, -0.4, 0.1])[y_true], 0.15) # log10 of S over P amplitude
hour = np.select([y_true == 1, y_true == 2], [r.normal(13, 2, n), r.normal(14, 4, n)], r.uniform(0, 24, n)) % 24
if mixed_clock:
hour[n // 2:] = (hour[n // 2:] + 8) % 24 # second half stored in UTC
X = np.column_stack([s_to_p, np.cos(2 * np.pi * (hour - 13) / 24)])
pool = np.flatnonzero(y_true == 1) if structured else np.arange(n) # structured: only blasts mislabeled
wrong = r.choice(pool, min(int(round(flip * n)), len(pool)), replace=False)
y_obs = y_true.copy()
y_obs[wrong] = 0 if structured else (y_true[wrong] + r.integers(1, 3, len(wrong))) % 3
return X, y_obs, y_true
X_cat, y_obs_cat, truth_cat = make_catalog()
fig, ax = plt.subplots(figsize=(7, 4))
for c in range(3):
ax.scatter(*X_cat[y_obs_cat == c].T, s=10, alpha=0.6, label=f"labelled {CLASSES[c]}")
bad = y_obs_cat != truth_cat
ax.scatter(*X_cat[bad].T, s=40, facecolors="none", edgecolors="k", lw=0.7, label="wrong label (truth known)")
ax.set(xlabel="log10 S/P amplitude ratio", ylabel="cos(2π (hour − 13) / 24)", title="Template E: catalog with 10% random label flips")
ax.legend(fontsize=8, loc="lower left");
Your turn (team E): label agreement and two consequences. Fill in agreement in label_agreement: the fraction of observed labels equal to the true ones. The cell then measures two consequences. First, the day-to-night ratio of the events labelled earthquakes, per hour, between 8 and 18 h against the rest; true earthquakes come at any hour, so the truth is close to 1. Second, the accuracy of a nearest-class-mean rule (each event goes to the class whose mean features are closest), trained on the first half of the catalog with the observed labels and scored on the second half against the truth. Change settings: flip, structured, mixed_clock, and compare. A nearest-mean rule only uses class averages, so a clean subset of blasts still finds them; the logistic regression in the Session 9 slides learns where the classes overlap and is hurt by the same structured flips. Which behaves like your model?
Hint: np.mean(y_obs == y_true). What to look for: at the same fraction of wrong labels, which kind of error makes daytime “earthquakes” appear, and which kind hurts the trained rule? What does the 8-hour shift do? A worked solution follows the code cell (hidden).
def nearest_mean_accuracy(X, y_labels, y_true):
half = len(y_true) // 2
means = np.array([X[:half][y_labels[:half] == c].mean(0) for c in range(3)])
pred = np.argmin(((X[half:, None, :] - means[None]) ** 2).sum(-1), axis=1)
return np.mean(pred == y_true[half:])
def day_night_ratio(X, y_labels):
day = X[:, 1] > np.cos(2 * np.pi * 5 / 24) # 8 to 18 h local, 10 hours
quakes = y_labels == 0
return (np.sum(quakes & day) / 10) / (np.sum(quakes & ~day) / 14) # events per hour, day over night
def label_agreement(y_obs, y_true):
# --- your code
agreement = None # fraction of observed labels that equal the true labels
# --- end
return agreement
settings = [dict(flip=0.0), dict(flip=0.15), dict(flip=0.15, structured=True), dict(flip=0.0, mixed_clock=True)]
for kw in settings:
X_k, y_obs_k, y_true_k = make_catalog(**kw)
agree_k = label_agreement(y_obs_k, y_true_k)
print(kw, "-> label agreement:", agree_k if agree_k is None else f"{agree_k:.3f}",
f"| earthquakes day/night {day_night_ratio(X_k, y_obs_k):.2f} (true labels, same clock {day_night_ratio(X_k, y_true_k):.2f})"
f" | nearest-mean accuracy {nearest_mean_accuracy(X_k, y_obs_k, y_true_k):.3f}")
check = label_agreement(*make_catalog(flip=0.1)[1:])
print("self-check, flip = 0.1:", "not answered yet" if check is None
else ("correct" if abs(check - 0.9) < 1e-9 else f"{check:.3f}, expected 0.900")){'flip': 0.0} -> label agreement: None | earthquakes day/night 1.01 (true labels, same clock 1.01) | nearest-mean accuracy 0.733
{'flip': 0.15} -> label agreement: None | earthquakes day/night 1.14 (true labels, same clock 1.01) | nearest-mean accuracy 0.640
{'flip': 0.15, 'structured': True} -> label agreement: None | earthquakes day/night 1.65 (true labels, same clock 1.01) | nearest-mean accuracy 0.738
{'flip': 0.0, 'mixed_clock': True} -> label agreement: None | earthquakes day/night 1.02 (true labels, same clock 1.02) | nearest-mean accuracy 0.431
self-check, flip = 0.1: not answered yet
Notebook Cell
# Worked solution, team E. Names end in _sol so that running this cell keeps your own results.
rows_sol = []
for structured in [False, True]:
for mixed_clock in [False, True]:
for flip in [0.0, 0.05, 0.1, 0.15]:
res = []
for s in range(20):
X_s, y_obs_s, y_true_s = make_catalog(flip=flip, structured=structured, mixed_clock=mixed_clock, seed=s)
res.append([day_night_ratio(X_s, y_obs_s), nearest_mean_accuracy(X_s, y_obs_s, y_true_s)])
res = np.mean(res, axis=0)
rows_sol.append({"flips": "structured" if structured else "random", "mixed clock": mixed_clock,
"flip": flip, "earthquakes day/night": res[0], "accuracy": res[1]})
table_cat_sol = pd.DataFrame(rows_sol).pivot(index=["flips", "mixed clock"], columns="flip")
print("means of 20 catalogs; columns: fraction of wrong labels")
print(table_cat_sol.round(2).to_string())means of 20 catalogs; columns: fraction of wrong labels
earthquakes day/night accuracy
flip 0.00 0.05 0.10 0.15 0.00 0.05 0.10 0.15
flips mixed clock
random False 1.03 1.08 1.13 1.18 0.75 0.73 0.70 0.68
True 1.05 1.05 1.07 1.06 0.42 0.42 0.43 0.43
structured False 1.03 1.27 1.50 1.74 0.75 0.75 0.76 0.76
True 1.05 1.09 1.12 1.17 0.42 0.43 0.43 0.44
5.7 Reflection (5 minutes, in your team notes)¶
Which parts of your real data are signal for someone else? Name the field or the person who would want what you remove.
Which ingredient moved your measured number the most: the noise level, its color, its distribution, the nuisance, or the instrument problem? Give the numbers.
What does your synthetic leave out? Name two properties of your real record it does not reproduce: noise that changes with season or time of day, transients that are not Gaussian, a nuisance correlated with the signal, labels that are wrong for a reason, a gap that falls when the signal is strongest.
Would a model trained on your synthetic learn the real problem, or an easier one? Friday’s class turns these answers into a rubric for AI-ready data.
6. Exercises¶
Exercise 1: spectrum-matched noise from two different hours¶
The course copy holds two hours of noise. Split it into the first hour (04:15 to 05:15 UTC) and the second (05:15 to 06:15 UTC), generate spectrum-matched noise from each, and compare:
Compare the variance and kurtosis of the two real hours and of their two synthetic versions.
Overlay the four amplitude spectra. Do the microseism peaks move between the two hours?
Comment: is one synthetic noise window enough to represent the noise at this station? What would a window from another day or season add? (Optional, needs internet: download 04:15 to 06:15 UTC on 28 July 2021 from the EarthScope FDSN web services, as in the commented lines of the scaffold, and repeat.)
# Exercise 1 scaffold
# from scipy.stats import kurtosis
# hour1, hour2 = real_noise[:360_000], real_noise[360_000:] # 04:15-05:15 and 05:15-06:15 UTC
# synth1 = mlgeo_synth.spectrum_matched_noise(hour1, seed=1)
# synth2 = mlgeo_synth.spectrum_matched_noise(hour2, seed=2)
# ... compare np.var and kurtosis of the four series, then overlay their spectra
#
# Optional, needs internet: the same two hours one day earlier
# from obspy.clients.fdsn import Client
# day_before = Client("https://service.earthscope.org").get_waveforms(
# "UW", "RATT", "--", "HHZ", obspy.UTCDateTime(2021, 7, 28, 4, 15), obspy.UTCDateTime(2021, 7, 28, 6, 15))Self-check
Each real hour has 360,000 samples (one hour at 100 Hz), and so does each synthetic version.
Each synthetic hour reproduces the variance of its own reference hour; the second hour’s variance is about 1.2 times the first’s.
scipy.stats.kurtosisreturns excess kurtosis, so the synthetic (random-phase, hence Gaussian) hours sit near 0; the real hours are slightly above 0 over the full band, and well above it in the 1 to 20 Hz band (section 5.1).On the overlaid spectra, each synthetic curve lies on top of its own real curve. Between the two hours the microseism peak stays near 0.15 Hz with a similar amplitude.
Part 3: two hours of one evening (21:15 to 23:15 PDT on 28 July 2021) agree closely, so they do not sample what changes the noise: ocean storms, season, day and night. One window under-represents the station’s noise; draw from several days.
Exercise 2: move the STA/LTA detection floor¶
The detection floor in Section 4.4 was measured with one specific window pair: 1 s short, 10 s long. Those lengths are the detector’s only tuning knobs, and observatories choose them to match the signals they hunt.
Repeat the Section 4.4 sweep for three window pairs: (0.5 s, 5 s), (1 s, 10 s), and (2 s, 20 s). For each pair, recompute the threshold from noise-only windows first — the noise distribution changes with the windows — then measure the detection curve and its 50% crossing.
Plot the three detection curves on one axis. Which window pair detects the Ricker event at the lowest SNR, and how does that relate to the event’s roughly 1 s duration?
What goes wrong if you keep the 1 s / 10 s threshold while changing the windows?
# Exercise 2 scaffold
# for sta_s, lta_s in [(0.5, 5.0), (1.0, 10.0), (2.0, 20.0)]:
# n_s, n_l = int(sta_s * fs), int(lta_s * fs)
# # 1) recompute the threshold: peak_stalta of 200 noise-only windows with
# # these window lengths, take the 99th percentile
# # 2) rerun the SNR sweep of Section 4.4 with peak_stalta(..., n_s, n_l)
# # 3) record the 50% crossing with np.interp(0.5, detect_prob, snrs_ex)
# plot the three curves on one semilogx axis and compare the crossingsSelf-check
Each window pair needs its own threshold: the noise-only peak distribution shifts when the windows change (a longer short window averages more noise samples, so its peaks are lower). Expect three different 99th percentiles.
All three detection curves rise from the 1% false-alarm floor to 1, and each 50% crossing sits within roughly a factor of two of the Section 4.4 value (SNR near 5).
The short window closest to the event duration (about 1 s for this Ricker wavelet) gives the lowest crossing: a 0.5-2 s STA integrates most of the event energy, while a much longer STA dilutes it with surrounding noise.
Reusing the 1 s / 10 s threshold with different windows breaks the 1% false-alarm calibration: the comparison between curves is then unfair, because each detector operates at a different false-alarm rate. Detection probability only means something at a stated false-alarm rate.
7. When is synthetic data admissible?¶
Synthetic data is a tool, not a substitute for observation. Use this checklist before putting synthetic data into a project.
Admissible:
Method development. Prototyping a detector, a filter, or a model on data with known ground truth before touching real data.
Benchmarking. Measuring accuracy, recall, or failure points (as in Exercise 2) requires knowing the true answer. Synthetic data provides it.
Augmentation with disclosed provenance. Adding noise realizations or synthetic events to a training set is standard practice, as long as the paper or report states which samples are synthetic and how they were generated.
Hidden test sets. Instructors and benchmark maintainers use synthetic data to build test sets that models cannot have memorized.
Not admissible:
Substituting for real validation in scientific claims. A model validated only on synthetic data has not been validated. A scientific conclusion about the Earth must rest on real observations.
Always disclose. Whenever synthetic data enters an analysis, say so: which samples, which generator, which seed. The generator code and seeds belong in the repository with the rest of the project. In this course, use the mlgeo_synth package as the generator so that provenance is one import away, and follow the project guidance in the MLGeo project instructions.