Skip to main content

crisol_plot_core/
analysis.rs

1#![allow(clippy::needless_range_loop)]
2
3//! Signal analysis helpers used by the plot UI and by applications directly.
4//!
5//! Every function is a pure transform over slices: peak detection, baseline removal,
6//! Savitzky–Golay smoothing/derivatives, integration, an FFT spectrum, resampling, a
7//! Gauss–Newton fit with confidence bands, and selection statistics.
8
9use std::ops::Range;
10
11mod fit;
12
13/// One detected peak: index and height.
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub struct Peak {
16    /// Sample index.
17    pub index: usize,
18    /// Sample value.
19    pub value: f64,
20}
21
22/// Detect local maxima above `min_height`, at least `min_distance` samples apart.
23pub fn find_peaks(values: &[f64], min_height: f64, min_distance: usize) -> Vec<Peak> {
24    let distance = min_distance.max(1);
25    let mut peaks: Vec<Peak> = Vec::new();
26    for index in 1..values.len().saturating_sub(1) {
27        let value = values[index];
28        if !value.is_finite() || value < min_height {
29            continue;
30        }
31        if value < values[index - 1] || value < values[index + 1] {
32            continue;
33        }
34        if let Some(last) = peaks.last()
35            && index - last.index < distance
36        {
37            if value > last.value {
38                peaks.pop();
39            } else {
40                continue;
41            }
42        }
43        peaks.push(Peak { index, value });
44    }
45    peaks
46}
47
48/// A rolling-minimum baseline. `window` is clamped to an odd number of samples.
49pub fn rolling_baseline(values: &[f64], window: usize) -> Vec<f64> {
50    let window = window.max(1) | 1;
51    let half = window / 2;
52    (0..values.len())
53        .map(|index| {
54            let start = index.saturating_sub(half);
55            let end = (index + half + 1).min(values.len());
56            values[start..end]
57                .iter()
58                .copied()
59                .filter(|value| value.is_finite())
60                .fold(f64::INFINITY, f64::min)
61        })
62        .collect()
63}
64
65/// Subtract a rolling baseline in place.
66pub fn remove_baseline(values: &mut [f64], window: usize) {
67    let baseline = rolling_baseline(values, window);
68    for (value, base) in values.iter_mut().zip(baseline) {
69        *value -= base;
70    }
71}
72
73/// Savitzky–Golay smoothing coefficients for the center of an odd window.
74fn savgol_coefficients(window: usize, order: usize, derivative: usize) -> Option<Vec<f64>> {
75    let window = window.max(1) | 1;
76    let order = order.min(window - 1);
77    let half = window / 2;
78    let size = order + 1;
79    if derivative > order {
80        return None;
81    }
82    let mut matrix = vec![vec![0.0; size + 1]; size];
83    for row in 0..size {
84        for column in 0..size {
85            let power = row + column;
86            matrix[row][column] = (-(half as i64)..=(half as i64))
87                .map(|offset| (offset as f64).powi(power as i32))
88                .sum();
89        }
90    }
91    matrix[derivative][size] = factorial(derivative) as f64;
92    for pivot in 0..size {
93        let mut best = pivot;
94        for row in pivot + 1..size {
95            if matrix[row][pivot].abs() > matrix[best][pivot].abs() {
96                best = row;
97            }
98        }
99        if matrix[best][pivot].abs() < 1e-12 {
100            return None;
101        }
102        matrix.swap(pivot, best);
103        let divisor = matrix[pivot][pivot];
104        for column in pivot..=size {
105            matrix[pivot][column] /= divisor;
106        }
107        for row in 0..size {
108            if row != pivot {
109                let factor = matrix[row][pivot];
110                for column in pivot..=size {
111                    matrix[row][column] -= factor * matrix[pivot][column];
112                }
113            }
114        }
115    }
116    let coefficients: Vec<f64> = (0..window)
117        .map(|index| {
118            let offset = index as i64 - half as i64;
119            (0..size)
120                .map(|power| matrix[power][size] * (offset as f64).powi(power as i32))
121                .sum()
122        })
123        .collect();
124    Some(coefficients)
125}
126
127/// Savitzky–Golay smoothing. Returns the same length; the edges are clamped.
128pub fn savgol(values: &[f64], window: usize, order: usize) -> Vec<f64> {
129    let Some(coefficients) = savgol_coefficients(window, order, 0) else {
130        return values.to_vec();
131    };
132    let half = coefficients.len() / 2;
133    (0..values.len())
134        .map(|index| {
135            coefficients
136                .iter()
137                .enumerate()
138                .map(|(offset, weight)| {
139                    let source = (index as i64 + offset as i64 - half as i64)
140                        .clamp(0, values.len().saturating_sub(1) as i64) as usize;
141                    values[source] * weight
142                })
143                .sum()
144        })
145        .collect()
146}
147
148/// Savitzky–Golay first derivative, per sample step.
149pub fn savgol_derivative(values: &[f64], window: usize, order: usize, step: f64) -> Vec<f64> {
150    let step = if step.abs() > f64::EPSILON { step } else { 1.0 };
151    let Some(coefficients) = savgol_coefficients(window, order, 1) else {
152        return vec![0.0; values.len()];
153    };
154    let half = coefficients.len() / 2;
155    (0..values.len())
156        .map(|index| {
157            coefficients
158                .iter()
159                .enumerate()
160                .map(|(offset, weight)| {
161                    let source = (index as i64 + offset as i64 - half as i64)
162                        .clamp(0, values.len().saturating_sub(1) as i64) as usize;
163                    values[source] * weight
164                })
165                .sum::<f64>()
166                / step
167        })
168        .collect()
169}
170
171/// Central-difference derivative; the ends use one-sided differences.
172pub fn derivative(values: &[f64], step: f64) -> Vec<f64> {
173    let step = if step.abs() > f64::EPSILON { step } else { 1.0 };
174    (0..values.len())
175        .map(|index| {
176            if values.len() < 2 {
177                0.0
178            } else if index == 0 {
179                (values[1] - values[0]) / step
180            } else if index + 1 == values.len() {
181                (values[index] - values[index - 1]) / step
182            } else {
183                (values[index + 1] - values[index - 1]) / (2.0 * step)
184            }
185        })
186        .collect()
187}
188
189/// Trapezoidal integral, with the running area at every sample.
190pub fn integral(values: &[f64], step: f64) -> Vec<f64> {
191    let mut out = Vec::with_capacity(values.len());
192    let mut total = 0.0;
193    out.push(0.0);
194    for window in values.windows(2) {
195        total += (window[0] + window[1]) * 0.5 * step;
196        out.push(total);
197    }
198    out
199}
200
201/// A complex sample for the FFT.
202#[derive(Clone, Copy, Debug, Default, PartialEq)]
203pub struct Complex {
204    /// Real part.
205    pub re: f64,
206    /// Imaginary part.
207    pub im: f64,
208}
209
210/// In-place radix-2 FFT. The length must be a power of two.
211pub fn fft(values: &mut [Complex]) {
212    let length = values.len();
213    if length <= 1 || !length.is_power_of_two() {
214        return;
215    }
216    let mut j = 0;
217    for i in 1..length {
218        let mut bit = length >> 1;
219        while j & bit != 0 {
220            j ^= bit;
221            bit >>= 1;
222        }
223        j ^= bit;
224        if i < j {
225            values.swap(i, j);
226        }
227    }
228    let mut size = 2;
229    while size <= length {
230        let angle = -std::f64::consts::TAU / size as f64;
231        let (sin, cos) = angle.sin_cos();
232        for start in (0..length).step_by(size) {
233            let mut w = Complex { re: 1.0, im: 0.0 };
234            for offset in 0..size / 2 {
235                let even = values[start + offset];
236                let odd = values[start + offset + size / 2];
237                let product = Complex {
238                    re: odd.re * w.re - odd.im * w.im,
239                    im: odd.re * w.im + odd.im * w.re,
240                };
241                values[start + offset] = Complex {
242                    re: even.re + product.re,
243                    im: even.im + product.im,
244                };
245                values[start + offset + size / 2] = Complex {
246                    re: even.re - product.re,
247                    im: even.im - product.im,
248                };
249                w = Complex {
250                    re: w.re * cos - w.im * sin,
251                    im: w.re * sin + w.im * cos,
252                };
253            }
254        }
255        size <<= 1;
256    }
257}
258
259/// A one-sided magnitude spectrum: `[frequency, magnitude]` up to Nyquist.
260pub fn spectrum(values: &[f64], sample_rate: f64) -> Vec<[f64; 2]> {
261    let mut length = 1;
262    while length * 2 <= values.len() {
263        length *= 2;
264    }
265    if length < 2 {
266        return Vec::new();
267    }
268    let mut buffer: Vec<Complex> = values[..length]
269        .iter()
270        .map(|value| Complex { re: *value, im: 0.0 })
271        .collect();
272    fft(&mut buffer);
273    (0..=length / 2)
274        .map(|index| {
275            let magnitude = buffer[index].re.hypot(buffer[index].im) / length as f64;
276            [index as f64 * sample_rate / length as f64, magnitude]
277        })
278        .collect()
279}
280
281/// A short-time Fourier transform: one magnitude spectrum per window.
282#[derive(Clone, Debug, Default, PartialEq)]
283pub struct Spectrogram {
284    /// Frequency of each column, in hertz.
285    pub frequencies: Vec<f64>,
286    /// Center time of each row, in seconds.
287    pub times: Vec<f64>,
288    /// Row-major magnitudes: `times.len() * frequencies.len()` values.
289    pub magnitudes: Vec<f64>,
290}
291
292impl Spectrogram {
293    /// The magnitude at `time` row and `frequency` column.
294    pub fn magnitude(&self, time: usize, frequency: usize) -> Option<f64> {
295        if frequency >= self.frequencies.len() {
296            return None;
297        }
298        self.magnitudes.get(time * self.frequencies.len() + frequency).copied()
299    }
300}
301
302/// Short-time Fourier transform with a Hann window.
303///
304/// `window` is rounded up to a power of two, `hop` defaults to half the window, and
305/// `sample_rate` is in hertz. Frames start at every `hop` samples and stop at the last
306/// complete window.
307pub fn spectrogram(values: &[f64], window: usize, hop: usize, sample_rate: f64) -> Spectrogram {
308    /// Largest FFT window: 64k samples keeps every intermediate bounded.
309    const MAX_WINDOW: usize = 1 << 16;
310    let window = window
311        .clamp(2, MAX_WINDOW)
312        .checked_next_power_of_two()
313        .unwrap_or(MAX_WINDOW);
314    let hop = hop.max(1);
315    if values.len() < window {
316        return Spectrogram::default();
317    }
318    let bins = window / 2 + 1;
319    let frequencies = (0..bins)
320        .map(|index| index as f64 * sample_rate / window as f64)
321        .collect();
322    let hann: Vec<f64> = (0..window)
323        .map(|index| {
324            let angle = std::f64::consts::TAU * index as f64 / (window - 1) as f64;
325            0.5 - 0.5 * angle.cos()
326        })
327        .collect();
328    let mut times = Vec::new();
329    let mut magnitudes = Vec::new();
330    let mut start = 0;
331    while start + window <= values.len() {
332        let mut buffer: Vec<Complex> = values[start..start + window]
333            .iter()
334            .zip(&hann)
335            .map(|(value, weight)| Complex {
336                re: value * weight,
337                im: 0.0,
338            })
339            .collect();
340        fft(&mut buffer);
341        for index in 0..bins {
342            magnitudes.push(buffer[index].re.hypot(buffer[index].im) / window as f64);
343        }
344        times.push((start as f64 + window as f64 * 0.5) / sample_rate);
345        start += hop;
346    }
347    Spectrogram {
348        frequencies,
349        times,
350        magnitudes,
351    }
352}
353
354/// Linear resampling to `len` samples.
355pub fn resample(values: &[f64], len: usize) -> Vec<f64> {
356    if len == 0 || values.is_empty() {
357        return Vec::new();
358    }
359    if len == 1 {
360        return vec![values[0]];
361    }
362    (0..len)
363        .map(|index| {
364            let position = index as f64 * (values.len() - 1) as f64 / (len - 1) as f64;
365            let low = position.floor() as usize;
366            let high = (low + 1).min(values.len() - 1);
367            let fraction = position - low as f64;
368            values[low] * (1.0 - fraction) + values[high] * fraction
369        })
370        .collect()
371}
372
373pub use fit::{Model, ModelFit, fit_model};
374
375/// Summary statistics of a selection.
376#[derive(Clone, Copy, Debug, Default, PartialEq)]
377pub struct Statistics {
378    /// Number of finite values.
379    pub count: usize,
380    /// Minimum.
381    pub min: f64,
382    /// Maximum.
383    pub max: f64,
384    /// Mean.
385    pub mean: f64,
386    /// Population standard deviation.
387    pub stddev: f64,
388    /// Median.
389    pub median: f64,
390}
391
392impl Statistics {
393    /// Statistics of a slice, ignoring non-finite values.
394    pub fn of(values: &[f64]) -> Self {
395        let mut finite: Vec<f64> = values.iter().copied().filter(|value| value.is_finite()).collect();
396        if finite.is_empty() {
397            return Self::default();
398        }
399        finite.sort_by(f64::total_cmp);
400        let count = finite.len();
401        let mean = finite.iter().sum::<f64>() / count as f64;
402        let variance = finite.iter().map(|value| (value - mean).powi(2)).sum::<f64>() / count as f64;
403        let median = if count.is_multiple_of(2) {
404            (finite[count / 2 - 1] + finite[count / 2]) * 0.5
405        } else {
406            finite[count / 2]
407        };
408        Self {
409            count,
410            min: finite[0],
411            max: finite[count - 1],
412            mean,
413            stddev: variance.sqrt(),
414            median,
415        }
416    }
417
418    /// Statistics of a slice of samples in `range`.
419    pub fn range(values: &[f64], range: Range<usize>) -> Self {
420        let start = range.start.min(values.len());
421        let end = range.end.min(values.len()).max(start);
422        Self::of(&values[start..end])
423    }
424}
425
426fn factorial(value: usize) -> u64 {
427    (1..=value as u64).product::<u64>().max(1)
428}
429
430#[cfg(test)]
431mod tests;