signal
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.
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}");
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.
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}"); }
}
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.
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");
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.
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}");
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.
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");
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.
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));
[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::stftandspectral::spectrogram, the Hilbert transform (spectral::hilbert), resampling (filter::resample).
Modules
convConvolution and correlation, 1-d and 2-d, direct or by FFT.fftDiscrete Fourier transforms of any length: complex, real, n-d, the frequency helpers and the cosine and sine transforms built on them.filterDigital filters: FIR and IIR design, filtering (causal and zero-phase), frequency response, resampling and detrending.opsConvolution and correlation as operators:a ⊛ b(U+229B, circled asterisk) is the full linear convolution anda ⋆ b(U+22C6, star operator) the full cross-correlation, both at the level of*.peaksPeak finding as SciPy'sfind_peaks: local maxima (a flat top counts once, at its middle), then filtered by height, by distance (highest first) and by topographic prominence.spectralSpectral estimation: periodograms averaged over segments (Welch), the short-time Fourier transform and its inverse, spectrograms, and the analytic signal.unitsNumber suffixes for frequencies and times, so a call reads like its spec sheet:butter(4, Band::Lowpass(100hz), fs: 8khz).windowWindow functions, as SciPy'sscipy.signal.windows: symmetric by default (for filter design);sym: falsegives the periodic form (for spectral analysis), the firstmpoints of them + 1window.
Re-exports
conv::{convolve, correlate, convolve2d, correlate2d, Mode, Method}Source
pub use conv::{convolve, correlate, convolve2d, correlate2d, Mode, Method}convolveThe convolution(a * v)[k] = sum_i a[i] v[k - i], cut tomode.correlateThe cross-correlationc[k] = sum_i a[i + k] v[i], as SciPy'scorrelate:convolve(a, v reversed), so inMode::Fulllag 0 is at indexv.len() - 1.convolve2dThe 2-d convolution ofaand kernelk, cut tomodealong both axes (as SciPy'sconvolve2dwith zero boundaries).correlate2dThe 2-d cross-correlation:convolve2dwithkflipped on both axes.ModeWhich part of the full convolution to return.MethodHow to compute:Autopicks 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}fftThe DFTX_k = sum_j x_j exp(-2 pi i j k / n)of a real or complex signal, cut or zero-padded tonsamples whennis given.ifftThe inverse DFTx_j = (1/n) sum_k X_k exp(2 pi i j k / n)(the1/nunderNorm::Backward), soifft(fft(x))isxto about1e-15relative.rfftBins0..=n/2of the DFT of a real signal: the rest are their conjugates.irfftThenreal samples whose non-negative bins arex(asrfftgives them);ndefaults to2 * (x.len() - 1).fftnThe N-d DFT ofxoveraxes(every axis by default), in the order given; an axis named twice is transformed twice.ifftnThe inverse offftnover the sameaxes.PlanA complex FFT of one length with its twiddles computed once: build it withPlan::new(n)and run it on many signals.RealPlanA real FFT of one length, reusable:forwardgives then / 2 + 1non-negative frequency bins,inversetakes them back.NormHow a transform is scaled:Backward(the default, as NumPy) leaves the forward transform unscaled and divides the inverse byn;Orthodivides both bysqrt(n), so the pair is unitary;Forwarddivides the forward transform byn.
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}BandThe pass band of a filter, edges in the units of the sampling ratefsthe design function takes (with the defaultfs = 2.0an edge of 1 is the Nyquist frequency, as SciPy).butterA Butterworth filter as second-order sections.cheby1A Chebyshev type I filter withrpdB of pass-band ripple, as second-order sections.cheby2A Chebyshev type II filterrsdB down in the stop band, as second-order sections.besselA Bessel filter (phase-normalized, as SciPy's default), as second-order sections: nearly constant group delay in the pass band.firwinA linear-phase FIR filter ofnumtapscoefficients forband(edges in units offs), windowed bywindow(Hamming by default).lfilterxfiltered byb(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).sosfiltxfiltered by the cascade of second-order sectionssos(rows[b0, b1, b2, a0, a1, a2]), from rest.filtfiltxfiltered forward and then backward: zero phase, the magnitude response squared, and no delay.sosfiltfiltfiltfiltfor second-order sections: the zero-phase way to run an IIR filter of any order.freqzThe responseH(e^jw) = b(e^jw) / a(e^jw)atnfrequencies from 0 up to (not including) Nyquist, or the whole circle withwhole.sosfreqzfreqzfor second-order sections: the product of the rows' responses.
peaks::{find_peaks, Peaks}Source
pub use peaks::{find_peaks, Peaks}find_peaksThe peaks ofx: samples higher than both neighbours (a flat top counts once, at its middle; the ends never count).PeaksThe peaksfind_peakskept, 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}welchWelch's power spectral density estimate ofxsampled atfs: segments ofnpersegsamples (256 by default, at most the signal length), overlapping bynoverlap(half by default), each detrended (Detrend::Constantby default,nonefor no detrending), windowed (periodic Hann by default) and zero-padded tonfft.periodogramThe periodogram ofx: one segment, the whole signal, no window by default.stftThe STFT ofx(as SciPy'sstft):nperseg / 2zeros added at each end and zeros at the end to fill the last segment, so every sample is covered; segments ofnperseg(256) overlapping bynoverlap(half), windowed by a periodic Hann window, each a real FFT ofnfftpoints scaled by1 / sum(window).istftThe signal back from its STFT (as SciPy'sistft): each column is inverse-transformed, windowed and overlap-added, divided by the summed squared window, and thenperseg / 2boundary samples are dropped.spectrogramThe spectrogram ofx(as SciPy'sspectrogram): power spectral density of each segment, by defaultnperseg256 samples of a Tukey(0.25) window overlapping by an eighth, each detrended.hilbertThe analytic signalx + i H(x)of a realx(Hthe Hilbert transform), zero-padded or cut tonsamples when given.
window::WindowSource
pub use window::WindowWindowA window by name, for the functions that take one (firwin,welch,stft, ...).
Enums
SignalErrorSource
pub enum SignalErrorWhat went wrong in a signal call. Every message names the
argument, the value it got and what to pass instead.
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`)
};
A length, size or count is out of range.
A cutoff or band edge outside
(0, fs/2), or edges out of order.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 SignalErrorimpl Error for SignalError
Traits
SamplesSource
pub trait SamplesA 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.
The real and imaginary parts as two lists of
f64.
RealSamplesSource
pub trait RealSamplesA 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.
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]);
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.
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].