Skip to main content

lib_jsl_dsp/discrete/
peaks.rs

1//! Peak finding in one-dimensional signals: local maxima selected by height, threshold, distance,
2//! prominence and width, following SciPy's `find_peaks`, `peak_prominences` and `peak_widths`.
3//!
4//! A *peak* is a sample (or a flat run of samples, a *plateau*) larger than its neighbours on both
5//! sides. Real signals have many such points, most of them noise, so peaks are filtered by
6//! properties that describe how much they stand out:
7//!
8//! - **height**: the value itself;
9//! - **threshold**: the drop to the immediate neighbours;
10//! - **distance**: the gap to a taller peak (the shorter of two close peaks is removed);
11//! - **prominence**: how far the peak rises above the higher of the two lowest points that
12//!   separate it from taller terrain on each side (the topographic prominence of a mountain);
13//! - **width**: the peak's width at a given fraction of its prominence below the summit.
14//!
15//! See the book entry [Peak finding](https://jwkunz.github.io/lib_jsl/book/spectral/peaks.html).
16
17use crate::prelude::ErrorsJSL;
18
19/// An inclusive range `[min, max]`; either end may be open.
20#[derive(Clone, Copy, Debug, Default, PartialEq)]
21pub struct Bounds {
22    pub min: Option<f64>,
23    pub max: Option<f64>,
24}
25
26impl Bounds {
27    /// Values at least `min`.
28    pub fn at_least(min: f64) -> Self {
29        Self { min: Some(min), max: None }
30    }
31    /// Values in `[min, max]`.
32    pub fn between(min: f64, max: f64) -> Self {
33        Self { min: Some(min), max: Some(max) }
34    }
35    fn contains(&self, v: f64) -> bool {
36        self.min.is_none_or(|m| m <= v) && self.max.is_none_or(|m| v <= m)
37    }
38}
39
40/// The selection criteria of [`find_peaks`]; `None` disables a criterion. The defaults select
41/// every local maximum.
42#[derive(Clone, Copy, Debug, PartialEq)]
43pub struct PeakOptions {
44    /// Required peak value.
45    pub height: Option<Bounds>,
46    /// Required vertical drop to the neighbouring samples (both sides).
47    pub threshold: Option<Bounds>,
48    /// Minimum horizontal distance in samples to the nearest kept peak; of two closer peaks the
49    /// lower one is removed.
50    pub distance: Option<f64>,
51    /// Required prominence.
52    pub prominence: Option<Bounds>,
53    /// Required width in samples, measured at `rel_height` of the prominence.
54    pub width: Option<Bounds>,
55    /// Window length in samples that limits the search for a peak's bases (prominence).
56    pub wlen: Option<f64>,
57    /// Where the width is measured, as a fraction of the prominence below the peak (default 0.5).
58    pub rel_height: f64,
59    /// Required plateau length in samples.
60    pub plateau_size: Option<Bounds>,
61}
62
63impl Default for PeakOptions {
64    fn default() -> Self {
65        Self { height: None, threshold: None, distance: None, prominence: None, width: None, wlen: None, rel_height: 0.5, plateau_size: None }
66    }
67}
68
69/// Prominences of peaks and the bases they were measured from.
70#[derive(Clone, Debug, Default, PartialEq)]
71pub struct Prominences {
72    pub prominences: Vec<f64>,
73    pub left_bases: Vec<usize>,
74    pub right_bases: Vec<usize>,
75}
76
77/// Widths of peaks: the width, the height at which it was measured, and the interpolated
78/// positions of its left and right ends.
79#[derive(Clone, Debug, Default, PartialEq)]
80pub struct Widths {
81    pub widths: Vec<f64>,
82    pub width_heights: Vec<f64>,
83    pub left_ips: Vec<f64>,
84    pub right_ips: Vec<f64>,
85}
86
87/// The result of [`find_peaks`]: the indices of the peaks, and the properties computed while
88/// selecting them (only those the options required, as in SciPy).
89#[derive(Clone, Debug, Default, PartialEq)]
90pub struct Peaks {
91    pub indices: Vec<usize>,
92    pub peak_heights: Option<Vec<f64>>,
93    pub left_thresholds: Option<Vec<f64>>,
94    pub right_thresholds: Option<Vec<f64>>,
95    pub plateau_sizes: Option<Vec<usize>>,
96    pub left_edges: Option<Vec<usize>>,
97    pub right_edges: Option<Vec<usize>>,
98    pub prominences: Option<Prominences>,
99    pub widths: Option<Widths>,
100}
101
102// ANCHOR: local_maxima
103/// Local maxima of `x`, with the left and right edges of each plateau. A flat run counts once,
104/// at its middle sample (rounded down), when the samples on both sides of it are lower. The end
105/// samples are never peaks.
106pub fn local_maxima(x: &[f64]) -> (Vec<usize>, Vec<usize>, Vec<usize>) {
107    let (mut peaks, mut left, mut right) = (Vec::new(), Vec::new(), Vec::new());
108    let n = x.len();
109    let mut i = 1;
110    while i + 1 < n {
111        if x[i - 1] < x[i] {
112            let mut ahead = i + 1;
113            while ahead + 1 < n && x[ahead] == x[i] {
114                ahead += 1;
115            }
116            if x[ahead] < x[i] {
117                left.push(i);
118                right.push(ahead - 1);
119                peaks.push((i + ahead - 1) / 2);
120                i = ahead;
121            }
122        }
123        i += 1;
124    }
125    (peaks, left, right)
126}
127// ANCHOR_END: local_maxima
128
129fn check_signal(x: &[f64]) -> Result<(), ErrorsJSL> {
130    if x.iter().any(|v| !v.is_finite()) {
131        return Err(ErrorsJSL::InvalidInputRange("the signal must be finite"));
132    }
133    Ok(())
134}
135
136// ANCHOR: peak_prominences
137/// The prominence of each peak (SciPy's `peak_prominences`).
138///
139/// From the peak, walk left while the signal stays at or below the peak, and record the lowest
140/// value passed; do the same to the right. The walk stops at a higher sample or at the edge of
141/// the window `wlen` centred on the peak. The higher of the two minima is the *key col*, and the
142/// prominence is the peak's height above it.
143pub fn peak_prominences(x: &[f64], peaks: &[usize], wlen: Option<f64>) -> Result<Prominences, ErrorsJSL> {
144    check_signal(x)?;
145    if peaks.iter().any(|&p| p >= x.len()) {
146        return Err(ErrorsJSL::InvalidInputRange("peak index out of range"));
147    }
148    let half = match wlen {
149        None => None,
150        Some(w) if w.ceil() > 1.0 => Some(w.ceil() as usize / 2),
151        Some(_) => return Err(ErrorsJSL::InvalidInputRange("wlen must be larger than 1")),
152    };
153    let mut out = Prominences::default();
154    for &peak in peaks {
155        let (i_min, i_max) = match half {
156            Some(h) => (peak.saturating_sub(h), (peak + h).min(x.len() - 1)),
157            None => (0, x.len() - 1),
158        };
159        let (mut left_base, mut left_min) = (peak, x[peak]);
160        let mut i = peak as isize;
161        while i >= i_min as isize && x[i as usize] <= x[peak] {
162            if x[i as usize] < left_min {
163                left_min = x[i as usize];
164                left_base = i as usize;
165            }
166            i -= 1;
167        }
168        let (mut right_base, mut right_min) = (peak, x[peak]);
169        let mut i = peak;
170        while i <= i_max && x[i] <= x[peak] {
171            if x[i] < right_min {
172                right_min = x[i];
173                right_base = i;
174            }
175            i += 1;
176        }
177        out.prominences.push(x[peak] - left_min.max(right_min));
178        out.left_bases.push(left_base);
179        out.right_bases.push(right_base);
180    }
181    Ok(out)
182}
183// ANCHOR_END: peak_prominences
184
185// ANCHOR: peak_widths
186/// The width of each peak at `rel_height` of its prominence below the summit (SciPy's
187/// `peak_widths`): from the peak, walk outwards until the signal drops below that height (or a
188/// base is reached), and interpolate linearly between the two samples that straddle it.
189/// `rel_height = 0.5` gives the full width at half prominence; `1.0` the width at the key col.
190pub fn peak_widths(x: &[f64], peaks: &[usize], rel_height: f64, prominence: Option<&Prominences>) -> Result<Widths, ErrorsJSL> {
191    if !(rel_height >= 0.0) {
192        return Err(ErrorsJSL::InvalidInputRange("rel_height must be at least 0"));
193    }
194    let computed;
195    let p = match prominence {
196        Some(p) => p,
197        None => {
198            computed = peak_prominences(x, peaks, None)?;
199            &computed
200        }
201    };
202    if p.prominences.len() != peaks.len() {
203        return Err(ErrorsJSL::IncompatibleArraySizes((p.prominences.len(), peaks.len())));
204    }
205    let mut out = Widths::default();
206    for (k, &peak) in peaks.iter().enumerate() {
207        let (i_min, i_max) = (p.left_bases[k], p.right_bases[k]);
208        let height = x[peak] - p.prominences[k] * rel_height;
209        let mut i = peak;
210        while i_min < i && height < x[i] {
211            i -= 1;
212        }
213        let mut left = i as f64;
214        if x[i] < height {
215            left += (height - x[i]) / (x[i + 1] - x[i]);
216        }
217        let mut i = peak;
218        while i < i_max && height < x[i] {
219            i += 1;
220        }
221        let mut right = i as f64;
222        if x[i] < height {
223            right -= (height - x[i]) / (x[i - 1] - x[i]);
224        }
225        out.widths.push(right - left);
226        out.width_heights.push(height);
227        out.left_ips.push(left);
228        out.right_ips.push(right);
229    }
230    Ok(out)
231}
232// ANCHOR_END: peak_widths
233
234/// Keeps the entries of `values` where `keep` is true.
235fn retain<T: Copy>(values: &mut Vec<T>, keep: &[bool]) {
236    let mut k = keep.iter();
237    values.retain(|_| *k.next().unwrap());
238}
239
240/// Peaks of `x` at least `distance` samples apart, removing lower peaks first (SciPy's
241/// `_select_by_peak_distance`). Peaks of equal height are taken from the right.
242fn select_by_distance(peaks: &[usize], x: &[f64], distance: f64) -> Vec<bool> {
243    let distance = distance.ceil() as usize;
244    let n = peaks.len();
245    let mut keep = vec![true; n];
246    let mut order: Vec<usize> = (0..n).collect();
247    order.sort_by(|&a, &b| x[peaks[a]].total_cmp(&x[peaks[b]]));
248    for &j in order.iter().rev() {
249        if !keep[j] {
250            continue;
251        }
252        let mut k = j;
253        while k > 0 && peaks[j] - peaks[k - 1] < distance {
254            keep[k - 1] = false;
255            k -= 1;
256        }
257        let mut k = j + 1;
258        while k < n && peaks[k] - peaks[j] < distance {
259            keep[k] = false;
260            k += 1;
261        }
262    }
263    keep
264}
265
266// ANCHOR: find_peaks
267/// The peaks of `x` that satisfy the criteria in `options` (SciPy's `find_peaks`).
268///
269/// Candidates are the local maxima ([`local_maxima`]). The criteria are applied in SciPy's order,
270/// cheapest first: plateau size, height, threshold, distance, prominence, width. The distance
271/// criterion removes peaks, so prominences and widths are computed only for the survivors.
272pub fn find_peaks(x: &[f64], options: &PeakOptions) -> Result<Peaks, ErrorsJSL> {
273    check_signal(x)?;
274    if options.distance.is_some_and(|d| !(d >= 1.0)) {
275        return Err(ErrorsJSL::InvalidInputRange("distance must be at least 1"));
276    }
277    let (mut peaks, mut left_edges, mut right_edges) = local_maxima(x);
278    let mut result = Peaks::default();
279
280    if let Some(bounds) = options.plateau_size {
281        let sizes: Vec<usize> = left_edges.iter().zip(&right_edges).map(|(l, r)| r - l + 1).collect();
282        let keep: Vec<bool> = sizes.iter().map(|&s| bounds.contains(s as f64)).collect();
283        let mut sizes = sizes;
284        for v in [&mut peaks, &mut left_edges, &mut right_edges] {
285            retain(v, &keep);
286        }
287        retain(&mut sizes, &keep);
288        result.plateau_sizes = Some(sizes);
289    }
290
291    // Each later criterion filters the peaks and every property already computed.
292    let mut heights: Option<Vec<f64>> = None;
293    let mut thresholds: Option<(Vec<f64>, Vec<f64>)> = None;
294    let apply = |keep: &[bool], peaks: &mut Vec<usize>, le: &mut Vec<usize>, re: &mut Vec<usize>, result: &mut Peaks, heights: &mut Option<Vec<f64>>, thresholds: &mut Option<(Vec<f64>, Vec<f64>)>| {
295        retain(peaks, keep);
296        retain(le, keep);
297        retain(re, keep);
298        if let Some(s) = result.plateau_sizes.as_mut() {
299            retain(s, keep);
300        }
301        if let Some(h) = heights.as_mut() {
302            retain(h, keep);
303        }
304        if let Some((l, r)) = thresholds.as_mut() {
305            retain(l, keep);
306            retain(r, keep);
307        }
308    };
309
310    if let Some(bounds) = options.height {
311        let h: Vec<f64> = peaks.iter().map(|&p| x[p]).collect();
312        let keep: Vec<bool> = h.iter().map(|&v| bounds.contains(v)).collect();
313        heights = Some(h);
314        apply(&keep, &mut peaks, &mut left_edges, &mut right_edges, &mut result, &mut heights, &mut thresholds);
315    }
316
317    if let Some(bounds) = options.threshold {
318        let l: Vec<f64> = peaks.iter().map(|&p| x[p] - x[p - 1]).collect();
319        let r: Vec<f64> = peaks.iter().map(|&p| x[p] - x[p + 1]).collect();
320        let keep: Vec<bool> = l
321            .iter()
322            .zip(&r)
323            .map(|(&a, &b)| bounds.min.is_none_or(|m| m <= a.min(b)) && bounds.max.is_none_or(|m| a.max(b) <= m))
324            .collect();
325        thresholds = Some((l, r));
326        apply(&keep, &mut peaks, &mut left_edges, &mut right_edges, &mut result, &mut heights, &mut thresholds);
327    }
328
329    if let Some(d) = options.distance {
330        let keep = select_by_distance(&peaks, x, d);
331        apply(&keep, &mut peaks, &mut left_edges, &mut right_edges, &mut result, &mut heights, &mut thresholds);
332    }
333
334    let mut prominences = None;
335    if options.prominence.is_some() || options.width.is_some() {
336        let mut p = peak_prominences(x, &peaks, options.wlen)?;
337        if let Some(bounds) = options.prominence {
338            let keep: Vec<bool> = p.prominences.iter().map(|&v| bounds.contains(v)).collect();
339            apply(&keep, &mut peaks, &mut left_edges, &mut right_edges, &mut result, &mut heights, &mut thresholds);
340            retain(&mut p.prominences, &keep);
341            retain(&mut p.left_bases, &keep);
342            retain(&mut p.right_bases, &keep);
343        }
344        prominences = Some(p);
345    }
346
347    if let Some(bounds) = options.width {
348        let p = prominences.as_mut().expect("computed above");
349        let mut w = peak_widths(x, &peaks, options.rel_height, Some(p))?;
350        let keep: Vec<bool> = w.widths.iter().map(|&v| bounds.contains(v)).collect();
351        apply(&keep, &mut peaks, &mut left_edges, &mut right_edges, &mut result, &mut heights, &mut thresholds);
352        retain(&mut p.prominences, &keep);
353        retain(&mut p.left_bases, &keep);
354        retain(&mut p.right_bases, &keep);
355        retain(&mut w.widths, &keep);
356        retain(&mut w.width_heights, &keep);
357        retain(&mut w.left_ips, &keep);
358        retain(&mut w.right_ips, &keep);
359        result.widths = Some(w);
360    }
361
362    if options.plateau_size.is_some() {
363        result.left_edges = Some(left_edges);
364        result.right_edges = Some(right_edges);
365    }
366    result.peak_heights = heights;
367    if let Some((l, r)) = thresholds {
368        result.left_thresholds = Some(l);
369        result.right_thresholds = Some(r);
370    }
371    result.prominences = prominences;
372    result.indices = peaks;
373    Ok(result)
374}
375// ANCHOR_END: find_peaks
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    #[test]
382    fn plateaus_count_once_at_their_middle() {
383        let x = [0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 2.0, 0.0, 3.0, 3.0];
384        let (p, l, r) = local_maxima(&x);
385        assert_eq!(p, vec![2, 6]);
386        assert_eq!(l, vec![1, 6]);
387        assert_eq!(r, vec![4, 6]);
388    }
389
390    #[test]
391    fn prominence_is_height_above_the_higher_col() {
392        // Two summits: 5 at index 2 and 8 at index 6, separated by a col at 1.
393        let x = [0.0, 3.0, 5.0, 2.0, 1.0, 4.0, 8.0, 2.0, 0.0];
394        let p = peak_prominences(&x, &[2, 6], None).unwrap();
395        assert_eq!(p.prominences, vec![4.0, 8.0]);
396        assert_eq!(p.left_bases, vec![0, 0]);
397        assert_eq!(p.right_bases, vec![4, 8]);
398    }
399
400    #[test]
401    fn half_prominence_width_of_a_triangle() {
402        let x = [0.0, 1.0, 2.0, 3.0, 4.0, 3.0, 2.0, 1.0, 0.0];
403        let w = peak_widths(&x, &[4], 0.5, None).unwrap();
404        assert!((w.widths[0] - 4.0).abs() < 1e-15);
405        assert_eq!(w.width_heights, vec![2.0]);
406    }
407
408    #[test]
409    fn distance_keeps_the_taller_of_close_peaks() {
410        let x = [0.0, 2.0, 0.0, 3.0, 0.0, 1.0, 0.0];
411        let all = find_peaks(&x, &PeakOptions::default()).unwrap();
412        assert_eq!(all.indices, vec![1, 3, 5]);
413        let spaced = find_peaks(&x, &PeakOptions { distance: Some(3.0), ..Default::default() }).unwrap();
414        assert_eq!(spaced.indices, vec![3]);
415        let tall = find_peaks(&x, &PeakOptions { height: Some(Bounds::at_least(1.5)), ..Default::default() }).unwrap();
416        assert_eq!(tall.indices, vec![1, 3]);
417        assert_eq!(tall.peak_heights, Some(vec![2.0, 3.0]));
418    }
419}