typestar

Signal processing in Python

Peaks, filters and spectra over a sampled series.

import numpy as np
from scipy import signal

rng = np.random.default_rng(7)
t = np.linspace(0, 2, 400)
clean = np.sin(2 * np.pi * 3 * t)
noisy = clean + rng.normal(0, 0.4, size=t.size)

peaks, props = signal.find_peaks(noisy, height=0.5, distance=20)
print(len(peaks), props["peak_heights"][:3].round(2))

b, a = signal.butter(4, 0.1, btype="low")
smoothed = signal.filtfilt(b, a, noisy)
print(round(float(np.std(noisy - clean)), 3),
      round(float(np.std(smoothed - clean)), 3))

freqs, power = signal.welch(noisy, fs=200, nperseg=128)
print(round(float(freqs[np.argmax(power)]), 1))

How it works

  1. find_peaks takes height, distance and prominence.
  2. butter designs a filter; filtfilt applies it without phase shift.
  3. detrend removes a linear trend before analysis.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
581
Tokens
209
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 114 seconds.

Type this snippet

Step 2 of 3 in Linear algebra & signals, step 17 of 23 in Scientific computing with SciPy.

← Previous Next →