Skip to main content

xsf/scipy_special/
ellip_harm.rs

1//! Translated from scipy/special/_ellip_harm.pxd
2
3use crate::ext::tridiag;
4use crate::utils::pow2;
5use crate::xsf::cephes::dd_real::{frexp_f64, ldexp_f64};
6
7/// `x^2 - c`, without the rounding error of `x^2`, which matters if `x^2 ~ c`
8pub(super) fn sq_sub(x: f64, c: f64) -> f64 {
9    // Veltkamp's split `x = hi + lo` (as in Dekker's `two_prod`), where `hi` and `lo` have at
10    // most 26 bits, so that `hi^2`, `hi lo`, and `lo^2` are exact
11    const SPLITTER: f64 = pow2(27) + 1.0;
12    let x2 = x * x;
13    if x2.is_infinite() {
14        // and `SPLITTER x` might overflow
15        return x2;
16    }
17    let t = SPLITTER * x;
18    let hi = t - (t - x);
19    let lo = x - hi;
20    ((hi * hi - c) + 2.0 * hi * lo) + lo * lo
21}
22
23/// The type of a Lamé function, i.e. its factor `psi` in front of the polynomial (DLMF 29.12.1)
24#[derive(Clone, Copy)]
25enum Kind {
26    K,
27    L,
28    M,
29    N,
30}
31
32/// Lamé function of the first kind `E_n^p`, as `psi(s)` times a polynomial in `s^2 - h2`
33pub(crate) struct Lame {
34    h2: f64,
35    k2: f64,
36    odd: bool,
37    kind: Kind,
38    /// of ascending powers of `s^2 - h2`
39    coefs: Vec<f64>,
40}
41
42impl Lame {
43    /// `lame_coefficients`, or `None` for an invalid `p`
44    ///
45    /// Unlike in SciPy, the eigenpair of the symmetric tridiagonal matrix is computed without
46    /// LAPACK's `dstevr`, see [`tridiag`].
47    pub(crate) fn new(h2: f64, k2: f64, n: u32, p: u32) -> Option<Self> {
48        let (n, p) = (n as usize, p as usize);
49        let odd = n % 2 == 1;
50
51        let r = n / 2;
52        let alpha = h2;
53        let beta = k2 - h2;
54        let gamma = alpha - beta;
55
56        // the type, the order `tp` within that type, and the number of coefficients
57        let (kind, tp, size) = if p == 0 {
58            return None;
59        } else if p - 1 < r + 1 {
60            (Kind::K, p, r + 1)
61        } else if p - 1 < (n - r) + (r + 1) {
62            (Kind::L, p - (r + 1), n - r)
63        } else if p - 1 < (n - r) + (n - r) + (r + 1) {
64            (Kind::M, p - (n - r) - (r + 1), n - r)
65        } else if p - 1 < 2 * n + 1 {
66            (Kind::N, p - (n - r) - (n - r) - (r + 1), r)
67        } else {
68            return None;
69        };
70
71        // the tridiagonal matrix with diagonal `d`, and `g` above and `f` below it
72        let mut g = vec![0.0; size];
73        let mut f = vec![0.0; size];
74        let mut d = vec![0.0; size];
75        let r = r as f64;
76        for i in 0..size {
77            let j = i as f64;
78            (g[i], f[i], d[i]) = match (kind, odd) {
79                (Kind::K, true) => (
80                    -(2.0 * j + 2.0) * (2.0 * j + 1.0) * beta,
81                    -alpha * (2.0 * (r - (j + 1.0)) + 2.0) * (2.0 * ((j + 1.0) + r) + 1.0),
82                    ((2.0 * r + 1.0) * (2.0 * r + 2.0) - 4.0 * j * j) * alpha
83                        + (2.0 * j + 1.0) * (2.0 * j + 1.0) * beta,
84                ),
85                (Kind::K, false) => (
86                    -(2.0 * j + 2.0) * (2.0 * j + 1.0) * beta,
87                    -alpha * (2.0 * (r - (j + 1.0)) + 2.0) * (2.0 * (r + (j + 1.0)) - 1.0),
88                    2.0 * r * (2.0 * r + 1.0) * alpha - 4.0 * j * j * gamma,
89                ),
90                (Kind::L, true) => (
91                    -(2.0 * j + 2.0) * (2.0 * j + 3.0) * beta,
92                    -alpha * (2.0 * (r - (j + 1.0)) + 2.0) * (2.0 * ((j + 1.0) + r) + 1.0),
93                    (2.0 * r + 1.0) * (2.0 * r + 2.0) * alpha
94                        - (2.0 * j + 1.0) * (2.0 * j + 1.0) * gamma,
95                ),
96                (Kind::L, false) => (
97                    -(2.0 * j + 2.0) * (2.0 * j + 3.0) * beta,
98                    -alpha * (2.0 * (r - (j + 1.0))) * (2.0 * (r + (j + 1.0)) + 1.0),
99                    (2.0 * r * (2.0 * r + 1.0) - (2.0 * j + 1.0) * (2.0 * j + 1.0)) * alpha
100                        + (2.0 * j + 2.0) * (2.0 * j + 2.0) * beta,
101                ),
102                (Kind::M, true) => (
103                    -(2.0 * j + 2.0) * (2.0 * j + 1.0) * beta,
104                    -alpha * (2.0 * (r - (j + 1.0)) + 2.0) * (2.0 * ((j + 1.0) + r) + 1.0),
105                    ((2.0 * r + 1.0) * (2.0 * r + 2.0) - (2.0 * j + 1.0) * (2.0 * j + 1.0)) * alpha
106                        + 4.0 * j * j * beta,
107                ),
108                (Kind::M, false) => (
109                    -(2.0 * j + 2.0) * (2.0 * j + 1.0) * beta,
110                    -alpha * (2.0 * (r - (j + 1.0))) * (2.0 * (r + (j + 1.0)) + 1.0),
111                    2.0 * r * (2.0 * r + 1.0) * alpha - (2.0 * j + 1.0) * (2.0 * j + 1.0) * gamma,
112                ),
113                (Kind::N, true) => (
114                    -(2.0 * j + 2.0) * (2.0 * j + 3.0) * beta,
115                    -alpha * (2.0 * (r - (j + 1.0))) * (2.0 * ((j + 1.0) + r) + 3.0),
116                    (2.0 * r + 1.0) * (2.0 * r + 2.0) * alpha
117                        - (2.0 * j + 2.0) * (2.0 * j + 2.0) * gamma,
118                ),
119                (Kind::N, false) => (
120                    -(2.0 * j + 2.0) * (2.0 * j + 3.0) * beta,
121                    -alpha * (2.0 * (r - (j + 1.0))) * (2.0 * (r + (j + 1.0)) + 1.0),
122                    2.0 * r * (2.0 * r + 1.0) * alpha - (2.0 * j + 2.0) * (2.0 * j + 2.0) * alpha
123                        + (2.0 * j + 1.0) * (2.0 * j + 1.0) * beta,
124                ),
125            };
126        }
127
128        // the diagonal similarity transform `ss` that makes it symmetric
129        let mut ss = vec![1.0; size];
130        for i in 1..size {
131            ss[i] = (g[i - 1] / f[i - 1]).sqrt() * ss[i - 1];
132        }
133        let dd: Vec<f64> = (0..size - 1).map(|i| g[i] * ss[i] / ss[i + 1]).collect();
134
135        // the eigenvector of the `tp`-th smallest eigenvalue
136        let eigv = tridiag::eigvec(&d, &dd, tridiag::eigvals(&d, &dd)[tp - 1]);
137        let eigv: Vec<f64> = eigv.iter().zip(&ss).map(|(v, s)| v / s).collect();
138
139        // the coefficients of the polynomial in `s^2 - h2`, monic in `s^2`, so
140        // `v_j (-h2)^(size - 1 - j) / v_last`, with the exponents kept apart
141        //
142        // Unlike in SciPy, not of the one in `1 - s^2 / h2`, whose normalization by
143        // `(-h2)^(size - 1)` underflows for small `h2` and large `n`.
144        let (m_h, e_h) = frexp_f64(-h2);
145        let (m_last, e_last) = frexp_f64(eigv[size - 1]);
146        // `(-h2)^(size - 1 - j) / v_last = m 2^e`
147        let (mut m, mut e) = (1.0 / m_last, -e_last);
148        let mut coefs = vec![0.0; size];
149        for (c, &v) in coefs.iter_mut().zip(&eigv).rev() {
150            let (m_v, e_v) = frexp_f64(v);
151            *c = ldexp_f64(m_v * m, e_v + e);
152            let (m_next, e_next) = frexp_f64(m * m_h);
153            (m, e) = (m_next, e + e_next + e_h);
154        }
155        Some(Self {
156            h2,
157            k2,
158            odd,
159            kind,
160            coefs,
161        })
162    }
163
164    /// `ellip_harm_eval`
165    ///
166    /// Unlike in SciPy, `s^2 - h2` and `s^2 - k2` are computed with [`sq_sub`].
167    pub(crate) fn eval(&self, s: f64, signm: f64, signn: f64) -> f64 {
168        self.eval_with(s, sq_sub(s, self.h2), sq_sub(s, self.k2), signm, signn)
169    }
170
171    /// [`Self::eval`], with `s^2 - h2` and `s^2 - k2` given, e.g. without cancellation
172    ///
173    /// Unlike in SciPy, their square roots are taken separately, and without `s^2` if that
174    /// overflows, so that they can't overflow needlessly.
175    pub(crate) fn eval_with(&self, s: f64, s2_h2: f64, s2_k2: f64, signm: f64, signn: f64) -> f64 {
176        let (h2, k2) = (self.h2, self.k2);
177        // `sqrt(|s^2 - c|)`
178        let root = |s2_c: f64, c: f64| {
179            if s2_c.is_finite() {
180                s2_c.abs().sqrt()
181            } else {
182                s.abs() * (1.0 - c / s / s).abs().sqrt()
183            }
184        };
185        // `pow(s, n - 2 r)` and `pow(s, 1 - n + 2 r)`
186        let (s_odd, s_even) = if self.odd { (s, 1.0) } else { (1.0, s) };
187        let psi = match self.kind {
188            Kind::K => s_odd,
189            Kind::L => s_even * signm * root(s2_h2, h2),
190            Kind::M => s_even * signn * root(s2_k2, k2),
191            Kind::N => s_odd * signm * signn * root(s2_h2, h2) * root(s2_k2, k2),
192        };
193
194        let (&last, rest) = self.coefs.split_last().unwrap();
195        let pp = rest.iter().rev().fold(last, |pp, &c| pp * s2_h2 + c);
196        pp * psi
197    }
198}
199
200/// Ellipsoidal harmonic function $E^p_n(s)$
201///
202/// Also known as the Lamé function of the first kind, a solution of the Lamé equation
203///
204/// $$
205/// (s^2 - h^2)(s^2 - k^2)E^{\prime\prime}(s) + s(2s^2 - h^2 - k^2)E^\prime(s) +
206/// (a - n(n+1) s^2)E(s) = 0
207/// $$
208///
209/// for an eigenvalue $a$.
210///
211/// Corresponds to [`scipy.special.ellip_harm`][scipy].
212///
213/// [scipy]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ellip_harm.html
214///
215/// # Arguments
216/// - `h2`: $h^2$
217/// - `k2`: $k^2$, should be larger than `h2`
218/// - `n`: degree
219/// - `p`: order, `1 <= p <= 2n + 1`
220/// - `s`: coordinate
221/// - `signm`, `signn`: the sign, `+1.0` or `-1.0`, of the prefactor of the functions of type L
222///   (`signm`), M (`signn`), and N (`signm * signn`), see DLMF 29.12.1
223///
224/// Returns NaN if `p` or a sign is invalid.
225///
226/// # See also
227/// - [`ellip_harm_2`](crate::ellip_harm_2): Ellipsoidal harmonic function $F^p_n(s)$
228/// - [`ellip_normal`](crate::ellip_normal): Ellipsoidal harmonic normalization constant
229///   $\gamma^p_n$
230/// - [DLMF 29.12](https://dlmf.nist.gov/29.12)
231#[must_use]
232pub fn ellip_harm(h2: f64, k2: f64, n: u32, p: u32, s: f64, signm: f64, signn: f64) -> f64 {
233    if signm.abs() != 1.0 || signn.abs() != 1.0 {
234        return f64::NAN;
235    }
236    Lame::new(h2, k2, n, p).map_or(f64::NAN, |e| e.eval(s, signm, signn))
237}