packages

signal

On this page

Signal processing over core::array arrays: FFTs of any length, convolution, windows, FIR and IIR filters, spectral estimation and peak finding, in pure Nabi.

#Signals and spectra

A recorded signal is a vector of samples taken at a fixed rate. signal finds the frequencies in it (the FFT and spectral estimates), removes the ones you do not want (filters), and finds features such as peaks. Samples come in as anything array-like and go out as Vector<f64>, or Vector<Complex<f64>> for a spectrum.

#A test signal

Two tones, 50 Hz and 120 Hz, sampled at 1 kHz for one second. signal defines number suffixes for rates and times: 1khz is 1000.0, 50hz is 50.0 and 5ms is 0.005, plain f64 values that say what they mean. Array::from_fn builds the samples from their index.

nabi
use core::array::{Array, Vector};
use signal::units::*;

let fs = 1khz;
let x: Vector<f64> = Array::from_fn([1000], |i: [usize; 1]| -> f64 {
    let t = (i[0] as f64) / fs;
    (2.0 * f64::PI * 50hz * t).sin() + 0.5 * (2.0 * f64::PI * 120hz * t).sin()
});
println(f"{x.len()} samples, {x.len() as f64 / fs} s, peak value {x.max() ?? 0.0:.3}");
text
1000 samples, 1 s, peak value 1.476

#The FFT

signal::rfft is the discrete Fourier transform of a real signal: one complex number per frequency from 0 up to half the sampling rate. signal::fft::rfftfreq gives the frequency of each bin. The magnitudes, scaled by 2 / n, are the amplitudes of the tones.

nabi
use core::array::{Array, Vector};
use signal::units::*;

let fs = 1khz;
let n = 1000;
let x: Vector<f64> = Array::from_fn([n], |i: [usize; 1]| -> f64 {
    let t = (i[0] as f64) / fs;
    (2.0 * f64::PI * 50hz * t).sin() + 0.5 * (2.0 * f64::PI * 120hz * t).sin()
});

let spec = try signal::rfft(x);
let freq = try signal::fft::rfftfreq(n, d: 1.0 / fs);
let amp = signal::abs(spec) .* (2.0 / (n as f64));
for k in 0..amp.len() {
    if amp[k] > 0.1 { println(f"{freq[k]} Hz: amplitude {amp[k]:.3}"); }
}
text
50 Hz: amplitude 1.000
120 Hz: amplitude 0.500

fft and ifft transform complex signals of any length, not only powers of two; fft::fft2 and fftn work on images and volumes.

#Noise and the power spectrum

A real measurement has noise on top, and a single FFT of it is noisy too. Welch's method averages the spectra of overlapping segments: less detail in frequency, much less noise. welch returns a Spectrum with the frequencies f, the power density p and peak, the frequency of the largest value. The noise here comes from the stats package.

nabi
use core::array::{Array, Vector};
use signal::units::*;
use stats::{Distribution, Normal, Sampler};

let fs = 1khz;
let g = Sampler::seed(3);
let noise = (try Normal::new(0.0, 1.0)).samples(ref g, 4000);
let x: Vector<f64> = Array::from_fn([4000], |i: [usize; 1]| -> f64 {
    let t = (i[0] as f64) / fs;
    0.8 * (2.0 * f64::PI * 120hz * t).sin() + noise[i[0]]
});

let s = try signal::welch(x, fs: fs, nperseg: 256);
println(f"{s.f.len()} bins, {s.f[1] - s.f[0]:.4} Hz apart");
println(f"strongest frequency {s.peak():.1} Hz");
text
129 bins, 3.9062 Hz apart
strongest frequency 121.1 Hz

The tone is weaker than the noise in every single sample (0.8 against a standard deviation of 1), but the spectrum still shows it clearly.

#Filter a signal

A filter keeps some frequencies and removes others. butter designs a Butterworth filter (flat in the band it keeps) as second-order sections, which stay accurate at high orders; sosfiltfilt runs it forwards and backwards, so the output has no delay. Here a low-pass at 80 Hz removes the 120 Hz tone and keeps the 50 Hz one.

nabi
use core::array::{Array, Vector};
use signal::filter::{Band, butter, sosfiltfilt};
use signal::units::*;

