Skip to main content

lib_jsl_electromagnetics/fields/
interpolation.rs

1//! Sampling fields at arbitrary points and resampling them onto other domains.
2//!
3//! Interpolation is separable over a domain's axes with [`InterpolationMethod::Nearest`],
4//! [`InterpolationMethod::Linear`] (two-point) or [`InterpolationMethod::Cubic`] (four-point
5//! Lagrange, exact for cubics) stencils:
6//!
7//! - periodic (azimuth) axes wrap around;
8//! - bounded axes shift the stencil inside the grid near the ends (falling back to fewer points
9//!   when an axis is too short);
10//! - polar axes on spherical domains continue *across the pole* onto the reflected samples
11//!   `(θ', φ + π)` when the grid allows it (see [`Domain::across_pole`]), so queries between the
12//!   pole and the first Gauss-Legendre node, or stencils straddling a pole, are handled smoothly.
13//!
14//! Vector fields are interpolated in **Cartesian components**, which are smooth everywhere
15//! (spherical θ̂/φ̂ components flip sign across the poles), and the result is expressed in the
16//! field's basis at the query point.
17//!
18//! See the book entry [Fields on grids](https://jwkunz.github.io/lib_jsl/book/em-arrays/fields.html).
19
20use crate::conventions::C64;
21use crate::coordinates::systems::Position;
22use crate::fields::domain::{Axis, Domain, DomainKind};
23use crate::fields::field_container::{HarmonicField, Rank, TimeField};
24use lib_jsl_core::ErrorsJSL;
25use ndarray::{Array2, Array3};
26use std::f64::consts::{PI, TAU};
27use std::sync::Arc;
28
29/// The interpolation stencil.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum InterpolationMethod {
32    Nearest,
33    Linear,
34    Cubic,
35}
36
37/// What resampling does with target points outside the source domain.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Extrapolation {
40    /// Fail with an error.
41    Error,
42    /// Use zero there.
43    Zero,
44}
45
46/// How a stencil index along one axis maps to a sample.
47#[derive(Debug, Clone, Copy)]
48struct Tap {
49    /// The index along the axis, possibly outside `0..len` (polar continuation).
50    index: isize,
51    weight: f64,
52}
53
54fn lagrange_weights(nodes: &[f64], u: f64) -> Vec<f64> {
55    (0..nodes.len())
56        .map(|a| (0..nodes.len()).filter(|&b| b != a).map(|b| (u - nodes[b]) / (nodes[a] - nodes[b])).product())
57        .collect()
58}
59
60/// Turns candidate `(index, coordinate)` pairs and a cell into taps for the method.
61fn taps_for(method: InterpolationMethod, coords: &dyn Fn(isize) -> f64, cell: isize, lo: isize, hi: isize, u: f64) -> Vec<Tap> {
62    // `lo..=hi` is the range of indices that may be used.
63    let available = (hi - lo + 1).max(0) as usize;
64    let want = match method {
65        InterpolationMethod::Nearest => 1,
66        InterpolationMethod::Linear => 2,
67        InterpolationMethod::Cubic => 4,
68    }
69    .min(available.max(1));
70    if want == 1 {
71        let (a, b) = (cell.clamp(lo, hi), (cell + 1).clamp(lo, hi));
72        let pick = if (u - coords(a)).abs() <= (coords(b) - u).abs() { a } else { b };
73        return vec![Tap { index: pick, weight: 1.0 }];
74    }
75    let start = if want == 2 { cell } else { cell - 1 }.clamp(lo, hi + 1 - want as isize);
76    let idx: Vec<isize> = (start..start + want as isize).collect();
77    let nodes: Vec<f64> = idx.iter().map(|&i| coords(i)).collect();
78    lagrange_weights(&nodes, u).into_iter().zip(idx).map(|(w, index)| Tap { index, weight: w }).collect()
79}
80
81/// Virtual coordinate of index `k` on a polar axis continued across the poles.
82pub(crate) fn polar_coordinate(axis: &Axis, k: isize) -> f64 {
83    let n = axis.len() as isize;
84    let v = axis.values();
85    let north = axis.first().abs() < 1e-12;
86    let south = (axis.last() - PI).abs() < 1e-12;
87    if k < 0 {
88        let m = if north { -k } else { -k - 1 };
89        -v[m.clamp(0, n - 1) as usize]
90    } else if k >= n {
91        let over = k - (n - 1);
92        let m = if south { n - 1 - over } else { n - over };
93        TAU - v[m.clamp(0, n - 1) as usize]
94    } else {
95        v[k as usize]
96    }
97}
98
99impl Domain {
100    /// The coordinates of `p` along this domain's axes. Surface domains require the point to lie
101    /// on the surface (to a relative tolerance of 1e-6); the far-field sphere only uses the
102    /// direction.
103    pub fn axis_coordinates(&self, p: &Position) -> Result<Vec<f64>, ErrorsJSL> {
104        let q = p.in_system(self.system()).coords;
105        let off = |actual: f64, expected: f64| (actual - expected).abs() > 1e-6 * expected.abs().max(1.0);
106        match self.kind() {
107            DomainKind::Plane { z0 } => {
108                if off(q[2], z0) {
109                    return Err(ErrorsJSL::InvalidInputRange("The point is not on the plane."));
110                }
111                Ok(vec![q[0], q[1]])
112            }
113            DomainKind::Sphere { radius } => {
114                if off(q[0], radius) {
115                    return Err(ErrorsJSL::InvalidInputRange("The point is not on the sphere."));
116                }
117                Ok(vec![q[1], q[2]])
118            }
119            DomainKind::FarFieldSphere => Ok(vec![q[1], q[2]]),
120            DomainKind::Cylinder { radius } => {
121                if off(q[0], radius) {
122                    return Err(ErrorsJSL::InvalidInputRange("The point is not on the cylinder."));
123                }
124                Ok(vec![q[1], q[2]])
125            }
126            DomainKind::Box | DomainKind::SphericalShell | DomainKind::CylindricalVolume => Ok(q.to_vec()),
127        }
128    }
129
130    fn polar_axis_index(&self) -> Option<usize> {
131        match self.kind() {
132            DomainKind::Sphere { .. } | DomainKind::FarFieldSphere => Some(0),
133            DomainKind::SphericalShell => Some(1),
134            _ => None,
135        }
136    }
137
138    /// Whether the polar axis may be continued across its poles (needs φ + π on the grid).
139    fn pole_continuation(&self) -> bool {
140        self.polar_axis_index().is_some_and(|pa| {
141            let n = self.axis(pa).len() as isize;
142            self.across_pole(-1, 0).is_some() && self.across_pole(n, 0).is_some()
143        })
144    }
145
146    /// The interpolation stencil at `p`: `(flat sample index, weight)` pairs with weights summing
147    /// to one. Errors if `p` is outside the domain.
148    pub fn stencil(&self, p: &Position, method: InterpolationMethod) -> Result<Vec<(usize, f64)>, ErrorsJSL> {
149        let u = self.axis_coordinates(p)?;
150        let polar = self.polar_axis_index();
151        let continue_pole = self.pole_continuation();
152        let mut per_axis: Vec<Vec<Tap>> = Vec::with_capacity(u.len());
153        for (a, (axis, &ua)) in self.axes().iter().zip(&u).enumerate() {
154            let n = axis.len() as isize;
155            let taps = if let Some(period) = axis.period() {
156                let ur = axis.reduce(ua);
157                let (i, _) = axis.locate(ur).ok_or(ErrorsJSL::InvalidInputRange("The coordinate is not finite."))?;
158                let coords = move |k: isize| axis.values()[k.rem_euclid(n) as usize] + period * k.div_euclid(n) as f64;
159                let lo = if n >= 4 { -4 } else { 0 };
160                let hi = if n >= 4 { n + 3 } else { n - 1 };
161                taps_for(method, &coords, i as isize, lo, hi, ur)
162            } else if Some(a) == polar && continue_pole {
163                if !(0.0..=PI).contains(&ua) {
164                    return Err(ErrorsJSL::InvalidInputRange("The polar angle is outside [0, π]."));
165                }
166                let coords = |k: isize| polar_coordinate(axis, k);
167                // Find the cell in the extended coordinate list (indices -2..n+1).
168                let cell = (-2..n + 1).rev().find(|&k| coords(k) <= ua).unwrap_or(-2);
169                taps_for(method, &coords, cell, -2, n + 1, ua)
170            } else {
171                let (i, _) = axis.locate(ua).ok_or(ErrorsJSL::InvalidInputRange("The point is outside the domain."))?;
172                let coords = |k: isize| axis.values()[k as usize];
173                taps_for(method, &coords, i as isize, 0, n - 1, ua)
174            };
175            per_axis.push(taps);
176        }
177        // Tensor product, mapping out-of-range indices (wrap / across the pole) to samples.
178        let mut out = Vec::new();
179        let dims = per_axis.len();
180        let mut counters = vec![0usize; dims];
181        loop {
182            let mut index: Vec<isize> = (0..dims).map(|d| per_axis[d][counters[d]].index).collect();
183            let weight: f64 = (0..dims).map(|d| per_axis[d][counters[d]].weight).product();
184            for (d, axis) in self.axes().iter().enumerate() {
185                if axis.is_periodic() {
186                    index[d] = index[d].rem_euclid(axis.len() as isize);
187                }
188            }
189            if let Some(pa) = polar {
190                let (t, f) = (index[pa], index[pa + 1]);
191                let (t2, f2) = self.across_pole(t, f as usize).ok_or(ErrorsJSL::InvalidInputRange("The stencil cannot cross this pole."))?;
192                index[pa] = t2 as isize;
193                index[pa + 1] = f2 as isize;
194            }
195            let multi: Vec<usize> = index.iter().map(|&i| i as usize).collect();
196            out.push((self.flatten(&multi), weight));
197            // Advance the odometer.
198            let mut d = dims;
199            loop {
200                if d == 0 {
201                    return Ok(out);
202                }
203                d -= 1;
204                counters[d] += 1;
205                if counters[d] < per_axis[d].len() {
206                    break;
207                }
208                counters[d] = 0;
209            }
210        }
211    }
212}
213
214impl HarmonicField {
215    /// The field at `p`: scalar fields give one value, vector fields three components in the
216    /// field's basis at `p`.
217    pub fn sample_at(&self, p: &Position, method: InterpolationMethod) -> Result<Vec<C64>, ErrorsJSL> {
218        let stencil = self.domain().stencil(p, method)?;
219        match self.rank() {
220            Rank::Scalar => Ok(vec![stencil.iter().map(|&(i, w)| self.scalar(i) * w).sum()]),
221            Rank::Vector(basis) => {
222                let mut cart = [C64::new(0.0, 0.0); 3];
223                for &(i, w) in &stencil {
224                    let c = self.cartesian(i);
225                    for k in 0..3 {
226                        cart[k] += c[k] * w;
227                    }
228                }
229                Ok(basis.from_cartesian(cart, p, self.convention()).to_vec())
230            }
231        }
232    }
233
234    /// The field resampled onto `domain` (same basis, quantity, frequency and convention).
235    pub fn resample_to(&self, domain: Arc<Domain>, method: InterpolationMethod, outside: Extrapolation) -> Result<HarmonicField, ErrorsJSL> {
236        let c = self.rank().components();
237        let mut values = Array2::<C64>::zeros((domain.len(), c));
238        for i in 0..domain.len() {
239            let p = domain.position_flat(i);
240            match self.sample_at(&p, method) {
241                Ok(v) => (0..c).for_each(|k| values[[i, k]] = v[k]),
242                Err(e) if outside == Extrapolation::Error => return Err(e),
243                Err(_) => {}
244            }
245        }
246        HarmonicField::new(domain, self.quantity(), self.rank(), self.frequency(), self.convention(), values)
247    }
248}
249
250impl TimeField {
251    /// The field at `p` for every time step, components in the field's basis at `p`.
252    pub fn sample_at(&self, p: &Position, method: InterpolationMethod) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
253        let stencil = self.domain().stencil(p, method)?;
254        let steps = self.time_axis().count;
255        let mut out = Vec::with_capacity(steps);
256        for t in 0..steps {
257            match self.rank() {
258                Rank::Scalar => out.push(vec![stencil.iter().map(|&(i, w)| self.values()[[t, i, 0]] * w).sum()]),
259                Rank::Vector(basis) => {
260                    let mut cart = [0.0; 3];
261                    for &(i, w) in &stencil {
262                        let v = [self.values()[[t, i, 0]], self.values()[[t, i, 1]], self.values()[[t, i, 2]]];
263                        let c = basis.convert_real(v, crate::coordinates::PolarizationBasis::CARTESIAN, &self.domain().position_flat(i))?;
264                        for k in 0..3 {
265                            cart[k] += c[k] * w;
266                        }
267                    }
268                    out.push(crate::coordinates::PolarizationBasis::CARTESIAN.convert_real(cart, basis, p)?.to_vec());
269                }
270            }
271        }
272        Ok(out)
273    }
274
275    /// The field resampled onto `domain`.
276    pub fn resample_to(&self, domain: Arc<Domain>, method: InterpolationMethod, outside: Extrapolation) -> Result<TimeField, ErrorsJSL> {
277        let (steps, c) = (self.time_axis().count, self.rank().components());
278        let mut values = Array3::<f64>::zeros((steps, domain.len(), c));
279        for i in 0..domain.len() {
280            match self.sample_at(&domain.position_flat(i), method) {
281                Ok(v) => {
282                    for t in 0..steps {
283                        for k in 0..c {
284                            values[[t, i, k]] = v[t][k];
285                        }
286                    }
287                }
288                Err(e) if outside == Extrapolation::Error => return Err(e),
289                Err(_) => {}
290            }
291        }
292        TimeField::new(domain, self.quantity(), self.rank(), self.time_axis(), values)
293    }
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299    use crate::conventions::TimeConvention;
300    use crate::coordinates::PolarizationBasis;
301    use crate::fields::field_container::{FieldQuantity, TimeAxis};
302
303    fn c(re: f64) -> C64 {
304        C64::new(re, 0.0)
305    }
306
307    #[test]
308    fn plane_interpolation_orders() {
309        let d = Arc::new(Domain::plane(Axis::from_values(vec![0.0, 0.4, 1.0, 1.5, 2.5]).unwrap(), Axis::uniform(-1.0, 1.0, 6).unwrap(), 0.5).unwrap());
310        let f = |x: f64, y: f64| 1.0 + 2.0 * x - y + 0.5 * x * y;
311        let g = |x: f64, y: f64| x.powi(3) - 2.0 * x * y * y + y.powi(3);
312        let lin = HarmonicField::scalar_from_fn(d.clone(), FieldQuantity::Generic, 1.0, TimeConvention::PlusJ, |p| c(f(p.coords[0], p.coords[1]))).unwrap();
313        let cub = HarmonicField::scalar_from_fn(d.clone(), FieldQuantity::Generic, 1.0, TimeConvention::PlusJ, |p| c(g(p.coords[0], p.coords[1]))).unwrap();
314        for (x, y) in [(0.1, 0.3), (1.2, -0.9), (2.4, 0.95), (0.0, -1.0), (2.5, 1.0)] {
315            let p = Position::cartesian(x, y, 0.5);
316            assert!((lin.sample_at(&p, InterpolationMethod::Linear).unwrap()[0].re - f(x, y)).abs() < 1e-12);
317            assert!((cub.sample_at(&p, InterpolationMethod::Cubic).unwrap()[0].re - g(x, y)).abs() < 1e-11, "({x},{y})");
318        }
319        let near = lin.sample_at(&Position::cartesian(0.39, -0.95, 0.5), InterpolationMethod::Nearest).unwrap()[0].re;
320        assert!((near - f(0.4, -1.0)).abs() < 1e-12);
321        assert!(lin.sample_at(&Position::cartesian(3.0, 0.0, 0.5), InterpolationMethod::Linear).is_err()); // outside
322        assert!(lin.sample_at(&Position::cartesian(1.0, 0.0, 0.7), InterpolationMethod::Linear).is_err()); // off the plane
323        let stencil = d.stencil(&Position::cartesian(1.1, 0.1, 0.5), InterpolationMethod::Cubic).unwrap();
324        assert_eq!(stencil.len(), 16);
325        assert!((stencil.iter().map(|s| s.1).sum::<f64>() - 1.0).abs() < 1e-12);
326    }
327
328    #[test]
329    fn vector_fields_interpolate_smoothly_through_the_poles() {
330        // A constant ẑ field stored in the spherical basis: (cos θ, -sin θ, 0). Cartesian
331        // interpolation reproduces it exactly anywhere, including at and near the poles.
332        for d in [Domain::far_field_uniform(13, 24).unwrap(), Domain::far_field_gauss(8, 16).unwrap()] {
333            let d = Arc::new(d);
334            let z = HarmonicField::vector_from_fn(d.clone(), FieldQuantity::ElectricField, PolarizationBasis::SPHERICAL, 1.0, TimeConvention::PlusJ, |p| {
335                let (s, ct) = p.coords[1].sin_cos();
336                [c(ct), c(-s), c(0.0)]
337            })
338            .unwrap();
339            for method in [InterpolationMethod::Linear, InterpolationMethod::Cubic] {
340                for (t, ph) in [(0.0, 1.0), (0.01, 4.0), (1.3, 6.2), (PI - 0.005, 0.3), (PI, 2.0)] {
341                    let v = z.sample_at(&Position::spherical(1.0, t, ph), method).unwrap();
342                    let (s, ct) = f64::sin_cos(t);
343                    assert!((v[0] - c(ct)).norm() < 1e-12 && (v[1] - c(-s)).norm() < 1e-12 && v[2].norm() < 1e-12, "{method:?} θ={t} φ={ph}: {v:?}");
344                }
345            }
346        }
347    }
348
349    #[test]
350    fn smooth_scalars_on_the_sphere_converge_with_order_and_wrap_in_azimuth() {
351        let d = Arc::new(Domain::far_field_gauss(16, 32).unwrap());
352        let f = |t: f64, p: f64| (t.sin() * p.cos()).powi(2) + t.cos().powi(3) + (t.sin() * p.sin());
353        let field = HarmonicField::scalar_from_fn(d.clone(), FieldQuantity::Generic, 1.0, TimeConvention::PlusJ, |pos| c(f(pos.coords[1], pos.coords[2]))).unwrap();
354        let err = |m| {
355            let mut worst: f64 = 0.0;
356            for k in 0..60 {
357                let (t, p) = (0.02 + 3.1 * (k as f64 * 0.618).fract(), TAU * (k as f64 * 0.754).fract());
358                worst = worst.max((field.sample_at(&Position::spherical(1.0, t, p), m).unwrap()[0].re - f(t, p)).abs());
359            }
360            worst
361        };
362        let (lin, cub) = (err(InterpolationMethod::Linear), err(InterpolationMethod::Cubic));
363        assert!(cub < lin / 5.0 && cub < 5e-3, "linear {lin}, cubic {cub}");
364        // φ = 2π - ε and φ = -ε are the same point.
365        let a = field.sample_at(&Position::spherical(1.0, 1.0, TAU - 1e-3), InterpolationMethod::Cubic).unwrap()[0];
366        let b = field.sample_at(&Position::spherical(1.0, 1.0, -1e-3), InterpolationMethod::Cubic).unwrap()[0];
367        assert!((a - b).norm() < 1e-12);
368        // Resampling to another grid preserves the integral closely.
369        let uniform = Arc::new(Domain::far_field_uniform(91, 64).unwrap());
370        let moved = field.resample_to(uniform, InterpolationMethod::Cubic, Extrapolation::Error).unwrap();
371        let (i1, i2) = (field.integrate().unwrap().re, moved.integrate().unwrap().re);
372        assert!((i1 - i2).abs() < 1e-3 * i1.abs(), "{i1} {i2}");
373    }
374
375    #[test]
376    fn volumes_extrapolation_and_time_fields() {
377        let d = Arc::new(Domain::cartesian_box(Axis::uniform(0.0, 1.0, 4).unwrap(), Axis::uniform(0.0, 1.0, 4).unwrap(), Axis::uniform(0.0, 2.0, 5).unwrap()).unwrap());
378        let t = TimeAxis::new(0.0, 0.5, 3).unwrap();
379        let tf = TimeField::from_fn(d.clone(), FieldQuantity::ElectricField, Rank::Vector(PolarizationBasis::CARTESIAN), t, |p, time| vec![p.coords[0] + time, p.coords[1] * p.coords[2], 1.0]).unwrap();
380        let v = tf.sample_at(&Position::cartesian(0.3, 0.6, 1.1), InterpolationMethod::Linear).unwrap();
381        assert!((v[2][0] - 1.3).abs() < 1e-12 && (v[1][1] - 0.66).abs() < 1e-12 && (v[0][2] - 1.0).abs() < 1e-12);
382        // The same field read in the cylindrical basis at a point on the y axis: ρ̂ = ŷ, φ̂ = -x̂.
383        let cyl = TimeField::from_fn(d.clone(), FieldQuantity::ElectricField, Rank::Vector(PolarizationBasis::CYLINDRICAL), t, |_, _| vec![1.0, 0.0, 0.0]).unwrap();
384        let s = cyl.sample_at(&Position::cylindrical(0.5, PI / 2.0, 1.0), InterpolationMethod::Linear).unwrap();
385        assert!((s[0][0] - 1.0).abs() < 1e-9 && s[0][1].abs() < 1e-9);
386        // Resampling onto a larger box: Error refuses, Zero fills.
387        let big = Arc::new(Domain::cartesian_box(Axis::uniform(0.0, 2.0, 3).unwrap(), Axis::uniform(0.0, 1.0, 2).unwrap(), Axis::uniform(0.0, 2.0, 2).unwrap()).unwrap());
388        assert!(tf.resample_to(big.clone(), InterpolationMethod::Linear, Extrapolation::Error).is_err());
389        let filled = tf.resample_to(big, InterpolationMethod::Linear, Extrapolation::Zero).unwrap();
390        assert_eq!(filled.at(0, filled.domain().flatten(&[2, 0, 0])), vec![0.0, 0.0, 0.0]);
391        // Short axes fall back to lower-order stencils instead of failing.
392        let tiny = Arc::new(Domain::cartesian_box(Axis::uniform(0.0, 1.0, 2).unwrap(), Axis::uniform(0.0, 1.0, 2).unwrap(), Axis::uniform(0.0, 1.0, 2).unwrap()).unwrap());
393        assert_eq!(tiny.stencil(&Position::cartesian(0.5, 0.5, 0.5), InterpolationMethod::Cubic).unwrap().len(), 8);
394    }
395}