Skip to main content

lib_jsl_electromagnetics/fields/domain/
axis.rs

1//! One-dimensional sample axes with built-in quadrature weights.
2//!
3//! An [`Axis`] holds strictly increasing sample coordinates and the weights `wᵢ` of a quadrature
4//! rule `∫ f(u) du ≈ Σ wᵢ f(uᵢ)` over the axis's extent. Jacobians are *not* included here: the
5//! domain that combines axes multiplies them in. Periodic axes (azimuth) cover one period and wrap.
6
7use lib_jsl_core::ErrorsJSL;
8use std::f64::consts::PI;
9
10/// How an axis's quadrature weights were constructed.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum QuadratureRule {
13    /// Trapezoid rule on the samples (endpoints included, any spacing).
14    Trapezoid,
15    /// Composite Simpson rule on uniform samples (odd count).
16    Simpson,
17    /// Rectangle rule on a periodic grid (spectrally accurate for smooth periodic integrands).
18    Periodic,
19    /// Gauss-Legendre nodes and weights (exact for polynomials of degree `2n - 1`).
20    GaussLegendre,
21    /// Gauss-Legendre in `cos θ` for a polar axis: nodes `θᵢ = acos(xᵢ)` with weights
22    /// `wᵢ / sin θᵢ`, so that multiplying by the `sin θ` Jacobian recovers the exact rule.
23    GaussLegendrePolar,
24}
25
26#[derive(Debug, Clone, PartialEq)]
27pub struct Axis {
28    values: Vec<f64>,
29    weights: Vec<f64>,
30    period: Option<f64>,
31    rule: QuadratureRule,
32}
33
34/// Gauss-Legendre nodes and weights on `[-1, 1]`, by Newton iteration on the Legendre recurrence.
35pub fn gauss_legendre_nodes(n: usize) -> (Vec<f64>, Vec<f64>) {
36    let mut x = vec![0.0; n];
37    let mut w = vec![0.0; n];
38    for i in 0..n.div_ceil(2) {
39        let mut z = (PI * (i as f64 + 0.75) / (n as f64 + 0.5)).cos();
40        let mut dp = 1.0;
41        for _ in 0..100 {
42            let (mut p0, mut p1) = (1.0, z);
43            for k in 2..=n {
44                let p2 = ((2 * k - 1) as f64 * z * p1 - (k - 1) as f64 * p0) / k as f64;
45                p0 = p1;
46                p1 = p2;
47            }
48            let p = if n == 0 { 1.0 } else if n == 1 { z } else { p1 };
49            let prev = if n == 1 { 1.0 } else { p0 };
50            dp = n as f64 * (z * p - prev) / (z * z - 1.0);
51            let dz = p / dp;
52            z -= dz;
53            if dz.abs() < 1e-16 {
54                break;
55            }
56        }
57        let wi = 2.0 / ((1.0 - z * z) * dp * dp);
58        x[i] = -z;
59        x[n - 1 - i] = z;
60        w[i] = wi;
61        w[n - 1 - i] = wi;
62    }
63    (x, w)
64}
65
66impl Axis {
67    fn check_increasing(values: &[f64]) -> Result<(), ErrorsJSL> {
68        if values.is_empty() || values.iter().any(|v| !v.is_finite()) || values.windows(2).any(|w| w[1] <= w[0]) {
69            return Err(ErrorsJSL::InvalidInputRange("Axis samples must be finite and strictly increasing."));
70        }
71        Ok(())
72    }
73
74    /// An axis on arbitrary increasing samples with trapezoid weights over `[first, last]`.
75    pub fn from_values(values: Vec<f64>) -> Result<Self, ErrorsJSL> {
76        Self::check_increasing(&values)?;
77        let n = values.len();
78        let weights = (0..n)
79            .map(|i| {
80                let left = if i > 0 { values[i] - values[i - 1] } else { 0.0 };
81                let right = if i + 1 < n { values[i + 1] - values[i] } else { 0.0 };
82                0.5 * (left + right)
83            })
84            .collect();
85        Ok(Axis { values, weights, period: None, rule: QuadratureRule::Trapezoid })
86    }
87
88    /// `n >= 2` uniform samples from `start` to `end` inclusive, trapezoid weights.
89    pub fn uniform(start: f64, end: f64, n: usize) -> Result<Self, ErrorsJSL> {
90        if n < 2 || end.partial_cmp(&start) != Some(std::cmp::Ordering::Greater) {
91            return Err(ErrorsJSL::InvalidInputRange("A uniform axis needs n >= 2 and end > start."));
92        }
93        Self::from_values((0..n).map(|i| start + (end - start) * i as f64 / (n - 1) as f64).collect())
94    }
95
96    /// Uniform samples with composite Simpson weights (`n` odd, at least 3).
97    pub fn simpson(start: f64, end: f64, n: usize) -> Result<Self, ErrorsJSL> {
98        if n < 3 || n.is_multiple_of(2) {
99            return Err(ErrorsJSL::InvalidInputRange("Simpson's rule needs an odd number (>= 3) of samples."));
100        }
101        let mut axis = Self::uniform(start, end, n)?;
102        let h = (end - start) / (n - 1) as f64;
103        axis.weights = (0..n).map(|i| h / 3.0 * if i == 0 || i == n - 1 { 1.0 } else if i % 2 == 1 { 4.0 } else { 2.0 }).collect();
104        axis.rule = QuadratureRule::Simpson;
105        Ok(axis)
106    }
107
108    /// `n` uniform samples covering one period `[offset, offset + period)` (the end point is the
109    /// start point again, so it is not repeated).
110    pub fn periodic(offset: f64, period: f64, n: usize) -> Result<Self, ErrorsJSL> {
111        if n == 0 || period.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
112            return Err(ErrorsJSL::InvalidInputRange("A periodic axis needs n >= 1 and a positive period."));
113        }
114        let h = period / n as f64;
115        Ok(Axis { values: (0..n).map(|i| offset + h * i as f64).collect(), weights: vec![h; n], period: Some(period), rule: QuadratureRule::Periodic })
116    }
117
118    /// Non-uniform samples within one period (trapezoid weights including the wrap-around gap).
119    pub fn periodic_from_values(values: Vec<f64>, period: f64) -> Result<Self, ErrorsJSL> {
120        Self::check_increasing(&values)?;
121        if values[values.len() - 1] - values[0] >= period {
122            return Err(ErrorsJSL::InvalidInputRange("Periodic samples must lie within one period."));
123        }
124        let n = values.len();
125        let gap = |i: usize| if i + 1 < n { values[i + 1] - values[i] } else { values[0] + period - values[n - 1] };
126        let weights = (0..n).map(|i| 0.5 * (gap(i) + gap((i + n - 1) % n))).collect();
127        Ok(Axis { values, weights, period: Some(period), rule: QuadratureRule::Periodic })
128    }
129
130    /// `n` Gauss-Legendre nodes on `[start, end]`.
131    pub fn gauss_legendre(start: f64, end: f64, n: usize) -> Result<Self, ErrorsJSL> {
132        if n == 0 || end.partial_cmp(&start) != Some(std::cmp::Ordering::Greater) {
133            return Err(ErrorsJSL::InvalidInputRange("Gauss-Legendre needs n >= 1 and end > start."));
134        }
135        let (x, w) = gauss_legendre_nodes(n);
136        let (mid, half) = (0.5 * (start + end), 0.5 * (end - start));
137        Ok(Axis { values: x.iter().map(|v| mid + half * v).collect(), weights: w.iter().map(|v| v * half).collect(), period: None, rule: QuadratureRule::GaussLegendre })
138    }
139
140    /// A polar (θ) axis on `(0, π)` with Gauss-Legendre nodes in `cos θ`; see
141    /// [`QuadratureRule::GaussLegendrePolar`]. Exact on the sphere for polynomials in `cos θ`
142    /// of degree up to `2n - 1`, and it never samples the poles.
143    pub fn gauss_legendre_polar(n: usize) -> Result<Self, ErrorsJSL> {
144        if n == 0 {
145            return Err(ErrorsJSL::InvalidInputRange("Need at least one node."));
146        }
147        let (x, w) = gauss_legendre_nodes(n);
148        // θ increases as cos θ decreases: reverse so the axis is increasing.
149        let values: Vec<f64> = x.iter().rev().map(|v| v.acos()).collect();
150        let weights: Vec<f64> = w.iter().rev().zip(&values).map(|(wi, t)| wi / t.sin()).collect();
151        Ok(Axis { values, weights, period: None, rule: QuadratureRule::GaussLegendrePolar })
152    }
153
154    pub fn values(&self) -> &[f64] {
155        &self.values
156    }
157
158    pub fn weights(&self) -> &[f64] {
159        &self.weights
160    }
161
162    pub fn len(&self) -> usize {
163        self.values.len()
164    }
165
166    pub fn is_empty(&self) -> bool {
167        self.values.is_empty()
168    }
169
170    pub fn period(&self) -> Option<f64> {
171        self.period
172    }
173
174    pub fn is_periodic(&self) -> bool {
175        self.period.is_some()
176    }
177
178    pub fn rule(&self) -> QuadratureRule {
179        self.rule
180    }
181
182    pub fn first(&self) -> f64 {
183        self.values[0]
184    }
185
186    pub fn last(&self) -> f64 {
187        self.values[self.values.len() - 1]
188    }
189
190    /// Whether every gap between samples (including the wrap gap on periodic axes) is equal.
191    pub fn is_uniform(&self) -> bool {
192        let n = self.len();
193        if n < 2 {
194            return true;
195        }
196        let h = self.values[1] - self.values[0];
197        let ok = self.values.windows(2).all(|w| ((w[1] - w[0]) - h).abs() <= 1e-9 * h.abs().max(1e-300));
198        ok && self.period.is_none_or(|p| ((self.values[0] + p - self.values[n - 1]) - h).abs() <= 1e-9 * h.abs())
199    }
200
201    /// Maps a possibly out-of-range index to a valid one: wrapping on periodic axes, `None`
202    /// beyond the ends otherwise.
203    pub fn wrap_index(&self, i: isize) -> Option<usize> {
204        let n = self.len() as isize;
205        if self.is_periodic() {
206            Some(i.rem_euclid(n) as usize)
207        } else if (0..n).contains(&i) {
208            Some(i as usize)
209        } else {
210            None
211        }
212    }
213
214    /// Reduces a coordinate into the axis's period (for periodic axes), starting at the first sample.
215    pub fn reduce(&self, u: f64) -> f64 {
216        match self.period {
217            Some(p) => self.values[0] + (u - self.values[0]).rem_euclid(p),
218            None => u,
219        }
220    }
221
222    /// The cell containing `u`: index `i` and fraction `t` in `[0, 1]` such that
223    /// `u = values[i] + t (values[i+1] - values[i])` (the "next" sample wraps on periodic axes).
224    /// `None` outside a non-periodic axis's range (inclusive of the end points), or for a
225    /// single-sample non-periodic axis unless `u` equals the sample.
226    pub fn locate(&self, u: f64) -> Option<(usize, f64)> {
227        let n = self.len();
228        if !u.is_finite() {
229            return None;
230        }
231        if let Some(p) = self.period {
232            let u = self.reduce(u);
233            let i = self.values.partition_point(|&v| v <= u).saturating_sub(1);
234            let next = if i + 1 < n { self.values[i + 1] } else { self.values[0] + p };
235            let width = next - self.values[i];
236            return Some((i, if width > 0.0 { (u - self.values[i]) / width } else { 0.0 }));
237        }
238        // Accept points a rounding error outside the ends (e.g. after a rotation) and clamp them.
239        let tol = 1e-9 * (self.values[n - 1] - self.values[0]).abs().max(self.values[0].abs()).max(self.values[n - 1].abs()).max(1e-300);
240        if u < self.values[0] - tol || u > self.values[n - 1] + tol {
241            return None;
242        }
243        let u = u.clamp(self.values[0], self.values[n - 1]);
244        if n == 1 {
245            return Some((0, 0.0));
246        }
247        let i = self.values.partition_point(|&v| v <= u).saturating_sub(1).min(n - 2);
248        Some((i, (u - self.values[i]) / (self.values[i + 1] - self.values[i])))
249    }
250
251    /// The index of the sample closest to `u` (wrapping on periodic axes; clamped otherwise).
252    pub fn nearest(&self, u: f64) -> usize {
253        let n = self.len();
254        if self.is_periodic() {
255            let (i, t) = self.locate(u).unwrap_or((0, 0.0));
256            return if t > 0.5 { (i + 1) % n } else { i };
257        }
258        let i = self.values.partition_point(|&v| v < u);
259        if i == 0 {
260            0
261        } else if i == n || u - self.values[i - 1] <= self.values[i] - u {
262            i - 1
263        } else {
264            i
265        }
266    }
267
268    /// The sum of the weights: the length the rule integrates over.
269    pub fn measure(&self) -> f64 {
270        self.weights.iter().sum()
271    }
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277
278    fn integrate(axis: &Axis, f: impl Fn(f64) -> f64) -> f64 {
279        axis.values().iter().zip(axis.weights()).map(|(&u, &w)| w * f(u)).sum()
280    }
281
282    #[test]
283    fn rules_integrate_what_they_should_exactly() {
284        let t = Axis::uniform(0.0, 2.0, 11).unwrap();
285        assert!((t.measure() - 2.0).abs() < 1e-14 && (integrate(&t, |x| 3.0 * x + 1.0) - 8.0).abs() < 1e-12);
286        let nu = Axis::from_values(vec![0.0, 0.1, 0.5, 1.7, 3.0]).unwrap();
287        assert!((integrate(&nu, |x| 2.0 * x - 1.0) - (9.0 - 3.0)).abs() < 1e-12); // linear functions exact
288        let s = Axis::simpson(0.0, 1.0, 9).unwrap();
289        assert!((integrate(&s, |x| x.powi(3) - x * x) - (0.25 - 1.0 / 3.0)).abs() < 1e-14); // cubics exact
290        let g = Axis::gauss_legendre(-1.0, 3.0, 5).unwrap();
291        assert!((integrate(&g, |x| x.powi(9)) - (3f64.powi(10) - 1.0) / 10.0).abs() < 1e-9); // degree 9 = 2n - 1
292        let (x1, w1) = gauss_legendre_nodes(1);
293        assert_eq!((x1, w1), (vec![0.0], vec![2.0]));
294        let p = Axis::periodic(0.0, std::f64::consts::TAU, 16).unwrap();
295        assert!((integrate(&p, |x| (3.0 * x).cos().powi(2)) - PI).abs() < 1e-12); // periodic: spectral
296        assert!((p.measure() - std::f64::consts::TAU).abs() < 1e-12);
297    }
298
299    #[test]
300    fn polar_gauss_legendre_integrates_on_the_sphere() {
301        let a = Axis::gauss_legendre_polar(6).unwrap();
302        assert!(a.values().windows(2).all(|w| w[1] > w[0]) && a.first() > 0.0 && a.last() < PI);
303        // ∫ f(θ) sin θ dθ with the Jacobian supplied by the caller.
304        let with_sin = |f: &dyn Fn(f64) -> f64| a.values().iter().zip(a.weights()).map(|(&t, &w)| w * t.sin() * f(t)).sum::<f64>();
305        assert!((with_sin(&|_| 1.0) - 2.0).abs() < 1e-13);
306        assert!((with_sin(&|t| t.cos().powi(2)) - 2.0 / 3.0).abs() < 1e-13);
307        assert!((with_sin(&|t| t.cos().powi(11))).abs() < 1e-13);
308    }
309
310    #[test]
311    fn periodic_axes_wrap_and_locate() {
312        let p = Axis::periodic(0.0, 360.0, 8).unwrap();
313        assert!(p.is_uniform() && p.is_periodic());
314        assert_eq!((p.wrap_index(-1), p.wrap_index(8), p.wrap_index(3)), (Some(7), Some(0), Some(3)));
315        assert_eq!(p.locate(350.0), Some((7, 35.0 / 45.0)));
316        assert_eq!(p.locate(-10.0), p.locate(350.0));
317        assert_eq!(p.nearest(359.0), 0);
318        assert_eq!(p.reduce(725.0), 5.0);
319        let np = Axis::periodic_from_values(vec![0.0, 1.0, 3.0], 4.0).unwrap();
320        assert_eq!(np.weights(), &[1.0, 1.5, 1.5]);
321        assert!(!np.is_uniform());
322        assert!(Axis::periodic_from_values(vec![0.0, 4.0], 4.0).is_err());
323    }
324
325    #[test]
326    fn bounded_axes_locate_and_validate() {
327        let a = Axis::from_values(vec![0.0, 1.0, 4.0]).unwrap();
328        assert_eq!((a.wrap_index(-1), a.wrap_index(3), a.wrap_index(2)), (None, None, Some(2)));
329        assert_eq!(a.locate(2.5), Some((1, 0.5)));
330        assert_eq!(a.locate(4.0), Some((1, 1.0)));
331        assert_eq!((a.locate(-0.1), a.locate(4.1), a.locate(f64::NAN)), (None, None, None));
332        assert_eq!((a.nearest(-5.0), a.nearest(2.4), a.nearest(2.6), a.nearest(9.0)), (0, 1, 2, 2));
333        assert!(Axis::from_values(vec![1.0, 1.0]).is_err() && Axis::from_values(vec![]).is_err());
334        assert!(Axis::uniform(1.0, 1.0, 3).is_err() && Axis::simpson(0.0, 1.0, 4).is_err());
335        assert!(Axis::periodic(0.0, 0.0, 4).is_err() && Axis::gauss_legendre(0.0, 1.0, 0).is_err());
336        let one = Axis::from_values(vec![2.0]).unwrap();
337        assert_eq!((one.locate(2.0), one.locate(2.1), one.measure()), (Some((0, 0.0)), None, 0.0));
338    }
339}