Skip to main content

lib_jsl_dsp/discrete/spectral/
non_uniformly_sampled.rs

1//! Spectral estimation for non-uniformly sampled data.
2//!
3//! Ordinary FFT spectra assume evenly spaced samples. When samples fall at irregular times (missed
4//! measurements, event-driven sensors, astronomical observations) the usual tools are:
5//!
6//! - the **Lomb-Scargle periodogram** ([`lomb_scargle`]), which fits a sinusoid by least squares at
7//!   each trial frequency. It is equivalent to the classical periodogram for even sampling, copes
8//!   with arbitrary gaps, and with irregular times is not subject to the usual Nyquist aliasing, so
9//!   frequencies far above the *average* sampling rate can still be detected;
10//! - the **non-uniform discrete Fourier transform** ([`non_uniform_dft`]), a direct evaluation of
11//!   `Σ y[n] e^{-j2π f t[n]}` at arbitrary frequencies;
12//! - a three-parameter **least-squares sinusoid fit** ([`fit_sinusoid`]) giving the amplitude and
13//!   phase at one frequency.
14//!
15//! All routines cost `O(N · F)` (samples times frequencies).
16//!
17//! See the book entry [Power spectra: periodogram, Welch, spectrogram and Lomb-Scargle](https://jwkunz.github.io/lib_jsl/book/spectral/power-spectra.html#unevenly-sampled-data-lomb-scargle).
18
19use lib_jsl_core::ErrorsJSL;
20use num_complex::Complex;
21use std::f64::consts::TAU;
22
23fn check_inputs(t: &[f64], y: &[f64]) -> Result<(), ErrorsJSL> {
24    if t.len() != y.len() {
25        return Err(ErrorsJSL::IncompatibleArraySizes((t.len(), y.len())));
26    }
27    if t.len() < 3 {
28        return Err(ErrorsJSL::InvalidInputRange("Need at least 3 samples"));
29    }
30    if t.iter().chain(y).any(|v| !v.is_finite()) {
31        return Err(ErrorsJSL::InvalidInputRange("Sample times and values must be finite"));
32    }
33    Ok(())
34}
35
36/// The Lomb-Scargle periodogram of samples `y` taken at times `t`, at the given **angular**
37/// frequencies (radians per unit time).
38///
39/// The mean is removed first. With `normalize` the result is the dimensionless power in `[0, 1]`
40/// (the fraction of the variance explained by the sinusoid at that frequency, so a noise-free
41/// sinusoid scores 1 at its frequency); otherwise it is the unnormalised power, which for a
42/// sinusoid of amplitude `A` sampled `N` times is about `A² N / 4`. Zero frequencies give 0.
43pub fn lomb_scargle(t: &[f64], y: &[f64], angular_frequencies: &[f64], normalize: bool) -> Result<Vec<f64>, ErrorsJSL> {
44    check_inputs(t, y)?;
45    let mean = y.iter().sum::<f64>() / y.len() as f64;
46    let yc: Vec<f64> = y.iter().map(|v| v - mean).collect();
47    let total: f64 = yc.iter().map(|v| v * v).sum();
48    if angular_frequencies.iter().any(|w| !w.is_finite() || *w < 0.0) {
49        return Err(ErrorsJSL::InvalidInputRange("Frequencies must be finite and non-negative"));
50    }
51    Ok(angular_frequencies
52        .iter()
53        .map(|&w| {
54            if w == 0.0 {
55                return 0.0;
56            }
57            let (mut s2, mut c2) = (0.0, 0.0);
58            for &ti in t {
59                let (s, c) = (2.0 * w * ti).sin_cos();
60                s2 += s;
61                c2 += c;
62            }
63            let tau = s2.atan2(c2) / (2.0 * w);
64            let (mut yc_c, mut yc_s, mut cc, mut ss) = (0.0, 0.0, 0.0, 0.0);
65            for (&ti, &yi) in t.iter().zip(&yc) {
66                let (s, c) = (w * (ti - tau)).sin_cos();
67                yc_c += yi * c;
68                yc_s += yi * s;
69                cc += c * c;
70                ss += s * s;
71            }
72            let mut p = 0.5 * (if cc > 0.0 { yc_c * yc_c / cc } else { 0.0 } + if ss > 0.0 { yc_s * yc_s / ss } else { 0.0 });
73            if normalize {
74                p = if total > 0.0 { p * 2.0 / total } else { 0.0 };
75            }
76            p
77        })
78        .collect())
79}
80
81/// Lomb-Scargle power at frequencies given in cycles per unit time (Hz when `t` is in seconds).
82/// This is the spectrum of irregularly sampled data as a function of ordinary frequency.
83pub fn non_uniformly_sampled_spectrum(t: &[f64], y: &[f64], frequencies_hz: &[f64], normalize: bool) -> Result<Vec<f64>, ErrorsJSL> {
84    let w: Vec<f64> = frequencies_hz.iter().map(|f| f * TAU).collect();
85    lomb_scargle(t, y, &w, normalize)
86}
87
88/// A sensible frequency grid (cycles per unit time, excluding zero) for [`lomb_scargle`]:
89/// spacing `1 / (oversampling · T)` for a record of duration `T`, extending to `max_frequency`.
90pub fn lomb_scargle_frequency_grid(t: &[f64], oversampling: f64, max_frequency: f64) -> Result<Vec<f64>, ErrorsJSL> {
91    if t.len() < 2 || !(oversampling > 0.0) || !(max_frequency > 0.0) {
92        return Err(ErrorsJSL::InvalidInputRange("Need >= 2 times, positive oversampling and positive maximum frequency"));
93    }
94    let span = t.iter().cloned().fold(f64::NEG_INFINITY, f64::max) - t.iter().cloned().fold(f64::INFINITY, f64::min);
95    if !(span > 0.0) {
96        return Err(ErrorsJSL::InvalidInputRange("Sample times must span a nonzero interval"));
97    }
98    let df = 1.0 / (oversampling * span);
99    let n = (max_frequency / df).floor() as usize;
100    Ok((1..=n).map(|i| i as f64 * df).collect())
101}
102
103/// Non-uniform discrete Fourier transform: `X(f) = Σ y[n] e^{-j2π f t[n]}` at each frequency (in
104/// cycles per unit time).
105pub fn non_uniform_dft(t: &[f64], y: &[f64], frequencies_hz: &[f64]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
106    if t.len() != y.len() {
107        return Err(ErrorsJSL::IncompatibleArraySizes((t.len(), y.len())));
108    }
109    if t.is_empty() {
110        return Err(ErrorsJSL::InvalidInputRange("Need at least 1 sample"));
111    }
112    Ok(frequencies_hz
113        .iter()
114        .map(|&f| t.iter().zip(y).map(|(&ti, &yi)| Complex::from_polar(yi, -TAU * f * ti)).sum())
115        .collect())
116}
117
118/// The result of fitting `offset + amplitude · cos(2π f t + phase)` to the samples.
119#[derive(Clone, Copy, Debug, PartialEq)]
120pub struct SinusoidFit {
121    pub amplitude: f64,
122    /// Phase in radians, in `(-π, π]`.
123    pub phase: f64,
124    pub offset: f64,
125}
126
127#[allow(clippy::needless_range_loop)]
128/// Least-squares fit of a constant plus a sinusoid of known frequency `f` (cycles per unit time).
129pub fn fit_sinusoid(t: &[f64], y: &[f64], f: f64) -> Result<SinusoidFit, ErrorsJSL> {
130    check_inputs(t, y)?;
131    if !(f > 0.0) || !f.is_finite() {
132        return Err(ErrorsJSL::InvalidInputRange("Frequency must be positive and finite"));
133    }
134    // Normal equations for y ≈ c0 + c1 cos(wt) + c2 sin(wt).
135    let w = TAU * f;
136    let mut m = [[0.0f64; 3]; 3];
137    let mut rhs = [0.0f64; 3];
138    for (&ti, &yi) in t.iter().zip(y) {
139        let (s, c) = (w * ti).sin_cos();
140        let basis = [1.0, c, s];
141        for i in 0..3 {
142            rhs[i] += basis[i] * yi;
143            for j in 0..3 {
144                m[i][j] += basis[i] * basis[j];
145            }
146        }
147    }
148    // Gauss-Jordan with partial pivoting on the 3x3 system.
149    let mut aug = [[0.0f64; 4]; 3];
150    for i in 0..3 {
151        aug[i][..3].copy_from_slice(&m[i]);
152        aug[i][3] = rhs[i];
153    }
154    for col in 0..3 {
155        let pivot = (col..3).max_by(|&a, &b| aug[a][col].abs().partial_cmp(&aug[b][col].abs()).unwrap()).unwrap();
156        if aug[pivot][col].abs() < 1e-12 * (t.len() as f64) {
157            return Err(ErrorsJSL::RuntimeError("Sinusoid fit is ill-conditioned at this frequency"));
158        }
159        aug.swap(col, pivot);
160        for r in 0..3 {
161            if r != col {
162                let factor = aug[r][col] / aug[col][col];
163                for k in col..4 {
164                    aug[r][k] -= factor * aug[col][k];
165                }
166            }
167        }
168    }
169    let (c0, c1, c2) = (aug[0][3] / aug[0][0], aug[1][3] / aug[1][1], aug[2][3] / aug[2][2]);
170    // c1 cos + c2 sin = A cos(wt + phi)  =>  A cos(phi) = c1, A sin(phi) = -c2.
171    Ok(SinusoidFit { amplitude: c1.hypot(c2), phase: (-c2).atan2(c1), offset: c0 })
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    fn lcg(seed: &mut u64) -> f64 {
179        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
180        (*seed >> 33) as f64 / (1u64 << 31) as f64
181    }
182
183    /// Irregular sample times with the given mean spacing.
184    fn irregular_times(n: usize, mean_dt: f64, seed: &mut u64) -> Vec<f64> {
185        let mut t = 0.0;
186        (0..n)
187            .map(|_| {
188                t += mean_dt * (0.2 + 1.6 * lcg(seed));
189                t
190            })
191            .collect()
192    }
193
194    fn argmax(p: &[f64]) -> usize {
195        p.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0
196    }
197
198    #[test]
199    fn evenly_sampled_sinusoid_scores_one_at_its_frequency() {
200        let t: Vec<f64> = (0..200).map(|n| n as f64 * 0.01).collect();
201        let y: Vec<f64> = t.iter().map(|&ti| 3.0 + 2.0 * (TAU * 12.5 * ti + 0.4).sin()).collect();
202        let p = non_uniformly_sampled_spectrum(&t, &y, &[12.5, 10.0, 20.0, 31.0], true).unwrap();
203        assert!((p[0] - 1.0).abs() < 1e-9, "{p:?}");
204        assert!(p[1] < 0.2 && p[2] < 0.2 && p[3] < 0.2);
205        // Unnormalised power is A^2 N / 4 for a full-cycle record.
206        let raw = non_uniformly_sampled_spectrum(&t, &y, &[12.5], false).unwrap()[0];
207        assert!((raw / (4.0 * 200.0 / 4.0) - 1.0).abs() < 0.05, "raw power {raw}");
208    }
209
210    #[test]
211    fn recovers_a_frequency_from_irregular_samples() {
212        let mut seed = 5;
213        let t = irregular_times(300, 0.1, &mut seed);
214        let f0 = 1.37;
215        let y: Vec<f64> = t.iter().map(|&ti| (TAU * f0 * ti + 1.0).cos() + 0.1 * (lcg(&mut seed) - 0.5)).collect();
216        let grid = lomb_scargle_frequency_grid(&t, 20.0, 4.0).unwrap();
217        let p = non_uniformly_sampled_spectrum(&t, &y, &grid, true).unwrap();
218        let est = grid[argmax(&p)];
219        assert!((est - f0).abs() < 0.01, "estimated {est}");
220        assert!(p[argmax(&p)] > 0.95);
221    }
222
223    #[test]
224    fn detects_frequencies_far_above_the_average_sampling_rate() {
225        // Average rate 10 samples/unit (nominal Nyquist 5), true frequency 13.2: irregular times
226        // break the aliasing that would make uniform sampling report 3.2 or 6.8.
227        let mut seed = 8;
228        let t = irregular_times(400, 0.1, &mut seed);
229        let f0 = 13.2;
230        let y: Vec<f64> = t.iter().map(|&ti| (TAU * f0 * ti).sin()).collect();
231        let grid = lomb_scargle_frequency_grid(&t, 10.0, 20.0).unwrap();
232        let p = non_uniformly_sampled_spectrum(&t, &y, &grid, true).unwrap();
233        let est = grid[argmax(&p)];
234        assert!((est - f0).abs() < 0.05, "estimated {est}");
235    }
236
237    #[test]
238    fn sinusoid_fit_recovers_amplitude_phase_and_offset_exactly() {
239        let mut seed = 2;
240        let t = irregular_times(60, 0.3, &mut seed);
241        let y: Vec<f64> = t.iter().map(|&ti| -1.5 + 2.5 * (TAU * 0.8 * ti + 0.9).cos()).collect();
242        let fit = fit_sinusoid(&t, &y, 0.8).unwrap();
243        assert!((fit.amplitude - 2.5).abs() < 1e-9 && (fit.phase - 0.9).abs() < 1e-9 && (fit.offset + 1.5).abs() < 1e-9, "{fit:?}");
244        let neg = fit_sinusoid(&t, &t.iter().map(|&ti| (TAU * 0.8 * ti - 2.0).cos()).collect::<Vec<_>>(), 0.8).unwrap();
245        assert!((neg.phase + 2.0).abs() < 1e-9);
246    }
247
248    #[allow(clippy::needless_range_loop)]
249    #[test]
250    fn non_uniform_dft_matches_the_dft_for_even_sampling() {
251        let n = 16;
252        let t: Vec<f64> = (0..n).map(|i| i as f64).collect();
253        let y: Vec<f64> = (0..n).map(|i| ((i * 7) % 5) as f64 - 2.0).collect();
254        let freqs: Vec<f64> = (0..n).map(|k| k as f64 / n as f64).collect();
255        let x = non_uniform_dft(&t, &y, &freqs).unwrap();
256        for k in 0..n {
257            let want: Complex<f64> = (0..n).map(|i| Complex::from_polar(y[i], -TAU * (i * k) as f64 / n as f64)).sum();
258            assert!((x[k] - want).norm() < 1e-9);
259        }
260        // A single sample at time t0 gives a pure phase ramp.
261        let one = non_uniform_dft(&[0.3], &[2.0], &[1.0]).unwrap();
262        assert!((one[0] - Complex::from_polar(2.0, -TAU * 0.3)).norm() < 1e-12);
263    }
264
265    #[test]
266    fn frequency_grid_shape_and_validation() {
267        let g = lomb_scargle_frequency_grid(&[0.0, 10.0], 5.0, 1.0).unwrap();
268        assert!((g[0] - 0.02).abs() < 1e-12 && g.len() == 50);
269        assert!(lomb_scargle_frequency_grid(&[1.0], 5.0, 1.0).is_err());
270        assert!(lomb_scargle_frequency_grid(&[1.0, 1.0], 5.0, 1.0).is_err());
271        assert!(lomb_scargle_frequency_grid(&[0.0, 1.0], 0.0, 1.0).is_err());
272        assert!(lomb_scargle(&[0.0, 1.0], &[1.0, 2.0], &[1.0], true).is_err(), "fewer than 3 samples");
273        assert!(lomb_scargle(&[0.0, 1.0, 2.0], &[1.0, 2.0], &[1.0], true).is_err(), "length mismatch");
274        assert!(lomb_scargle(&[0.0, 1.0, 2.0], &[1.0, 2.0, f64::NAN], &[1.0], true).is_err());
275        assert!(lomb_scargle(&[0.0, 1.0, 2.0], &[1.0, 2.0, 3.0], &[-1.0], true).is_err());
276        assert_eq!(lomb_scargle(&[0.0, 1.0, 2.0], &[1.0, 2.0, 4.0], &[0.0], true).unwrap(), vec![0.0]);
277        assert!(fit_sinusoid(&[0.0, 1.0, 2.0], &[1.0, 2.0, 3.0], 0.0).is_err());
278    }
279}