Peak finding
| Problem | Find the peaks of a sampled signal that matter, ignoring the many small maxima made by noise, and measure their size and width |
| Devised by | Local-maximum detection and full width at half maximum are long-standing practice in spectroscopy and chromatography; prominence comes from topography; the combination used here is SciPy’s find_peaks (2018) |
| Accuracy | Exact: the same peaks, prominences, bases, widths and interpolated crossings as SciPy on every test case |
| Cost | for the local maxima and the height, threshold and distance criteria; prominence and width walk outwards from each peak, per peak in the worst case |
| Read first | Power spectra: periodogram, Welch, spectrogram and Lomb-Scargle |
| API | find_peaks, PeakOptions, Bounds, peak_prominences, peak_widths, local_maxima |
Overview
Spectra have lines, chromatograms have compounds, heartbeats have R-waves, and in every case the first task is to say where the peaks are. The definition looks easy: a sample larger than its two neighbours. On real data it is useless by itself, because noise turns every gentle slope into a staircase of tiny maxima. The test signal below has seven real peaks and 146 local maxima.
The way out is to describe each local maximum by how much it stands out, and keep only those that stand out enough. The most useful such description is the prominence: how far a peak rises above the higher of the two lowest points that separate it from taller terrain on either side. A noise spike on the flank of a large peak has a tiny prominence, however high it sits; an isolated small peak keeps its full height. With a prominence and a width, peaks can be selected by scale rather than by absolute level.
Where it is used
Finding meaningful peaks is the first step of much data analysis.
- Spectroscopy and chromatography. Peak positions and areas identify compounds and measure their quantity.
- Biomedical signals. R peaks of the ECG give heart rate; the same method finds steps in a gait signal.
- Vibration monitoring. Peaks in a spectrum indicate faults in rotating machinery.
- Prominence and width. Distinguishing real peaks from noise by how far they stand out.
History
Locating peaks and quoting their full width at half maximum (FWHM) has been routine in spectroscopy since the line shapes of atomic spectra were first measured, and the same vocabulary passed into chromatography, crystallography and signal processing. Prominence is borrowed from topography and mountaineering, where a summit’s prominence is its height above the lowest contour line that encloses it and no higher summit: Mont Blanc is prominent, a rock on its shoulder is not, although the rock is higher than most mountains.
The library follows the definitions of SciPy’s find_peaks, peak_prominences and peak_widths (added to SciPy in 2018), which combine
these ideas with simple criteria on height, neighbour threshold and horizontal distance, and measure widths at a chosen fraction of the
prominence rather than of the absolute height, so that a sloping baseline does not distort them.
The idea
Local maxima and plateaus
A sample is a local maximum if . Quantised signals often have flat tops, so a plateau of equal samples counts as one peak if the samples just outside it are lower, and its position is the middle sample (rounded down). In the plateau at indices 1–4 gives a peak at 2, index 6 is a peak, and the final plateau is not, because the signal ends without coming down. End samples are never peaks: there is no neighbour to compare with.
Height, threshold and distance
The three cheapest criteria look at one peak at a time, or at pairs:
- Height keeps peaks whose value lies in a range. It fails when the baseline moves, as it does in most spectra.
- Threshold keeps peaks that rise by at least a given amount above both neighbours. It measures steepness at the top, so it rejects rounded peaks and keeps sharp noise.
- Distance keeps peaks at least samples apart. Peaks are visited from the tallest down; each kept peak removes every lower peak within samples of it. It suppresses the spikes on a peak’s flanks but needs to know the spacing in advance.
Prominence
For a peak at , walk left while the signal is not higher than , and record the lowest value passed, ; stop at the first higher sample or at the start. Do the same to the right for . The higher of the two is the key col (the saddle to cross to reach higher ground), and
The positions of the two minima are the peak’s bases. Take . The peak 5 at index 2: to the left the
walk reaches the start with minimum 0; to the right it passes 2, 1 and 4 (none above 5) and stops at 8, the first higher sample; the lowest value it passed is
1, at index 4. The key col is and the prominence is . The peak 8 at index 6 is the highest, so
both walks reach the ends, with minima 0 and 0, and its prominence is 8. A window of length wlen centred on the peak can limit the
walks, which speeds up long signals and measures prominence locally (relative to nearby terrain only).
Figure 15.9. Peaks selected by prominence.
The orange dots are all 146 local maxima. The blue dots are those with prominence at least 0.25, with each prominence drawn as a vertical line from the peak down to its key col; the horizontal lines are the widths at half prominence. The large peak near 260 has many local maxima on its flanks, all with small prominence, because each is walled in by the peak itself.
Width
The width is measured at a height a fraction rel_height of the prominence below the peak:
From the peak, walk outwards on each side (no further than the bases) to the first sample below , and interpolate linearly between it
and the sample before to find where the signal crosses . The width is the distance between the two crossings, in samples, and can be
fractional. For the triangle the prominence is 4, half of it gives , the crossings are at indices 2 and 6,
and the width is 4. With rel_height this is the full width at half prominence, which equals the classical FWHM when the baseline
is flat; with rel_height it is the width at the key col.
Choosing criteria
On the test signal, with seven true peaks:
Table 15.8. Peaks kept by each criterion on the test signal, and how many of the seven true peaks they include.
| criterion | peaks found | true peaks found (within 3 samples) |
|---|---|---|
| none (every local maximum) | 146 | 7 of 7 |
| height ≥ 0.3 | 46 | 7 of 7 |
| threshold ≥ 0.02 | 106 | 5 of 7 |
| distance ≥ 20 | 20 | 7 of 7 |
| prominence ≥ 0.25 | 9 | 7 of 7 |
| prominence ≥ 0.25, width ≥ 4 | 7 | 7 of 7 |
Height leaves dozens of noise maxima on the tall peaks; threshold loses true peaks with rounded tops and keeps sharp noise; distance needs the spacing, which here is uneven (two true peaks are only 25 samples apart). Prominence alone finds every true peak with two extras, and adding a minimum width removes those two narrow noise features. In practice, prominence is the first criterion to try, and width the second.
Algorithm
find_peaks:
- Find the local maxima and plateau edges in one pass.
- Apply the criteria in this order, each removing peaks (and their already computed properties): plateau size, height, threshold, distance, prominence, width.
- For distance, sort the remaining peaks by height; from the tallest down, unless it has been removed, remove every peak closer than samples on either side.
- Compute prominences (with bases) if prominence or width is requested; select by prominence.
- Compute widths at
rel_heightfrom the prominences and bases; select by width. - Return the indices and every property that was computed.
peak_prominences, for each peak: walk left and right while not above the peak (within the window if wlen is given), tracking the
minimum and its position; the prominence is the peak minus the larger minimum.
peak_widths, for each peak: compute , walk left until the signal is not above or the left base is reached, interpolate the crossing;
the same to the right; subtract.
Implementation
Local maxima, with plateaus:
/// Local maxima of `x`, with the left and right edges of each plateau. A flat run counts once,
/// at its middle sample (rounded down), when the samples on both sides of it are lower. The end
/// samples are never peaks.
pub fn local_maxima(x: &[f64]) -> (Vec<usize>, Vec<usize>, Vec<usize>) {
let (mut peaks, mut left, mut right) = (Vec::new(), Vec::new(), Vec::new());
let n = x.len();
let mut i = 1;
while i + 1 < n {
if x[i - 1] < x[i] {
let mut ahead = i + 1;
while ahead + 1 < n && x[ahead] == x[i] {
ahead += 1;
}
if x[ahead] < x[i] {
left.push(i);
right.push(ahead - 1);
peaks.push((i + ahead - 1) / 2);
i = ahead;
}
}
i += 1;
}
(peaks, left, right)
}
Prominence:
/// The prominence of each peak (SciPy's `peak_prominences`).
///
/// From the peak, walk left while the signal stays at or below the peak, and record the lowest
/// value passed; do the same to the right. The walk stops at a higher sample or at the edge of
/// the window `wlen` centred on the peak. The higher of the two minima is the *key col*, and the
/// prominence is the peak's height above it.
pub fn peak_prominences(x: &[f64], peaks: &[usize], wlen: Option<f64>) -> Result<Prominences, ErrorsJSL> {
check_signal(x)?;
if peaks.iter().any(|&p| p >= x.len()) {
return Err(ErrorsJSL::InvalidInputRange("peak index out of range"));
}
let half = match wlen {
None => None,
Some(w) if w.ceil() > 1.0 => Some(w.ceil() as usize / 2),
Some(_) => return Err(ErrorsJSL::InvalidInputRange("wlen must be larger than 1")),
};
let mut out = Prominences::default();
for &peak in peaks {
let (i_min, i_max) = match half {
Some(h) => (peak.saturating_sub(h), (peak + h).min(x.len() - 1)),
None => (0, x.len() - 1),
};
let (mut left_base, mut left_min) = (peak, x[peak]);
let mut i = peak as isize;
while i >= i_min as isize && x[i as usize] <= x[peak] {
if x[i as usize] < left_min {
left_min = x[i as usize];
left_base = i as usize;
}
i -= 1;
}
let (mut right_base, mut right_min) = (peak, x[peak]);
let mut i = peak;
while i <= i_max && x[i] <= x[peak] {
if x[i] < right_min {
right_min = x[i];
right_base = i;
}
i += 1;
}
out.prominences.push(x[peak] - left_min.max(right_min));
out.left_bases.push(left_base);
out.right_bases.push(right_base);
}
Ok(out)
}
Width:
/// The width of each peak at `rel_height` of its prominence below the summit (SciPy's
/// `peak_widths`): from the peak, walk outwards until the signal drops below that height (or a
/// base is reached), and interpolate linearly between the two samples that straddle it.
/// `rel_height = 0.5` gives the full width at half prominence; `1.0` the width at the key col.
pub fn peak_widths(x: &[f64], peaks: &[usize], rel_height: f64, prominence: Option<&Prominences>) -> Result<Widths, ErrorsJSL> {
if !(rel_height >= 0.0) {
return Err(ErrorsJSL::InvalidInputRange("rel_height must be at least 0"));
}
let computed;
let p = match prominence {
Some(p) => p,
None => {
computed = peak_prominences(x, peaks, None)?;
&computed
}
};
if p.prominences.len() != peaks.len() {
return Err(ErrorsJSL::IncompatibleArraySizes((p.prominences.len(), peaks.len())));
}
let mut out = Widths::default();
for (k, &peak) in peaks.iter().enumerate() {
let (i_min, i_max) = (p.left_bases[k], p.right_bases[k]);
let height = x[peak] - p.prominences[k] * rel_height;
let mut i = peak;
while i_min < i && height < x[i] {
i -= 1;
}
let mut left = i as f64;
if x[i] < height {
left += (height - x[i]) / (x[i + 1] - x[i]);
}
let mut i = peak;
while i < i_max && height < x[i] {
i += 1;
}
let mut right = i as f64;
if x[i] < height {
right -= (height - x[i]) / (x[i - 1] - x[i]);
}
out.widths.push(right - left);
out.width_heights.push(height);
out.left_ips.push(left);
out.right_ips.push(right);
}
Ok(out)
}
- Criteria are given in a
PeakOptionsstruct, with ranges asBounds { min, max }(Bounds::at_least,Bounds::between);Nonedisables a criterion.rel_heightdefaults to 0.5. - The result holds the peak indices and, as
Options, each property that a criterion required: heights, thresholds, plateau sizes and edges, prominences with bases, widths with their heights and interpolated ends. - Peaks of equal height are resolved for the distance criterion from the right, as in SciPy.
- Signals must be finite; NaN has no ordering.
Timings on 100 000 samples:
Table 15.9. Time of find_peaks on 100 000 samples.
| find_peaks on 100 000 samples | time |
|---|---|
| local maxima only | 0.15 ms |
| with prominence | 2.14 ms |
| with prominence and width | 2.24 ms |
Prominence dominates the cost, because each walk continues until it meets higher ground, which for small peaks can be far away. A window
(wlen) bounds it.
In practice
//! Finding the lines of a noisy spectrum by prominence, and measuring their widths.
use lib_jsl_dsp::discrete::peaks::{Bounds, PeakOptions, find_peaks};
fn main() {
// Three Gaussian lines on a sloping baseline, plus a little deterministic "noise".
let x: Vec<f64> = (0..400)
.map(|i| {
let t = i as f64;
let line = |c: f64, h: f64, w: f64| h * (-0.5 * ((t - c) / w).powi(2)).exp();
line(80.0, 1.0, 4.0) + line(200.0, 0.4, 10.0) + line(300.0, 0.7, 3.0) + 0.001 * t + 0.03 * (1.7 * t).sin() * (0.31 * t).cos()
})
.collect();
let every = find_peaks(&x, &PeakOptions::default()).unwrap();
println!("local maxima: {}", every.indices.len());
let options = PeakOptions { prominence: Some(Bounds::at_least(0.2)), width: Some(Bounds::at_least(0.0)), ..Default::default() };
let peaks = find_peaks(&x, &options).unwrap();
let p = peaks.prominences.as_ref().unwrap();
let w = peaks.widths.as_ref().unwrap();
println!("peaks with prominence at least 0.2:");
for (k, &i) in peaks.indices.iter().enumerate() {
println!(
" at {i:3}: height {:.3}, prominence {:.3}, width at half prominence {:.1} samples",
x[i], p.prominences[k], w.widths[k]
);
}
}
local maxima: 111
peaks with prominence at least 0.2:
at 79: height 1.065, prominence 0.989, width at half prominence 9.5 samples
at 201: height 0.616, prominence 0.408, width at half prominence 21.5 samples
at 300: height 1.008, prominence 0.722, width at half prominence 7.2 samples
The three Gaussian lines have standard deviations 4, 10 and 3, so their FWHMs are , and samples. The narrow lines are measured accurately; the broad one comes out narrower, because the sloping baseline and the neighbouring lines lift its key col and so lower its prominence. Prominence measures height relative to the surroundings, not above an absolute zero.
Strengths
- Prominence separates real peaks from noise without a model of the baseline or the peak shape.
- Widths at a fraction of the prominence are insensitive to a slowly varying baseline.
- Every criterion is cheap and has an obvious meaning; the results match SciPy exactly.
Weaknesses
- The criteria need scales (a prominence, a width) chosen for the data; there is no automatic noise model.
- Overlapping peaks are not separated: the smaller one may have no local maximum at all. Fitting a sum of line shapes (least squares) does better.
- Peak positions are sample indices; sub-sample positions need interpolation, for example a parabola through the top three samples.
- Very noisy signals are best smoothed first, for example with a zero-phase low-pass filter, which does not move the peaks.
Exercises
- Find by hand the prominences and bases of every peak of .
- Show that the prominence of the highest peak of a signal is its height above the higher of the two end minima, and that every other peak’s prominence is less than its height above the global minimum.
- For a Gaussian on a flat baseline, show that the width at
rel_heightis , and check the value 2.355σ at . - Give a signal on which the distance criterion keeps a different set of peaks depending on whether equal heights are visited from the left or from the right.
- Smooth the test signal of the figure above with
sosfiltfiltbefore finding peaks, and compare the number of local maxima and the prominence needed to isolate the seven true peaks. What happens if you use a one-pass filter instead?
Hints and answers
- The peaks are 4 (index 1), 6 (index 3) and 5 (index 5). Peak 4: the left walk reaches the start (minimum 1), the right walk stops at 6 having passed 2, so the prominence is , bases 0 and 2. Peak 6 is the highest: minima 1 (left) and 0 (right), prominence . Peak 5: the left walk stops at 6 having passed 3, the right reaches the end with minimum 0, prominence .
- Neither walk from the highest peak ever stops early, so its minima are those of the two halves of the signal. For any other peak, at least one walk stops at higher ground, and each minimum is at least the global minimum.
- Solve for and double it. At , .
- Take two equal peaks closer than , such as with : only one survives, and which one depends on the visiting order. The library, like SciPy, keeps the right-hand one.
- Smoothing removes most of the noise maxima, so far fewer local maxima remain and a smaller prominence suffices. A zero-phase filter leaves the peaks in place; a one-pass filter shifts them all by its group delay (and the shift differs between narrow and broad peaks).
Further reading
- SciPy documentation,
scipy.signal.find_peaks,peak_prominencesandpeak_widths: definitions of every criterion and property. - E. Kirmse and J. de Ferranti, “Calculating the prominence and isolation of every mountain in the world”, Progress in Physical Geography 41 (2017) 788–802: prominence in its original, topographic setting.
- J. M. Chalmers and P. R. Griffiths (eds.), Handbook of Vibrational Spectroscopy, Wiley, 2002: peak picking, widths and baseline handling in spectroscopy.