Skip to main content

lib_jsl_dsp/discrete/spectral/
hilbert.rs

1//! The Hilbert transform and the analytic signal.
2//!
3//! See the book entry [The Hilbert transform and the analytic signal](https://jwkunz.github.io/lib_jsl/book/spectral/hilbert.html).
4
5use lib_jsl_core::ErrorsJSL;
6use lib_jsl_ffts::{Fft, FftDirection, FftEngine1D, FftOrdering, FftScaleFactor};
7use num_complex::Complex;
8use std::f64::consts::{PI, TAU};
9
10/// The analytic signal `x + i H{x}` of a real signal, by the FFT: negative-frequency bins are
11/// zeroed and positive ones doubled (DC, and Nyquist for even lengths, kept), as in SciPy's
12/// `hilbert`. The transform treats `x` as periodic, so edges show some ringing for non-periodic
13/// data.
14pub fn analytic_signal(x: &[f64]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
15    let n = x.len();
16    if n == 0 {
17        return Err(ErrorsJSL::InvalidInputRange("The signal must not be empty."));
18    }
19    // ANCHOR: analytic_signal
20    let input: Vec<Complex<f64>> = x.iter().map(|&v| Complex::new(v, 0.0)).collect();
21    let mut spectrum = Fft::with_plan(n, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard)?.execute(&input)?;
22    let half = n.div_ceil(2);
23    for (k, s) in spectrum.iter_mut().enumerate() {
24        if k == 0 || (n.is_multiple_of(2) && k == n / 2) {
25            continue;
26        }
27        *s *= if k < half { 2.0 } else { 0.0 };
28    }
29    Fft::with_plan(n, FftScaleFactor::N, FftDirection::Inverse, FftOrdering::Standard)?.execute(&spectrum)
30    // ANCHOR_END: analytic_signal
31}
32
33/// The Hilbert transform `H{x}` (the imaginary part of the analytic signal): `cos → sin`,
34/// `sin → −cos`.
35pub fn hilbert_transform(x: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
36    Ok(analytic_signal(x)?.iter().map(|z| z.im).collect())
37}
38
39/// Instantaneous amplitude, unwrapped phase and frequency of a signal.
40#[derive(Debug, Clone)]
41pub struct InstantaneousAttributes {
42    /// The envelope `|x + iH{x}|`.
43    pub amplitude: Vec<f64>,
44    /// Unwrapped phase in radians.
45    pub phase: Vec<f64>,
46    /// Frequency in Hz from phase differences (one shorter than the signal).
47    pub frequency: Vec<f64>,
48}
49
50/// The instantaneous attributes of `x` sampled at `fs`, from its analytic signal.
51pub fn instantaneous_attributes(x: &[f64], fs: f64) -> Result<InstantaneousAttributes, ErrorsJSL> {
52    let z = analytic_signal(x)?;
53    let amplitude = z.iter().map(|v| v.norm()).collect();
54    let mut phase: Vec<f64> = z.iter().map(|v| v.arg()).collect();
55    for i in 1..phase.len() {
56        let jump = ((phase[i] - phase[i - 1] + PI).rem_euclid(TAU)) - PI;
57        phase[i] = phase[i - 1] + jump;
58    }
59    let frequency = phase.windows(2).map(|w| (w[1] - w[0]) * fs / TAU).collect();
60    Ok(InstantaneousAttributes { amplitude, phase, frequency })
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    #[test]
68    fn transforms_cosines_to_sines_for_even_and_odd_lengths() {
69        for n in [64, 63, 100] {
70            let k = 5.0;
71            let x: Vec<f64> = (0..n).map(|i| (TAU * k * i as f64 / n as f64).cos()).collect();
72            let h = hilbert_transform(&x).unwrap();
73            assert!(h.iter().enumerate().all(|(i, v)| (v - (TAU * k * i as f64 / n as f64).sin()).abs() < 1e-12), "n={n}");
74            // The real part of the analytic signal is the signal itself.
75            assert!(analytic_signal(&x).unwrap().iter().zip(&x).all(|(z, v)| (z.re - v).abs() < 1e-12));
76        }
77        assert!(analytic_signal(&[]).is_err());
78    }
79
80    #[test]
81    fn recovers_the_envelope_and_frequency_of_an_am_signal() {
82        let (fs, n) = (1000.0, 1000);
83        let carrier = 100.0;
84        let envelope = |t: f64| 1.0 + 0.5 * (TAU * 3.0 * t).cos();
85        let x: Vec<f64> = (0..n).map(|i| { let t = i as f64 / fs; envelope(t) * (TAU * carrier * t).cos() }).collect();
86        let InstantaneousAttributes { amplitude, frequency, .. } = instantaneous_attributes(&x, fs).unwrap();
87        for i in (100..900).step_by(50) {
88            assert!((amplitude[i] - envelope(i as f64 / fs)).abs() < 1e-9, "i={i}");
89            assert!((frequency[i] - carrier).abs() < 1e-6, "i={i}: {}", frequency[i]);
90        }
91    }
92}