crisol_plot_core/
analysis.rs1#![allow(clippy::needless_range_loop)]
2
3use std::ops::Range;
10
11mod fit;
12
13#[derive(Clone, Copy, Debug, PartialEq)]
15pub struct Peak {
16 pub index: usize,
18 pub value: f64,
20}
21
22pub 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
48pub 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
65pub 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
73fn 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
127pub 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
148pub 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
171pub 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
189pub 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#[derive(Clone, Copy, Debug, Default, PartialEq)]
203pub struct Complex {
204 pub re: f64,
206 pub im: f64,
208}
209
210pub 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
259pub 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
281pub fn resample(values: &[f64], len: usize) -> Vec<f64> {
283 if len == 0 || values.is_empty() {
284 return Vec::new();
285 }
286 if len == 1 {
287 return vec![values[0]];
288 }
289 (0..len)
290 .map(|index| {
291 let position = index as f64 * (values.len() - 1) as f64 / (len - 1) as f64;
292 let low = position.floor() as usize;
293 let high = (low + 1).min(values.len() - 1);
294 let fraction = position - low as f64;
295 values[low] * (1.0 - fraction) + values[high] * fraction
296 })
297 .collect()
298}
299
300pub use fit::{Model, ModelFit, fit_model};
301
302#[derive(Clone, Copy, Debug, Default, PartialEq)]
304pub struct Statistics {
305 pub count: usize,
307 pub min: f64,
309 pub max: f64,
311 pub mean: f64,
313 pub stddev: f64,
315 pub median: f64,
317}
318
319impl Statistics {
320 pub fn of(values: &[f64]) -> Self {
322 let mut finite: Vec<f64> = values.iter().copied().filter(|value| value.is_finite()).collect();
323 if finite.is_empty() {
324 return Self::default();
325 }
326 finite.sort_by(f64::total_cmp);
327 let count = finite.len();
328 let mean = finite.iter().sum::<f64>() / count as f64;
329 let variance = finite.iter().map(|value| (value - mean).powi(2)).sum::<f64>() / count as f64;
330 let median = if count.is_multiple_of(2) {
331 (finite[count / 2 - 1] + finite[count / 2]) * 0.5
332 } else {
333 finite[count / 2]
334 };
335 Self {
336 count,
337 min: finite[0],
338 max: finite[count - 1],
339 mean,
340 stddev: variance.sqrt(),
341 median,
342 }
343 }
344
345 pub fn range(values: &[f64], range: Range<usize>) -> Self {
347 let start = range.start.min(values.len());
348 let end = range.end.min(values.len()).max(start);
349 Self::of(&values[start..end])
350 }
351}
352
353fn factorial(value: usize) -> u64 {
354 (1..=value as u64).product::<u64>().max(1)
355}
356
357#[cfg(test)]
358mod tests;