Skip to main content

lib_jsl_interpolation/one_d/
savitzky_golay.rs

1//! Savitzky-Golay smoothing and differentiation by local polynomial least squares.
2//!
3//! See the book entry [Savitzky-Golay smoothing](https://jwkunz.github.io/lib_jsl/book/interpolation/savitzky-golay.html).
4
5use lib_jsl_core::*;
6use ndarray::Array2;
7use lib_jsl_linalg::SVD;
8
9/// Convolution coefficients of a Savitzky-Golay filter.
10///
11/// `window` must be odd and greater than `order`. `deriv` selects the derivative (0 = smoothing)
12/// and `delta` is the sample spacing (needed for `deriv > 0`). The coefficients are ordered for
13/// correlation with the data centred on the middle tap (i.e. `y_smooth[i] = Σ c[k] y[i - m + k]`
14/// with `m = window / 2`).
15pub fn savitzky_golay_coefficients(window: usize, order: usize, deriv: usize, delta: f64) -> Result<Vec<f64>, ErrorsJSL> {
16    if window.is_multiple_of(2) || window <= order {
17        return Err(ErrorsJSL::InvalidInputRange("window must be odd and larger than the polynomial order"));
18    }
19    if deriv > order {
20        return Ok(vec![0.0; window]);
21    }
22    let m = window / 2;
23    // ANCHOR: savitzky_golay
24    // Least-squares polynomial in the scaled offset t = (i − m)/m ∈ [−1, 1]; the filter is row
25    // `deriv` of the pseudo-inverse, times deriv! / (m Δ)^deriv to undo the scaling.
26    let pinv = local_fit(window, order, m as f64, m.max(1) as f64)?;
27    let factorial: f64 = (1..=deriv).map(|k| k as f64).product();
28    let scale = factorial / (m.max(1) as f64 * delta).powi(deriv as i32);
29    Ok(pinv.row(deriv).iter().map(|&c| c * scale).collect())
30    // ANCHOR_END: savitzky_golay
31}
32
33/// The `(order + 1) × window` pseudo-inverse of the Vandermonde matrix `Aᵢⱼ = tᵢʲ` in the scaled
34/// variable `tᵢ = (i − centre) / width`, computed from an SVD: scaling keeps the Vandermonde
35/// matrix well conditioned, and the SVD avoids squaring its condition number as the normal
36/// equations would.
37fn local_fit(window: usize, order: usize, centre: f64, width: f64) -> Result<Array2<f64>, ErrorsJSL> {
38    let a = Array2::from_shape_fn((window, order + 1), |(i, j)| ((i as f64 - centre) / width).powi(j as i32));
39    let (u, sigma, vt) = a.svd(true, true).map_err(|_| ErrorsJSL::RuntimeError("SVD failed"))?;
40    let (u, vt) = (u.ok_or(ErrorsJSL::RuntimeError("SVD returned no U"))?, vt.ok_or(ErrorsJSL::RuntimeError("SVD returned no V"))?);
41    if sigma.iter().any(|&s| s <= sigma[0] * 1e-13) {
42        return Err(ErrorsJSL::RuntimeError("the local polynomial fit is numerically singular"));
43    }
44    // A⁺ = V Σ⁻¹ Uᵀ restricted to the order + 1 nonzero singular values.
45    Ok(Array2::from_shape_fn((order + 1, window), |(j, k)| (0..=order).map(|i| vt[[i, j]] * u[[k, i]] / sigma[i]).sum()))
46}
47
48/// Applies a Savitzky-Golay filter to `y`. Near the ends the polynomial fitted to the first/last
49/// `window` samples is evaluated (SciPy's `mode="interp"`), so the output has the input's length.
50/// Requires `y.len() >= window`.
51pub fn savitzky_golay(y: VR1D, window: usize, order: usize, deriv: usize, delta: f64) -> Result<R1D, ErrorsJSL> {
52    let n = y.len();
53    if n < window {
54        return Err(ErrorsJSL::IncompatibleArraySizes((n, window)));
55    }
56    let c = savitzky_golay_coefficients(window, order, deriv, delta)?;
57    let m = window / 2;
58    let mut out = R1D::zeros(n);
59    for i in m..n - m {
60        out[i] = (0..window).map(|k| c[k] * y[i + k - m]).sum();
61    }
62    // Edges: fit one polynomial (in the centred variable t = (i − start − h)/h ∈ [−1, 1], h half the
63    // window) to the first (last) window and evaluate it or its derivative there.
64    let h = (m.max(1)) as f64;
65    let pinv = local_fit(window, order, m as f64, h)?;
66    let fit_edge = |start: usize, out: &mut R1D, range: std::ops::Range<usize>| {
67        let coef = pinv.dot(&y.slice(ndarray::s![start..start + window]));
68        for i in range {
69            let t = (i as f64 - start as f64 - m as f64) / h;
70            // d-th derivative of Σ coef[j] t^j, with dt/dx = 1/(h Δ).
71            let mut v = 0.0;
72            for j in deriv..=order {
73                let falling: f64 = (0..deriv).map(|q| (j - q) as f64).product();
74                v += coef[j] * falling * t.powi((j - deriv) as i32);
75            }
76            out[i] = v / (h * delta).powi(deriv as i32);
77        }
78    };
79    fit_edge(0, &mut out, 0..m);
80    fit_edge(n - window, &mut out, n - m..n);
81    Ok(out)
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn classic_quadratic_five_point_coefficients() {
90        let c = savitzky_golay_coefficients(5, 2, 0, 1.0).unwrap();
91        let want = [-3.0 / 35.0, 12.0 / 35.0, 17.0 / 35.0, 12.0 / 35.0, -3.0 / 35.0];
92        for (a, b) in c.iter().zip(want) {
93            assert!((a - b).abs() < 1e-12);
94        }
95        // First-derivative coefficients of the same filter: (-2,-1,0,1,2)/10.
96        let d = savitzky_golay_coefficients(5, 2, 1, 1.0).unwrap();
97        for (a, b) in d.iter().zip([-0.2, -0.1, 0.0, 0.1, 0.2]) {
98            assert!((a - b).abs() < 1e-12);
99        }
100    }
101
102    #[test]
103    fn preserves_polynomials_and_their_derivatives() {
104        let n = 30;
105        let dt = 0.1;
106        let y = R1D::from_iter((0..n).map(|k| {
107            let t = k as f64 * dt;
108            1.0 - 2.0 * t + 0.5 * t * t + 0.25 * t * t * t
109        }));
110        let s = savitzky_golay(y.view(), 7, 3, 0, dt).unwrap();
111        let d = savitzky_golay(y.view(), 7, 3, 1, dt).unwrap();
112        let d2 = savitzky_golay(y.view(), 7, 3, 2, dt).unwrap();
113        for k in 0..n {
114            let t = k as f64 * dt;
115            assert!((s[k] - y[k]).abs() < 1e-9, "k={k}");
116            assert!((d[k] - (-2.0 + t + 0.75 * t * t)).abs() < 1e-8, "d k={k}");
117            assert!((d2[k] - (1.0 + 1.5 * t)).abs() < 1e-7, "d2 k={k}");
118        }
119    }
120
121    #[test]
122    fn rejects_even_window() {
123        assert!(savitzky_golay_coefficients(4, 2, 0, 1.0).is_err());
124    }
125
126    #[test]
127    fn wide_windows_and_high_orders_stay_exact() {
128        // The old normal-equations construction lost 9 digits at window 51, order 8, and failed
129        // as singular at window 101.
130        for (window, order) in [(11, 4), (51, 8), (101, 12)] {
131            let n = 300;
132            let p = |t: f64| (0..=order).map(|k| (t - 0.4).powi(k as i32)).sum::<f64>();
133            let y = R1D::from_vec((0..n).map(|i| p(i as f64 / n as f64)).collect());
134            let s = savitzky_golay(y.view(), window, order, 0, 1.0).unwrap();
135            let err = s.iter().zip(y.iter()).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
136            assert!(err < 1e-9, "window {window}, order {order}: {err:e}");
137            // The first derivative of the same polynomial, with spacing 1/n.
138            let d = savitzky_golay(y.view(), window, order, 1, 1.0 / n as f64).unwrap();
139            let dp = |t: f64| (1..=order).map(|k| k as f64 * (t - 0.4).powi(k as i32 - 1)).sum::<f64>();
140            let derr = d.iter().enumerate().map(|(i, v)| (v - dp(i as f64 / n as f64)).abs()).fold(0.0, f64::max);
141            assert!(derr < 1e-6, "derivative, window {window}, order {order}: {derr:e}");
142        }
143    }
144}