let fs = 1khz;
let tone = |f: f64, t: f64| -> f64 { (2.0 * f64::PI * f * t).sin() };
let x: Vector<f64> = Array::from_fn([1000], |i: [usize; 1]| -> f64 {
    let t = (i[0] as f64) / fs;
    tone(50hz, t) + 0.5 * tone(120hz, t)
});
let want: Vector<f64> = Array::from_fn([1000], |i: [usize; 1]| -> f64 { tone(50hz, (i[0] as f64) / fs) });

let sos = try butter(8, Band::Lowpass(80hz), fs: fs);
let y = try sosfiltfilt(sos, x);

// Away from the ends, the filtered signal is the 50 Hz tone alone.
let err = (y[100:900] .- want[100:900]).map(|v: f64| -> f64 { v.abs() }).max() ?? 0.0;
println(f"largest difference from the pure tone: {err:.4}");
text
largest difference from the pure tone: 0.0009

Band::Highpass, Bandpass and Bandstop make the other kinds; cheby1, cheby2 and bessel other shapes; firwin a finite impulse response filter. A design error says what to pass: forget fs: and the message explains that the band edges are then in units of the sampling rate.

#Find peaks

find_peaks finds the local maxima of a signal; height, distance and prominence keep only the ones that matter. Here, the beats of a synthetic heartbeat trace.

nabi
use core::array::{Array, Vector};

// A spike every 0.8 s on a slow wander, sampled at 100 Hz.
let x: Vector<f64> = Array::from_fn([500], |i: [usize; 1]| -> f64 {
    let t = (i[0] as f64) / 100.0;
    let phase = t % 0.8;
    0.2 * (2.0 * f64::PI * 0.1 * t).sin() + (-(phase - 0.4) * (phase - 0.4) / 0.0005).exp()
});

let p = try signal::find_peaks(x, height: 0.5, distance: 30);
println(f"{p.indices.len()} beats at samples {p.indices:?}");
let gaps = p.indices.to_list().pairwise().map(|(a, b)| b - a).to_list();
println(f"gaps {gaps:?}: {60.0 / 0.8} beats per minute");
text
6 beats at samples [40, 120, 200, 280, 360, 440]
gaps [80, 80, 80, 80, 80]: 75 beats per minute

#Convolution

Smoothing, edge detection and many filters are convolutions with a short kernel. ⊛ (from signal::ops) is the full convolution, ⋆ the correlation; signal::convolve takes a mode: to keep the output the length of the input.

nabi
use core::array::Vector;
use signal::ops::*;

let x: Vector<f64> = [0, 0, 1, 1, 1, 0, 0];
let k: Vector<f64> = [0.25, 0.5, 0.25];
println(x ⊛ k);
println(try signal::convolve(x, k, mode: signal::conv::Mode::Same));
text
[0.0, 0.0, 0.25, 0.75, 1.0, 0.75, 0.25, 0.0, 0.0]
[0.0, 0.25, 0.75, 1.0, 0.75, 0.25, 0.0]

#What next

  • Fitting and optimization: fit a model to measured data.
  • The modules below: window, spectral::stft and spectral::spectrogram, the Hilbert transform (spectral::hilbert), resampling (filter::resample).

Modules

  • conv Convolution and correlation, 1-d and 2-d, direct or by FFT.
  • fft Discrete Fourier transforms of any length: complex, real, n-d, the frequency helpers and the cosine and sine transforms built on them.
  • filter Digital filters: FIR and IIR design, filtering (causal and zero-phase), frequency response, resampling and detrending.
  • ops Convolution and correlation as operators: a ⊛ b (U+229B, circled asterisk) is the full linear convolution and a ⋆ b (U+22C6, star operator) the full cross-correlation, both at the level of *.
  • peaks Peak finding as SciPy's find_peaks: local maxima (a flat top counts once, at its middle), then filtered by height, by distance (highest first) and by topographic prominence.
  • spectral Spectral estimation: periodograms averaged over segments (Welch), the short-time Fourier transform and its inverse, spectrograms, and the analytic signal.
  • units Number suffixes for frequencies and times, so a call reads like its spec sheet: butter(4, Band::Lowpass(100hz), fs: 8khz).
  • window Window functions, as SciPy's scipy.signal.windows: symmetric by default (for filter design); sym: false gives the periodic form (for spectral analysis), the first m points of the m + 1 window.

