Skip to main content

xsf/xsf/
fresnel.rs

1//! Translated into pure Rust from `xsf/cpu/fresnel.h` (scipy/xsf@5709919).
2
3use core::f64::consts::{FRAC_PI_2, FRAC_PI_4, PI};
4
5use core::ffi::c_int;
6use num_complex::Complex;
7
8use crate::utils::{FRAC_1_SQRT_PI, SQRT_FRAC_2_PI, SQRT_TAU_DOWN, neg_one_pow};
9use crate::xsf::c64::{C64, c64};
10use crate::xsf::specfun::deflated_newton_step;
11
12fn cfc(z: C64) -> (C64, C64) {
13    // =========================================================
14    // Purpose: Compute complex Fresnel integral C(z) and C'(z)
15    // Input :  z --- Argument of C(z)
16    // Output:  ZF --- C(z)
17    //          ZD --- C'(z)
18    // =========================================================
19
20    const EPS: f64 = 1.0e-14;
21
22    let w0 = z.norm();
23    let zp = FRAC_PI_2 * z * z;
24    let zp2 = zp * zp;
25    let z0 = C64::ZERO;
26
27    let c = if z == z0 {
28        z0
29    } else if w0 <= 2.5 {
30        let mut cr = z;
31        let mut c = cr;
32        let mut wa0 = 0.0;
33        for k in 1..=80 {
34            let k = f64::from(k);
35            cr = -0.5 * cr * (4.0 * k - 3.0) / k / (2.0 * k - 1.0) / (4.0 * k + 1.0) * zp2;
36            c += cr;
37            let wa = c.norm();
38            if (((wa - wa0) / wa).abs() < EPS) && (k > 10.0) {
39                return (c, (FRAC_PI_2 * z * z).cos());
40            }
41            wa0 = wa;
42        }
43        c
44    } else if (w0 > 2.5) && (w0 < 4.5) {
45        let m = 85;
46        let mut c = z0;
47        let mut cf = z0;
48        let mut cf1 = z0;
49        let mut cf0 = c64(1.0e-100, 0.0);
50        for k in (0..=m).rev() {
51            cf = (2.0 * f64::from(k) + 3.0) * cf0 / zp - cf1;
52            if k % 2 == 0 {
53                c += cf;
54            }
55            cf1 = cf0;
56            cf0 = cf;
57        }
58        c *= 2.0 / (PI * z) * zp.sin() / cf;
59        c
60    } else {
61        // See comment at CFS(), use C(z) = iC(-iz)
62        let d = if (z.im > -z.re) && (z.im <= z.re) {
63            // right quadrant
64            c64(0.5, 0.0)
65        } else if (z.im > z.re) && (z.im >= -z.re) {
66            // upper quadrant
67            c64(0.0, 0.5)
68        } else if (z.im < -z.re) && (z.im >= z.re) {
69            // left quadrant
70            c64(-0.5, 0.0)
71        } else {
72            c64(0.0, -0.5)
73        };
74        let mut cr = C64::ONE;
75        let mut cf = C64::ONE;
76        for k in 1..=20 {
77            let k = f64::from(k);
78            cr = -0.25 * cr * (4.0 * k - 1.0) * (4.0 * k - 3.0) / zp2;
79            cf += cr;
80        }
81        cr = 1.0 / (PI * z * z);
82        let mut cg = cr;
83        for k in 1..=12 {
84            let k = f64::from(k);
85            cr = -0.25 * cr * (4.0 * k + 1.0) * (4.0 * k - 1.0) / zp2;
86            cg += cr;
87        }
88        d + (cf * zp.sin() - cg * zp.cos()) / (PI * z)
89    };
90    (c, (FRAC_PI_2 * z * z).cos())
91}
92
93fn cfs(z: C64) -> (C64, C64) {
94    // =========================================================
95    // Purpose: Compute complex Fresnel Integral S(z) and S'(z)
96    // Input :  z  --- Argument of S(z)
97    // Output:  ZF --- S(z)
98    //          ZD --- S'(z)
99    // =========================================================
100
101    const EPS: f64 = 1.0e-14;
102
103    let w0 = z.norm();
104    let zp = FRAC_PI_2 * z * z;
105    let zp2 = zp * zp;
106    let z0 = C64::ZERO;
107
108    let s = if z == z0 {
109        z0
110    } else if w0 <= 2.5 {
111        let mut s = z * zp / 3.0;
112        let mut cr = s;
113        let mut wb0 = 0.0;
114        for k in 1..=80 {
115            let k = f64::from(k);
116            cr = -0.5 * cr * (4.0 * k - 1.0) / k / (2.0 * k + 1.0) / (4.0 * k + 3.0) * zp2;
117            s += cr;
118            let wb = s.norm();
119            if ((wb - wb0).abs() < EPS) && (k > 10.0) {
120                return (s, (FRAC_PI_2 * z * z).sin());
121            }
122            wb0 = wb;
123        }
124        s
125    } else if (w0 > 2.5) && (w0 < 4.5) {
126        let m = 85;
127        let mut s = z0;
128        let mut cf = z0;
129        let mut cf1 = z0;
130        let mut cf0 = c64(1.0e-100, 0.0);
131        for k in (0..=m).rev() {
132            cf = (2.0 * f64::from(k) + 3.0) * cf0 / zp - cf1;
133            if k % 2 == 1 {
134                s += cf;
135            }
136            cf1 = cf0;
137            cf0 = cf;
138        }
139        2.0 / (PI * z) * zp.sin() / cf * s
140    } else {
141        // Auxiliary functions f(z) and g(z) can be computed using an
142        // asymptotic expansion in the right quadrant |arg(z)| <= pi/4, not pi/2
143        // as sometimes suggested. Use the symmetry S(z) = -iS(-iz).
144        // Interestingly, most of the expansion code is the same across
145        // the quadrants. (The forth power in Z is the equalizer here.)
146        // Only one constant has to be adapted.
147        let d = if (z.im > -z.re) && (z.im <= z.re) {
148            // right quadrant
149            c64(0.5, 0.0)
150        } else if (z.im > z.re) && (z.im >= -z.re) {
151            // upper quadrant
152            c64(0.0, -0.5)
153        } else if (z.im < -z.re) && (z.im >= z.re) {
154            // left quadrant
155            c64(-0.5, 0.0)
156        } else {
157            c64(0.0, 0.5)
158        };
159        let mut cr = C64::ONE;
160        let mut cf = C64::ONE;
161        for k in 1..=20 {
162            let k = f64::from(k);
163            cr = -0.25 * cr * (4.0 * k - 1.0) * (4.0 * k - 3.0) / zp2;
164            cf += cr;
165        }
166        cr = C64::ONE;
167        let mut cg = C64::ONE;
168        for k in 1..=12 {
169            let k = f64::from(k);
170            cr = -0.25 * cr * (4.0 * k + 1.0) * (4.0 * k - 1.0) / zp2;
171            cg += cr;
172        }
173        cg /= PI * z * z;
174        d - (cf * zp.cos() + cg * zp.sin()) / (PI * z)
175    };
176    (s, (FRAC_PI_2 * z * z).sin())
177}
178
179fn ffk(ks: i32, x: f64) -> (C64, C64) {
180    // =======================================================
181    // Purpose: Compute modified Fresnel integrals F±(x)
182    //          and K±(x)
183    // Input :  x   --- Argument of F±(x) and K±(x)
184    //          KS  --- Sign code
185    //                  KS=0 for calculating F+(x) and K+(x)
186    //                  KS=1 for calculating F_(x) and K_(x)
187    // Output:  FR  --- Re[F±(x)]
188    //          FI  --- Im[F±(x)]
189    //          GR  --- Re[K±(x)]
190    //          GI  --- Im[K±(x)]
191    // ======================================================
192
193    const EPS: f64 = 1.0e-15;
194    const PP2: f64 = 1.253_314_137_315_5;
195
196    let mut f = C64::ZERO;
197    let mut g = C64::ZERO;
198
199    let xa = x.abs();
200    let x2 = x * x;
201    let x4 = x2 * x2;
202    let sgn = neg_one_pow(ks);
203
204    if x == 0.0 {
205        f.re = 0.5 * FRAC_PI_2.sqrt();
206        f.im = sgn * f.re;
207        g = c64(0.5, 0.0);
208    } else {
209        let (c1, s1);
210        if xa <= 2.5 {
211            let mut xr = SQRT_FRAC_2_PI * xa;
212            let mut c = xr;
213
214            for k in 1..=50 {
215                let k = f64::from(k);
216                xr = -0.5 * xr * (4.0 * k - 3.0) / k / (2.0 * k - 1.0) / (4.0 * k + 1.0) * x4;
217                c += xr;
218                if (xr / c).abs() < EPS {
219                    break;
220                }
221            }
222
223            let mut s = SQRT_FRAC_2_PI * xa * xa * xa / 3.0;
224            xr = s;
225
226            for k in 1..=50 {
227                let k = f64::from(k);
228                xr = -0.5 * xr * (4.0 * k - 1.0) / k / (2.0 * k + 1.0) / (4.0 * k + 3.0) * x4;
229                s += xr;
230                if (xr / s).abs() < EPS {
231                    break;
232                }
233            }
234
235            (c1, s1) = (c, s);
236            f.re = PP2 * (0.5 - c1);
237            let fi0 = PP2 * (0.5 - s1);
238            f.im = sgn * fi0;
239        } else if xa < 5.5 {
240            let m = (42.0 + 1.75 * x2) as i32;
241            let mut xsu = 0.0;
242            let mut xc = 0.0;
243            let mut xs = 0.0;
244            let mut xf1 = 0.0;
245            let mut xf0 = 1.0e-100;
246
247            for k in (0..=m).rev() {
248                let xf = (2.0 * f64::from(k) + 3.0) * xf0 / x2 - xf1;
249                if k % 2 == 0 {
250                    xc += xf;
251                } else {
252                    xs += xf;
253                }
254                xsu += (2.0 * f64::from(k) + 1.0) * xf * xf;
255                xf1 = xf0;
256                xf0 = xf;
257            }
258
259            let xq = xsu.sqrt();
260            let xw = SQRT_FRAC_2_PI * xa / xq;
261            c1 = xc * xw;
262            s1 = xs * xw;
263        } else {
264            let mut xr = 1.0;
265            let mut xf = 1.0;
266
267            for k in 1..=12 {
268                let k = f64::from(k);
269                xr = -0.25 * xr * (4.0 * k - 1.0) * (4.0 * k - 3.0) / x4;
270                xf += xr;
271            }
272
273            xr = 1.0 / (2.0 * xa * xa);
274            let mut xg = xr;
275
276            for k in 1..=12 {
277                let k = f64::from(k);
278                xr = -0.25 * xr * (4.0 * k + 1.0) * (4.0 * k - 1.0) / x4;
279                xg += xr;
280            }
281
282            let (sin, cos) = x2.sin_cos();
283            c1 = 0.5 + (xf * sin - xg * cos) / SQRT_TAU_DOWN / xa;
284            s1 = 0.5 - (xf * cos + xg * sin) / SQRT_TAU_DOWN / xa;
285
286            // K+-(x) = (xg +- i xf) e^(-+i pi/4) / (2 sqrt(pi) x), DLMF 7.5.10, 7.12.2, 7.12.3;
287            // avoids the rounding error of the phase x^2 + pi/4 below
288            g.re = (xf + xg) / (2.0 * SQRT_TAU_DOWN) / xa;
289            g.im = sgn * (xf - xg) / (2.0 * SQRT_TAU_DOWN) / xa;
290        }
291
292        f.re = PP2 * (0.5 - c1);
293        let fi0 = PP2 * (0.5 - s1);
294        f.im = sgn * fi0;
295
296        if xa < 5.5 {
297            let (ss, cs) = (x2 + FRAC_PI_4).sin_cos();
298            let xq2 = FRAC_1_SQRT_PI;
299
300            g.re = xq2 * (f.re * cs + fi0 * ss);
301            g.im = sgn * xq2 * (fi0 * cs - f.re * ss);
302        }
303
304        if x < 0.0 {
305            f.re = PP2 - f.re;
306            // Unlike in xsf (scipy/xsf#367), this subtracts `f.im` instead of the updated `f.re`
307            f.im = sgn * PP2 - f.im;
308            let (sin, cos) = x2.sin_cos();
309            g.re = cos - g.re;
310            g.im = -sgn * sin - g.im;
311        }
312    }
313    (f, g)
314}
315
316fn fcszo(kf: i32, nt: usize, zo: &mut [C64]) {
317    // ===============================================================
318    // Purpose: Compute the complex zeros of Fresnel integral C(z)
319    //          or S(z) using modified Newton's iteration method
320    // Input :  KF  --- Function code
321    //                  KF=1 for C(z) or KF=2 for S(z)
322    //          NT  --- Total number of zeros
323    // Output:  ZO(L) --- L-th zero of C(z) or S(z)
324    // Routines called:
325    //      (1) CFC for computing Fresnel integral C(z)
326    //      (2) CFS for computing Fresnel integral S(z)
327    // ==============================================================
328
329    let mut psq = 0.0;
330    let mut w = 0.0;
331
332    for nr in 1..=nt {
333        if kf == 1 {
334            psq = (4.0 * nr as f64 - 1.0).sqrt();
335        }
336        if kf == 2 {
337            psq = 2.0 * (nr as f64).sqrt();
338        }
339
340        let px = psq - (PI * psq).ln() / (PI * PI * psq * psq * psq);
341        let py = (PI * psq).ln() / (PI * psq);
342        let mut z = c64(px, py);
343
344        if kf == 2 {
345            if nr == 2 {
346                z = c64(2.8334, 0.2443);
347            }
348            if nr == 3 {
349                z = c64(3.4674, 0.2185);
350            }
351            if nr == 4 {
352                z = c64(4.0025, 0.2008);
353            }
354        }
355
356        let mut it = 0;
357        loop {
358            it += 1;
359            let (zf, zd) = if kf == 1 { cfc(z) } else { cfs(z) };
360
361            z -= deflated_newton_step(z, zf, zd, &zo[..nr - 1]);
362            let w0 = w;
363            w = z.norm();
364            if !((it <= 50) && (((w - w0) / w).abs() > 1.0e-12)) {
365                break;
366            }
367        }
368        zo[nr - 1] = z;
369    }
370}
371
372pub trait FresnelArg: crate::sealed::Sealed + Sized {
373    fn fresnel(self) -> (Self, Self);
374}
375
376impl FresnelArg for f64 {
377    #[inline]
378    fn fresnel(self) -> (Self, Self) {
379        crate::xsf::cephes::fresnl(self)
380    }
381}
382
383impl FresnelArg for Complex<f64> {
384    #[inline]
385    fn fresnel(self) -> (Self, Self) {
386        let z = C64::from(self);
387        (cfs(z).0.into(), cfc(z).0.into())
388    }
389}
390
391/// Fresnel integrals $S(z)$ and $C(z)$ for real or complex argument
392///
393/// The Fresnel integrals are defined as:
394/// - $S(z) = \int_0^z \sin(\pi t^2 / 2) \dd t$
395/// - $C(z) = \int_0^z \cos(\pi t^2 / 2) \dd t$
396///
397/// where the integrals are taken from 0 to $z$.
398///
399/// Corresponds to [`scipy.special.fresnel`][scipy]
400///
401/// [scipy]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.fresnel.html
402///
403/// # See also
404/// - [`fresnel_zeros`] - Zeros of $S(z)$ and $C(z)$
405/// - [`modified_fresnel_plus`] - Modified Fresnel positive integrals
406/// - [`modified_fresnel_minus`] - Modified Fresnel negative integrals
407#[must_use]
408#[inline]
409pub fn fresnel<T: FresnelArg>(z: T) -> (T, T) {
410    z.fresnel()
411}
412
413/// Modified Fresnel positive integrals
414///
415/// Computes the modified Fresnel integrals:
416/// - $F_+(x) = \int_x^\infty \exp(i t^2) \dd t$
417/// - $K_+(x) = F_+(x) \times \exp(-i (x^2 + \pi/4)) / \sqrt\pi$
418///
419/// Corresponds to [`scipy.special.modfresnelp`][scipy]
420///
421/// [scipy]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.modfresnelp.html
422///
423/// # See also
424/// - [`fresnel`] - Standard Fresnel integrals
425/// - [`modified_fresnel_minus`] - Modified Fresnel negative integrals
426#[doc(alias = "modfresnelp")]
427#[must_use]
428#[inline]
429pub fn modified_fresnel_plus(x: f64) -> (Complex<f64>, Complex<f64>) {
430    let (f, k) = ffk(0, x);
431    (f.into(), k.into())
432}
433
434/// Modified Fresnel negative integrals
435///
436/// Computes the modified Fresnel integrals:
437/// - $F_-(x) = \int_x^\infty \exp(-i t^2) \dd t$
438/// - $K_-(x) = F_-(x) \times \exp(i (x^2 + \pi/4)) / \sqrt\pi$
439///
440/// Corresponds to [`scipy.special.modfresnelm`][scipy]
441///
442/// [scipy]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.modfresnelm.html
443///
444/// # See also
445/// - [`fresnel`] - Standard Fresnel integrals $S(z)$ and $C(z)$
446/// - [`modified_fresnel_plus`] - Modified Fresnel positive integrals
447#[doc(alias = "modfresnelm")]
448#[must_use]
449#[inline]
450pub fn modified_fresnel_minus(x: f64) -> (Complex<f64>, Complex<f64>) {
451    let (f, k) = ffk(1, x);
452    (f.into(), k.into())
453}
454
455/// Zeros of Fresnel integrals $S(z)$ and $C(z)$
456///
457/// Compute `nt` complex zeros of the Fresnel integrals $S(z)$ and $C(z)$.
458///
459/// Corresponds to [`scipy.special.fresnel_zeros`][scipy]
460///
461/// [scipy]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.fresnel_zeros.html
462///
463/// # Panics
464/// - if `nt` is greater than [`c_int::MAX`](core::ffi::c_int::MAX)
465///
466/// # See also
467/// - [`fresnel`] - Fresnel integrals $S(z)$ and $C(z)$
468/// - [`modified_fresnel_plus`] - Modified Fresnel positive integrals $F_+(x)$ and $K_+(x)$
469/// - [`modified_fresnel_minus`] - Modified Fresnel negative integrals $F_-(x)$ and $K_-(x)$
470#[doc(alias = "fresnelc_zeros", alias = "fresnels_zeros")]
471#[must_use]
472#[inline]
473pub fn fresnel_zeros(nt: usize) -> (Vec<Complex<f64>>, Vec<Complex<f64>>) {
474    assert!(nt <= c_int::MAX as usize);
475
476    let mut szo = vec![C64::NAN_RE; nt];
477    let mut czo = vec![C64::NAN_RE; nt];
478    fcszo(2, nt, &mut szo);
479    fcszo(1, nt, &mut czo);
480    (
481        szo.into_iter().map(Into::into).collect(),
482        czo.into_iter().map(Into::into).collect(),
483    )
484}