Skip to main content

lib_jsl_dsp/discrete/windows/
dpss.rs

1//! The discrete prolate spheroidal sequence (Slepian) window.
2//!
3//! See the book entry [Window functions](https://jwkunz.github.io/lib_jsl/book/spectral/windows.html#the-dolph-chebyshev-and-dpss-windows).
4
5use std::f64::consts::PI;
6
7use super::{extend, len_guard, truncate};
8
9/// The number of eigenvalues of the symmetric tridiagonal matrix (diagonal `d`, off-diagonal `e`)
10/// that are smaller than `x`, by Sturm's sign count of the `LDLᵀ` pivots of `T − xI`.
11fn count_below(d: &[f64], e: &[f64], x: f64) -> usize {
12    let mut count = 0;
13    let mut q = d[0] - x;
14    for i in 0..d.len() {
15        if i > 0 {
16            let qp = if q == 0.0 { f64::EPSILON * (e[i - 1].abs() + 1.0) } else { q };
17            q = d[i] - x - e[i - 1] * e[i - 1] / qp;
18        }
19        if q < 0.0 {
20            count += 1;
21        }
22    }
23    count
24}
25
26/// The discrete prolate spheroidal sequence (Slepian) window with time-half-bandwidth product `nw`:
27/// of all sequences of length `m`, the one with the largest fraction of its energy in the band
28/// `|f| < nw / m`. It is the eigenvector for the largest eigenvalue of a symmetric tridiagonal
29/// matrix that commutes with the concentration problem; that eigenvalue is located by Sturm
30/// bisection and the eigenvector found by inverse iteration, as in SciPy's `dpss`.
31pub fn dpss(m: usize, nw: f64, sym: bool) -> Vec<f64> {
32    if let Some(w) = len_guard(m) {
33        return w;
34    }
35    let (m2, needs_trunc) = extend(m, sym);
36    let wband = nw / m2 as f64;
37    let c = (2.0 * PI * wband).cos();
38    let d: Vec<f64> = (0..m2).map(|n| ((m2 as f64 - 1.0 - 2.0 * n as f64) / 2.0).powi(2) * c).collect();
39    let e: Vec<f64> = (1..m2).map(|n| (n as f64) * (m2 as f64 - n as f64) / 2.0).collect();
40
41    // ANCHOR: dpss_bisection
42    // Gershgorin bounds, then bisection for the largest eigenvalue.
43    let radius = |i: usize| (if i > 0 { e[i - 1].abs() } else { 0.0 }) + (if i + 1 < m2 { e[i].abs() } else { 0.0 });
44    let (mut lo, mut hi) = (0..m2).fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), i| (l.min(d[i] - radius(i)), h.max(d[i] + radius(i))));
45    for _ in 0..200 {
46        let mid = 0.5 * (lo + hi);
47        if mid <= lo || mid >= hi {
48            break;
49        }
50        if count_below(&d, &e, mid) < m2 { lo = mid } else { hi = mid }
51    }
52    let lambda = hi + 4.0 * f64::EPSILON * hi.abs().max(1.0);
53
54    // Inverse iteration: solve (T − λI) v_new = v by the tridiagonal (Thomas) elimination.
55    let mut v = vec![1.0_f64; m2];
56    for _ in 0..4 {
57        let mut cp = vec![0.0; m2];
58        let mut dp = vec![0.0; m2];
59        let mut b0 = d[0] - lambda;
60        if b0 == 0.0 {
61            b0 = f64::EPSILON;
62        }
63        cp[0] = if m2 > 1 { e[0] / b0 } else { 0.0 };
64        dp[0] = v[0] / b0;
65        for i in 1..m2 {
66            let mut den = d[i] - lambda - e[i - 1] * cp[i - 1];
67            if den == 0.0 {
68                den = f64::EPSILON;
69            }
70            cp[i] = if i + 1 < m2 { e[i] / den } else { 0.0 };
71            dp[i] = (v[i] - e[i - 1] * dp[i - 1]) / den;
72        }
73        let mut x = vec![0.0; m2];
74        x[m2 - 1] = dp[m2 - 1];
75        for i in (0..m2 - 1).rev() {
76            x[i] = dp[i] - cp[i] * x[i + 1];
77        }
78        let norm = x.iter().map(|t| t * t).sum::<f64>().sqrt();
79        v = x.into_iter().map(|t| t / norm).collect();
80    }
81    // ANCHOR_END: dpss_bisection
82
83    // Match scipy Kmax=None style normalization.
84    let maxv = v.iter().fold(0.0_f64, |a, &b| a.max(b.abs()));
85    if maxv > 0.0 {
86        for x in &mut v {
87            *x /= maxv;
88        }
89    }
90    if m2 % 2 == 0 {
91        let correction = (m2 * m2) as f64 / ((m2 * m2) as f64 + nw);
92        for x in &mut v {
93            *x *= correction;
94        }
95    }
96
97    if v.iter().sum::<f64>() < 0.0 {
98        for x in &mut v {
99            *x = -*x;
100        }
101    }
102
103    truncate(v, needs_trunc)
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use crate::discrete::windows::test_support::assert_window;
110
111    #[test]
112    fn wide_bandwidths_select_the_most_concentrated_sequence() {
113        // With nw / m > 1/4 the matrix has large negative eigenvalues, which power iteration
114        // (the previous method) converged to instead. scipy.signal.windows.dpss(7, 2.5):
115        let want = [0.06957312, 0.34640869, 0.77714755, 1.0, 0.77714755, 0.34640869, 0.06957312];
116        assert!(dpss(7, 2.5, true).iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-8));
117    }
118
119    #[test]
120    fn test_dpss() {
121        assert_window(include_str!("../test_data/dpss.csv"), dpss(7, 2.5, true));
122    }
123}