Re-exports

conv::{convolve, correlate, convolve2d, correlate2d, Mode, Method}Source

pub use conv::{convolve, correlate, convolve2d, correlate2d, Mode, Method}
  • convolve The convolution (a * v)[k] = sum_i a[i] v[k - i], cut to mode.
  • correlate The cross-correlation c[k] = sum_i a[i + k] v[i], as SciPy's correlate: convolve(a, v reversed), so in Mode::Full lag 0 is at index v.len() - 1.
  • convolve2d The 2-d convolution of a and kernel k, cut to mode along both axes (as SciPy's convolve2d with zero boundaries).
  • correlate2d The 2-d cross-correlation: convolve2d with k flipped on both axes.
  • Mode Which part of the full convolution to return.
  • Method How to compute: Auto picks the faster of the two by size.

fft::{fft, ifft, rfft, irfft, fftn, ifftn, Plan, RealPlan, Norm}Source

pub use fft::{fft, ifft, rfft, irfft, fftn, ifftn, Plan, RealPlan, Norm}
  • fft The DFT X_k = sum_j x_j exp(-2 pi i j k / n) of a real or complex signal, cut or zero-padded to n samples when n is given.
  • ifft The inverse DFT x_j = (1/n) sum_k X_k exp(2 pi i j k / n) (the 1/n under Norm::Backward), so ifft(fft(x)) is x to about 1e-15 relative.
  • rfft Bins 0..=n/2 of the DFT of a real signal: the rest are their conjugates.
  • irfft The n real samples whose non-negative bins are x (as rfft gives them); n defaults to 2 * (x.len() - 1).
  • fftn The N-d DFT of x over axes (every axis by default), in the order given; an axis named twice is transformed twice.
  • ifftn The inverse of fftn over the same axes.
  • Plan A complex FFT of one length with its twiddles computed once: build it with Plan::new(n) and run it on many signals.
  • RealPlan A real FFT of one length, reusable: forward gives the n / 2 + 1 non-negative frequency bins, inverse takes them back.
  • Norm How a transform is scaled: Backward (the default, as NumPy) leaves the forward transform unscaled and divides the inverse by n; Ortho divides both by sqrt(n), so the pair is unitary; Forward divides the forward transform by n.

filter::{Band, butter, cheby1, cheby2, bessel, firwin, lfilter, sosfilt, filtfilt, sosfiltfilt, freqz, sosfreqz}Source

pub use filter::{Band, butter, cheby1, cheby2, bessel, firwin, lfilter, sosfilt, filtfilt, sosfiltfilt, freqz, sosfreqz}
  • Band The pass band of a filter, edges in the units of the sampling rate fs the design function takes (with the default fs = 2.0 an edge of 1 is the Nyquist frequency, as SciPy).
  • butter A Butterworth filter as second-order sections.
  • cheby1 A Chebyshev type I filter with rp dB of pass-band ripple, as second-order sections.
  • cheby2 A Chebyshev type II filter rs dB down in the stop band, as second-order sections.
  • bessel A Bessel filter (phase-normalized, as SciPy's default), as second-order sections: nearly constant group delay in the pass band.
  • firwin A linear-phase FIR filter of numtaps coefficients for band (edges in units of fs), windowed by window (Hamming by default).
  • lfilter x filtered by b(z) / a(z) from rest: a[0] y[t] = sum b[k] x[t - k] - sum_(k >= 1) a[k] y[t - k] (transposed direct form II).
  • sosfilt x filtered by the cascade of second-order sections sos (rows [b0, b1, b2, a0, a1, a2]), from rest.
  • filtfilt x filtered forward and then backward: zero phase, the magnitude response squared, and no delay.
  • sosfiltfilt filtfilt for second-order sections: the zero-phase way to run an IIR filter of any order.
  • freqz The response H(e^jw) = b(e^jw) / a(e^jw) at n frequencies from 0 up to (not including) Nyquist, or the whole circle with whole.
  • sosfreqz freqz for second-order sections: the product of the rows' responses.

peaks::{find_peaks, Peaks}Source

pub use peaks::{find_peaks, Peaks}
  • find_peaks The peaks of x: samples higher than both neighbours (a flat top counts once, at its middle; the ends never count).
  • Peaks The peaks find_peaks kept, in increasing position, with the properties it measured.

spectral::{welch, periodogram, stft, istft, spectrogram, hilbert}Source

pub use spectral::{welch, periodogram, stft, istft, spectrogram, hilbert}
  • welch Welch's power spectral density estimate of x sampled at fs: segments of nperseg samples (256 by default, at most the signal length), overlapping by noverlap (half by default), each detrended (Detrend::Constant by default, none for no detrending), windowed (periodic Hann by default) and zero-padded to nfft.
  • periodogram The periodogram of x: one segment, the whole signal, no window by default.
  • stft The STFT of x (as SciPy's stft): nperseg / 2 zeros added at each end and zeros at the end to fill the last segment, so every sample is covered; segments of nperseg (256) overlapping by noverlap (half), windowed by a periodic Hann window, each a real FFT of nfft points scaled by 1 / sum(window).
  • istft The signal back from its STFT (as SciPy's istft): each column is inverse-transformed, windowed and overlap-added, divided by the summed squared window, and the nperseg / 2 boundary samples are dropped.
  • spectrogram The spectrogram of x (as SciPy's spectrogram): power spectral density of each segment, by default nperseg 256 samples of a Tukey(0.25) window overlapping by an eighth, each detrended.
  • hilbert The analytic signal x + i H(x) of a real x (H the Hilbert transform), zero-padded or cut to n samples when given.

window::WindowSource

pub use window::Window
  • Window A window by name, for the functions that take one (firwin, welch, stft, ...).

Enums

SignalErrorSource

pub enum SignalError

What went wrong in a signal call. Every message names the argument, the value it got and what to pass instead.

nabi
use signal::SignalError;

try signal::window::kaiser(0, 8.6) catch e: SignalError {
    println(e); // `kaiser` length: got 0, need at least 1 (pass `m >= 1`)
};
  • Length§

    Source

    A length, size or count is out of range.

  • Cutoff§

    Source

    A cutoff or band edge outside (0, fs/2), or edges out of order.

  • Unstable§

    Source

    A filter with a pole outside the unit circle: its output grows without bound.

  • Any other argument with no valid value.

Trait implementations 2
  • impl Display for SignalError
  • impl Error for SignalError

Traits

SamplesSource

pub trait Samples

A signal the FFT functions take: a real or complex Vector or List, of f64 or f32. Real input becomes complex with a zero imaginary part; f32 widens to f64.

  • fn to_split(self) -> (List<f64>, List<f64>)§

    Source

    The real and imaginary parts as two lists of f64.

RealSamplesSource

pub trait RealSamples

A real signal: anything that reads as a vector of f64 (linalg::AsVector<f64>): a Vector or List of f64, f32, i64, i32 or usize, a fixed array, an i64 range.

nabi
let xs: List<i64> = [1, 2, 3];
let a = try signal::convolve(xs, [1.0, 1.0]);
let b = try signal::convolve(1..4, [1f32, 1f32]);
assert(a == b && a.to_list() == [1.0, 3.0, 5.0, 3.0]);
  • fn to_reals(self) -> List<f64>§

    Source

    The samples as a new list of f64.

Functions

complexSource

pub fn complex<const N: usize>(x: Array<f64, N>) -> Array<Complex<f64>, N>

x as a complex array with zero imaginary parts.

nabi
use core::array::Vector;

let x: Vector<f64> = [1, 2];
println(signal::complex(x)); // [Complex { re: 1.0, im: 0.0 }, Complex { re: 2.0, im: 0.0 }]

absSource

pub fn abs<const N: usize>(x: Array<Complex<f64>, N>) -> Array<f64, N>

The modulus of each element: |z|.

realSource

pub fn real<const N: usize>(x: Array<Complex<f64>, N>) -> Array<f64, N>

The real part of each element.

imagSource

pub fn imag<const N: usize>(x: Array<Complex<f64>, N>) -> Array<f64, N>

The imaginary part of each element.

angleSource

pub fn angle<const N: usize>(x: Array<Complex<f64>, N>) -> Array<f64, N>

The argument of each element, in (-pi, pi].