Skip to main content

lib_jsl_dsp/continuous/spectral/
fourier_integrals.rs

1//! Numerical Fourier integrals of functions with finite support.
2//!
3//! The transform follows the angular-frequency convention
4//! `F(omega) = integral f(x) exp(-i omega x) dx`, with inverse
5//! `f(x) = (1 / 2 pi) integral F(omega) exp(i omega x) d omega`.
6//! The integral is approximated by the trapezoidal rule on `M` evenly spaced
7//! samples over the support. A chirp-z transform evaluates the requested
8//! evenly spaced frequencies using the crate's `Fft` implementation.
9//!
10//! See the book entry [Spectra at chosen frequencies: Goertzel, chirp-z and Fourier integrals](https://jwkunz.github.io/lib_jsl/book/spectral/chosen-frequencies.html#fourier-integrals).
11
12use num_complex::Complex;
13use std::f64::consts::TAU;
14
15use crate::{
16    discrete::spectral::chirpz::chirpz,
17    prelude::{C1D, ErrorsJSL, R1D},
18};
19
20/// Polarity and normalization convention for a Fourier integral.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum FourierDirection {
23    /// `integral f(x) exp(-i omega x) dx`.
24    Forward,
25    /// `(1 / 2 pi) integral f(x) exp(i omega x) dx`.
26    Inverse,
27}
28
29/// Samples of a Fourier integral on an angular-frequency grid.
30#[derive(Clone, Debug, PartialEq)]
31#[non_exhaustive]
32pub struct FourierIntegralResult {
33    /// Angular-frequency samples in rad per unit of `x`.
34    pub omega: R1D,
35    /// Transform values corresponding to `omega`.
36    pub values: C1D,
37}
38
39/// Approximate the Fourier integral of `f` over its finite support.
40///
41/// `M` is both the number of equally spaced samples used to approximate the
42/// integral on `[x_start, x_stop]` and the number of equally spaced output
43/// frequencies on `[omega_start, omega_stop]`. For `M == 1`, the sole
44/// frequency is `omega_start` and the function is sampled at the midpoint of
45/// its support. For larger `M`, the support endpoints are included and the
46/// trapezoidal rule is used.
47///
48/// The frequency-domain evaluation uses the chirp-z transform, which is
49/// implemented through FFT convolution with `Fft`. This permits arbitrary
50/// frequency ranges, not only the standard FFT bins.
51pub fn fourier_integral(
52    f: fn(f64) -> Complex<f64>,
53    x_start: f64,
54    x_stop: f64,
55    omega_start: f64,
56    omega_stop: f64,
57    m: usize,
58    direction: FourierDirection,
59) -> Result<FourierIntegralResult, ErrorsJSL> {
60    if !x_start.is_finite()
61        || !x_stop.is_finite()
62        || x_stop < x_start
63        || !omega_start.is_finite()
64        || !omega_stop.is_finite()
65    {
66        return Err(ErrorsJSL::InvalidInputRange(
67            "integration and frequency bounds must be finite and ordered",
68        ));
69    }
70    if m == 0 {
71        return Err(ErrorsJSL::InvalidInputRange("M must be > 0"));
72    }
73
74    let omega = R1D::from_vec(if m == 1 {
75        vec![omega_start]
76    } else {
77        (0..m)
78            .map(|k| omega_start + (omega_stop - omega_start) * k as f64 / (m - 1) as f64)
79            .collect()
80    });
81
82    if x_start == x_stop {
83        return Ok(FourierIntegralResult {
84            omega,
85            values: C1D::from_elem(m, Complex::new(0.0, 0.0)),
86        });
87    }
88
89    let support_width = x_stop - x_start;
90    let (sample_spacing, samples) = if m == 1 {
91        (
92            support_width,
93            vec![f((x_start + x_stop) * 0.5)],
94        )
95    } else {
96        let dx = support_width / (m - 1) as f64;
97        let samples = (0..m)
98            .map(|n| {
99                let x = x_start + n as f64 * dx;
100                let weight = if n == 0 || n + 1 == m { 0.5 } else { 1.0 };
101                f(x) * weight
102            })
103            .collect::<Vec<_>>();
104        (dx, samples)
105    };
106
107    let polarity = match direction {
108        FourierDirection::Forward => -1.0,
109        FourierDirection::Inverse => 1.0,
110    };
111    let delta_omega = if m == 1 {
112        0.0
113    } else {
114        (omega_stop - omega_start) / (m - 1) as f64
115    };
116    let chirp_angle = polarity * delta_omega * sample_spacing;
117    let chirp_step = Complex::new(chirp_angle.cos(), chirp_angle.sin());
118    let phased_samples = samples
119        .iter()
120        .enumerate()
121        .map(|(n, sample)| {
122            let x = if m == 1 {
123                (x_start + x_stop) * 0.5
124            } else {
125                x_start + n as f64 * sample_spacing
126            };
127            let phase = polarity * omega_start * x;
128            *sample * Complex::new(phase.cos(), phase.sin())
129        })
130        .collect::<Vec<_>>();
131    let mut values = chirpz(&phased_samples, Some(m), Some(chirp_step), None)?;
132
133    let normalization = sample_spacing
134        * match direction {
135            FourierDirection::Forward => 1.0,
136            FourierDirection::Inverse => 1.0 / TAU,
137        };
138    for (k, value) in values.iter_mut().enumerate() {
139        let x_origin_phase = polarity * delta_omega * k as f64 * x_start;
140        *value *= Complex::new(x_origin_phase.cos(), x_origin_phase.sin()) * normalization;
141    }
142
143    Ok(FourierIntegralResult { omega, values })
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    fn constant(_: f64) -> Complex<f64> {
151        Complex::new(1.0, 0.0)
152    }
153
154    fn linear(x: f64) -> Complex<f64> {
155        Complex::new(x, 0.5 * x)
156    }
157
158    fn assert_close(actual: Complex<f64>, expected: Complex<f64>, tol: f64) {
159        assert!(
160            (actual - expected).norm() < tol,
161            "actual={actual}, expected={expected}, tol={tol}"
162        );
163    }
164
165    #[test]
166    fn test_forward_integral_uses_requested_frequencies() {
167        let result = fourier_integral(
168            linear,
169            -1.0,
170            1.0,
171            -2.0,
172            2.0,
173            5,
174            FourierDirection::Forward,
175        )
176        .unwrap();
177
178        assert_eq!(result.omega.to_vec(), vec![-2.0, -1.0, 0.0, 1.0, 2.0]);
179
180        let dx = 0.5;
181        for (k, &omega) in result.omega.iter().enumerate() {
182            let mut expected = Complex::new(0.0, 0.0);
183            for n in 0..5 {
184                let x = -1.0 + n as f64 * dx;
185                let weight = if n == 0 || n == 4 { 0.5 } else { 1.0 };
186                let phase = -omega * x;
187                expected += linear(x) * Complex::new(phase.cos(), phase.sin()) * weight * dx;
188            }
189            assert_close(result.values[k], expected, 1e-10);
190        }
191    }
192
193    #[test]
194    fn test_inverse_integral_uses_positive_polarity_and_normalization() {
195        let result = fourier_integral(
196            constant,
197            0.0,
198            2.0,
199            0.0,
200            0.0,
201            3,
202            FourierDirection::Inverse,
203        )
204        .unwrap();
205
206        for value in result.values {
207            assert_close(value, Complex::new(2.0 / TAU, 0.0), 1e-12);
208        }
209    }
210
211    #[test]
212    fn test_single_frequency_uses_midpoint_rule() {
213        let result = fourier_integral(
214            constant,
215            2.0,
216            4.0,
217            3.0,
218            8.0,
219            1,
220            FourierDirection::Forward,
221        )
222        .unwrap();
223
224        assert_eq!(result.omega.to_vec(), vec![3.0]);
225        let phase = -9.0_f64;
226        assert_close(
227            result.values[0],
228            Complex::new(2.0 * phase.cos(), 2.0 * phase.sin()),
229            1e-12,
230        );
231    }
232
233    #[test]
234    fn test_zero_width_support_returns_zero_integral() {
235        let result = fourier_integral(
236            constant,
237            1.0,
238            1.0,
239            -1.0,
240            1.0,
241            3,
242            FourierDirection::Forward,
243        )
244        .unwrap();
245
246        assert_eq!(result.values, C1D::zeros(3));
247    }
248
249    #[test]
250    fn test_rejects_invalid_bounds_and_sample_count() {
251        assert!(matches!(
252            fourier_integral(
253                constant,
254                2.0,
255                1.0,
256                0.0,
257                1.0,
258                3,
259                FourierDirection::Forward,
260            ),
261            Err(ErrorsJSL::InvalidInputRange(_))
262        ));
263        assert!(matches!(
264            fourier_integral(
265                constant,
266                0.0,
267                1.0,
268                0.0,
269                1.0,
270                0,
271                FourierDirection::Forward,
272            ),
273            Err(ErrorsJSL::InvalidInputRange(_))
274        ));
275    }
276}