1use crate::prelude::ErrorsJSL;
18
19#[derive(Clone, Copy, Debug, Default, PartialEq)]
21pub struct Bounds {
22 pub min: Option<f64>,
23 pub max: Option<f64>,
24}
25
26impl Bounds {
27 pub fn at_least(min: f64) -> Self {
29 Self { min: Some(min), max: None }
30 }
31 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#[derive(Clone, Copy, Debug, PartialEq)]
43pub struct PeakOptions {
44 pub height: Option<Bounds>,
46 pub threshold: Option<Bounds>,
48 pub distance: Option<f64>,
51 pub prominence: Option<Bounds>,
53 pub width: Option<Bounds>,
55 pub wlen: Option<f64>,
57 pub rel_height: f64,
59 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#[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#[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#[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
102pub 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}
127fn 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
136pub 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}
183pub 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}
232fn retain<T: Copy>(values: &mut Vec<T>, keep: &[bool]) {
236 let mut k = keep.iter();
237 values.retain(|_| *k.next().unwrap());
238}
239
240fn 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
266pub 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 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#[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 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}