Skip to main content

lib_jsl_electromagnetics/fields/
surface_calculus.rs

1//! Differential operators on surface domains: surface gradient, divergence and curl, and the
2//! Laplace-Beltrami operator.
3//!
4//! On a surface parametrised by its two axes `(u₁, u₂)` with scale factors `(h₁, h₂)` and unit
5//! tangents `û₁ × û₂ = n̂` (plane: `x̂, ŷ, ẑ`; sphere: `θ̂, φ̂, r̂`; cylinder: `φ̂, ẑ, ρ̂`):
6//!
7//! - `∇ₛ f = (1/h₁) ∂f/∂u₁ û₁ + (1/h₂) ∂f/∂u₂ û₂`
8//! - `∇ₛ·F = 1/(h₁h₂) [∂(h₂F₁)/∂u₁ + ∂(h₁F₂)/∂u₂]`
9//! - `n̂·∇×F = 1/(h₁h₂) [∂(h₂F₂)/∂u₁ - ∂(h₁F₁)/∂u₂]` (the surface curl, a scalar)
10//! - `∇ₛ×(f n̂) = ∇ₛf × n̂` (the vector surface curl of a scalar)
11//! - `Δₛ f = ∇ₛ·∇ₛ f` (Laplace-Beltrami)
12//!
13//! Vector operators act on the *tangential* part of a field (any normal component is ignored),
14//! with derivatives from the same Lagrange stencils as the volume operators. The far-field sphere
15//! is treated as the unit sphere of directions (angular operators, `h = (1, sin θ)`). Samples where
16//! a scale factor vanishes (the poles of a uniform sphere grid) are returned as NaN; Gauss-Legendre
17//! polar grids avoid them. Vector results are in the linear basis of the domain's system.
18//!
19//! See the book entry [Fields on grids](https://jwkunz.github.io/lib_jsl/book/em-arrays/fields.html).
20
21use crate::conventions::C64;
22use crate::coordinates::polarization::PolarizationBasis;
23use crate::fields::domain::{Domain, DomainKind};
24use crate::fields::field_container::{FieldQuantity, HarmonicField, Rank, TimeField};
25use crate::fields::interpolation::polar_coordinate;
26use crate::fields::vector_calculus::{FieldScalar, axis_stencil, derivative_weights};
27use lib_jsl_core::ErrorsJSL;
28use ndarray::{Array2, Array3};
29
30/// Indices of the tangential components `(û₁, û₂)` and of the normal one in the domain's
31/// linear basis.
32fn component_layout(domain: &Domain) -> Result<([usize; 2], usize), ErrorsJSL> {
33    match domain.kind() {
34        DomainKind::Plane { .. } => Ok(([0, 1], 2)),
35        DomainKind::Sphere { .. } | DomainKind::FarFieldSphere | DomainKind::Cylinder { .. } => Ok(([1, 2], 0)),
36        _ => Err(ErrorsJSL::InvalidInputRange("Surface operators need a plane, sphere or cylinder domain.")),
37    }
38}
39
40/// The scale factors `(h₁, h₂)` of the surface axes at a sample.
41fn surface_scales(domain: &Domain, idx: &[usize]) -> [f64; 2] {
42    let p = domain.position(idx).coords;
43    match domain.kind() {
44        DomainKind::Sphere { radius } => [radius, radius * p[1].sin()],
45        DomainKind::FarFieldSphere => [1.0, p[1].sin()],
46        DomainKind::Cylinder { radius } => [radius, 1.0],
47        _ => [1.0, 1.0],
48    }
49}
50
51/// The θ stencil on a sphere, continued across the poles onto the reflected samples
52/// `(θ', φ + π)` when the grid allows it. The quantities differentiated along θ here (`f`,
53/// `h₂F₁`, `h₂F₂`) are even under that reflection (the sign flips of `sin θ` and of `θ̂`, `φ̂`
54/// cancel), so the reflected samples are used as they are.
55fn polar_stencil(domain: &Domain, idx: &[usize]) -> Option<Vec<(usize, f64)>> {
56    let axis = domain.axis(0);
57    let n = axis.len() as isize;
58    if n < 5 || domain.across_pole(-1, 0).is_none() || domain.across_pole(n, 0).is_none() {
59        return None;
60    }
61    let i = idx[0] as isize;
62    let window: Vec<isize> = (i - 2..=i + 2).collect();
63    let nodes: Vec<f64> = window.iter().map(|&k| polar_coordinate(axis, k)).collect();
64    let weights = derivative_weights(&nodes, axis.values()[idx[0]]);
65    window
66        .iter()
67        .zip(weights)
68        .map(|(&k, w)| domain.across_pole(k, idx[1]).map(|(t, p)| (domain.flatten(&[t, p]), w)))
69        .collect()
70}
71
72fn derivative<T: FieldScalar>(domain: &Domain, idx: &[usize], axis: usize, value: &dyn Fn(usize) -> T) -> T {
73    let spherical = matches!(domain.kind(), DomainKind::Sphere { .. } | DomainKind::FarFieldSphere);
74    let stencil = if spherical && axis == 0 { polar_stencil(domain, idx) } else { None }.unwrap_or_else(|| axis_stencil(domain, idx, axis));
75    stencil.into_iter().fold(T::zero(), |acc, (k, w)| acc + value(k) * w)
76}
77
78fn gradient_core<T: FieldScalar>(domain: &Domain, f: &[T]) -> Vec<[T; 2]> {
79    (0..domain.len())
80        .map(|flat| {
81            let idx = domain.unflatten(flat);
82            let h = surface_scales(domain, &idx);
83            if h.iter().any(|v| v.abs() < 1e-300) {
84                return [T::nan(); 2];
85            }
86            [derivative(domain, &idx, 0, &|k| f[k]) * (1.0 / h[0]), derivative(domain, &idx, 1, &|k| f[k]) * (1.0 / h[1])]
87        })
88        .collect()
89}
90
91/// `∇ₛ·F` (`curl = false`) or `n̂·∇×F` (`curl = true`) of tangential components.
92fn divergence_or_curl_core<T: FieldScalar>(domain: &Domain, t: &[[T; 2]], curl: bool) -> Vec<T> {
93    let scales: Vec<[f64; 2]> = (0..domain.len()).map(|k| surface_scales(domain, &domain.unflatten(k))).collect();
94    (0..domain.len())
95        .map(|flat| {
96            let idx = domain.unflatten(flat);
97            let [h1, h2] = scales[flat];
98            if h1.abs() < 1e-300 || h2.abs() < 1e-300 {
99                return T::nan();
100            }
101            let inv = 1.0 / (h1 * h2);
102            if curl {
103                (derivative(domain, &idx, 0, &|k| t[k][1] * scales[k][1]) - derivative(domain, &idx, 1, &|k| t[k][0] * scales[k][0])) * inv
104            } else {
105                (derivative(domain, &idx, 0, &|k| t[k][0] * scales[k][1]) + derivative(domain, &idx, 1, &|k| t[k][1] * scales[k][0])) * inv
106            }
107        })
108        .collect()
109}
110
111fn native_basis(domain: &Domain) -> PolarizationBasis {
112    PolarizationBasis::Linear(domain.system())
113}
114
115/// Tangential components of a harmonic vector field in the domain's native basis.
116fn harmonic_tangential(field: &HarmonicField) -> Result<Vec<[C64; 2]>, ErrorsJSL> {
117    let ([a, b], _) = component_layout(field.domain())?;
118    let native = field.to_basis(native_basis(field.domain()))?;
119    Ok((0..native.len()).map(|i| [native.values()[[i, a]], native.values()[[i, b]]]).collect())
120}
121
122fn harmonic_from_tangential(template: &HarmonicField, t: Vec<[C64; 2]>) -> Result<HarmonicField, ErrorsJSL> {
123    let domain = template.domain().clone();
124    let ([a, b], _) = component_layout(&domain)?;
125    let mut values = Array2::<C64>::zeros((domain.len(), 3));
126    for (i, v) in t.iter().enumerate() {
127        values[[i, a]] = v[0];
128        values[[i, b]] = v[1];
129    }
130    HarmonicField::new(domain.clone(), FieldQuantity::Generic, Rank::Vector(native_basis(&domain)), template.frequency(), template.convention(), values)
131}
132
133fn harmonic_scalar(template: &HarmonicField, v: Vec<C64>) -> Result<HarmonicField, ErrorsJSL> {
134    let domain = template.domain().clone();
135    let values = Array2::from_shape_fn((domain.len(), 1), |(i, _)| v[i]);
136    HarmonicField::new(domain, FieldQuantity::Generic, Rank::Scalar, template.frequency(), template.convention(), values)
137}
138
139impl HarmonicField {
140    /// The surface gradient `∇ₛ f` of a scalar field on a surface.
141    pub fn surface_gradient(&self) -> Result<HarmonicField, ErrorsJSL> {
142        component_layout(self.domain())?;
143        if !self.is_scalar() {
144            return Err(ErrorsJSL::InvalidInputRange("The surface gradient needs a scalar field."));
145        }
146        let f: Vec<C64> = (0..self.len()).map(|i| self.scalar(i)).collect();
147        harmonic_from_tangential(self, gradient_core(self.domain(), &f))
148    }
149
150    /// The surface divergence `∇ₛ·F` of the tangential part of a vector field.
151    pub fn surface_divergence(&self) -> Result<HarmonicField, ErrorsJSL> {
152        if self.is_scalar() {
153            return Err(ErrorsJSL::InvalidInputRange("The surface divergence needs a vector field."));
154        }
155        let t = harmonic_tangential(self)?;
156        harmonic_scalar(self, divergence_or_curl_core(self.domain(), &t, false))
157    }
158
159    /// The surface curl `n̂·∇×F` of the tangential part of a vector field (a scalar field).
160    pub fn surface_curl(&self) -> Result<HarmonicField, ErrorsJSL> {
161        if self.is_scalar() {
162            return Err(ErrorsJSL::InvalidInputRange("The surface curl needs a vector field."));
163        }
164        let t = harmonic_tangential(self)?;
165        harmonic_scalar(self, divergence_or_curl_core(self.domain(), &t, true))
166    }
167
168    /// The vector surface curl `∇ₛ×(f n̂) = ∇ₛf × n̂` of a scalar field (tangential).
169    pub fn surface_vector_curl(&self) -> Result<HarmonicField, ErrorsJSL> {
170        let g = self.surface_gradient()?;
171        let t = harmonic_tangential(&g)?;
172        harmonic_from_tangential(self, t.into_iter().map(|[g1, g2]| [g2, -g1]).collect())
173    }
174
175    /// The Laplace-Beltrami operator `Δₛ f = ∇ₛ·∇ₛ f` of a scalar field.
176    pub fn laplace_beltrami(&self) -> Result<HarmonicField, ErrorsJSL> {
177        self.surface_gradient()?.surface_divergence()
178    }
179}
180
181impl TimeField {
182    fn per_step<F: Fn(&Domain, usize) -> Result<Vec<[f64; 3]>, ErrorsJSL>>(&self, rank: Rank, f: F) -> Result<TimeField, ErrorsJSL> {
183        let domain = self.domain().clone();
184        let (steps, n) = (self.time_axis().count, domain.len());
185        let c = rank.components();
186        let mut values = Array3::<f64>::zeros((steps, n, c));
187        for t in 0..steps {
188            let out = f(&domain, t)?;
189            for i in 0..n {
190                for k in 0..c {
191                    values[[t, i, k]] = out[i][k];
192                }
193            }
194        }
195        TimeField::new(domain, FieldQuantity::Generic, rank, self.time_axis(), values)
196    }
197
198    fn tangential_step(&self, t: usize) -> Result<Vec<[f64; 2]>, ErrorsJSL> {
199        let ([a, b], _) = component_layout(self.domain())?;
200        let Rank::Vector(basis) = self.rank() else {
201            return Err(ErrorsJSL::InvalidInputRange("This operator needs a vector field."));
202        };
203        let target = native_basis(self.domain());
204        (0..self.domain().len())
205            .map(|i| {
206                let v = basis.convert_real([self.values()[[t, i, 0]], self.values()[[t, i, 1]], self.values()[[t, i, 2]]], target, &self.domain().position_flat(i))?;
207                Ok([v[a], v[b]])
208            })
209            .collect()
210    }
211
212    /// `∇ₛ f` of a scalar time field at every step.
213    pub fn surface_gradient(&self) -> Result<TimeField, ErrorsJSL> {
214        let ([a, b], _) = component_layout(self.domain())?;
215        if self.rank() != Rank::Scalar {
216            return Err(ErrorsJSL::InvalidInputRange("The surface gradient needs a scalar field."));
217        }
218        self.per_step(Rank::Vector(native_basis(self.domain())), |d, t| {
219            let f: Vec<f64> = (0..d.len()).map(|i| self.values()[[t, i, 0]]).collect();
220            Ok(gradient_core(d, &f)
221                .into_iter()
222                .map(|g| {
223                    let mut v = [0.0; 3];
224                    v[a] = g[0];
225                    v[b] = g[1];
226                    v
227                })
228                .collect())
229        })
230    }
231
232    /// `∇ₛ·F` of the tangential part of a vector time field.
233    pub fn surface_divergence(&self) -> Result<TimeField, ErrorsJSL> {
234        component_layout(self.domain())?;
235        self.per_step(Rank::Scalar, |d, t| Ok(divergence_or_curl_core(d, &self.tangential_step(t)?, false).into_iter().map(|v| [v, 0.0, 0.0]).collect()))
236    }
237
238    /// `n̂·∇×F` of the tangential part of a vector time field.
239    pub fn surface_curl(&self) -> Result<TimeField, ErrorsJSL> {
240        component_layout(self.domain())?;
241        self.per_step(Rank::Scalar, |d, t| Ok(divergence_or_curl_core(d, &self.tangential_step(t)?, true).into_iter().map(|v| [v, 0.0, 0.0]).collect()))
242    }
243
244    /// `Δₛ f` of a scalar time field.
245    pub fn laplace_beltrami(&self) -> Result<TimeField, ErrorsJSL> {
246        self.surface_gradient()?.surface_divergence()
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253    use crate::conventions::TimeConvention;
254    use crate::fields::domain::Axis;
255    use crate::fields::field_container::TimeAxis;
256    use std::f64::consts::TAU;
257    use std::sync::Arc;
258
259    fn c(re: f64) -> C64 {
260        C64::new(re, 0.0)
261    }
262
263    fn sphere(radius: f64) -> Arc<Domain> {
264        Arc::new(Domain::sphere(radius, Axis::gauss_legendre_polar(48).unwrap(), Axis::periodic(0.0, TAU, 96).unwrap()).unwrap())
265    }
266
267    fn scalar(d: Arc<Domain>, f: impl Fn(&crate::coordinates::systems::Position) -> f64) -> HarmonicField {
268        HarmonicField::scalar_from_fn(d, FieldQuantity::Generic, 1.0, TimeConvention::PlusJ, |p| c(f(p))).unwrap()
269    }
270
271    #[test]
272    fn spherical_harmonics_are_laplace_beltrami_eigenfunctions() {
273        let r = 2.0;
274        let d = sphere(r);
275        for (l, f) in [(1, Box::new(|p: &crate::coordinates::systems::Position| p.coords[1].sin() * p.coords[2].cos()) as Box<dyn Fn(&_) -> f64>), (2, Box::new(|p: &crate::coordinates::systems::Position| 3.0 * p.coords[1].cos().powi(2) - 1.0))] {
276            let field = scalar(d.clone(), &f);
277            let lap = field.laplace_beltrami().unwrap();
278            let k = -(l * (l + 1)) as f64 / (r * r);
279            let worst = (0..d.len()).map(|i| (lap.scalar(i) - field.scalar(i) * k).norm()).fold(0.0, f64::max);
280            assert!(worst < 2e-3, "l = {l}: {worst}");
281        }
282    }
283
284    #[test]
285    fn gradient_divergence_theorem_and_curl_on_the_sphere() {
286        let r = 1.5;
287        let d = sphere(r);
288        // z = R cos θ: ∇ₛz = -sin θ θ̂ (the tangential part of ẑ).
289        let g = scalar(d.clone(), |p| r * p.coords[1].cos()).surface_gradient().unwrap();
290        assert_eq!(g.basis(), Some(PolarizationBasis::SPHERICAL));
291        for i in (0..d.len()).step_by(31) {
292            let t = d.position_flat(i).coords[1];
293            assert!((g.vector(i)[1] - c(-t.sin())).norm() < 1e-5 && g.vector(i)[2].norm() < 1e-9 && g.vector(i)[0].norm() == 0.0);
294        }
295        // The surface divergence integrates to zero over a closed surface.
296        let f = HarmonicField::vector_from_fn(d.clone(), FieldQuantity::Generic, PolarizationBasis::SPHERICAL, 1.0, TimeConvention::PlusJ, |p| {
297            let (t, ph) = (p.coords[1], p.coords[2]);
298            [c(5.0), c(t.sin() * ph.cos() + t.sin().powi(2)), c((2.0 * t).sin() * ph.sin())] // the radial part is ignored
299        })
300        .unwrap();
301        assert!(f.surface_divergence().unwrap().integrate().unwrap().norm() < 1e-6);
302        // Surface curl of a gradient vanishes; ∇ₛ·(∇ₛf × n̂) vanishes.
303        let h = scalar(d.clone(), |p| p.coords[1].cos().powi(3) + p.coords[1].sin() * p.coords[2].sin());
304        assert!(h.surface_gradient().unwrap().surface_curl().unwrap().values().iter().all(|v| v.norm() < 1e-3));
305        assert!(h.surface_vector_curl().unwrap().surface_divergence().unwrap().values().iter().all(|v| v.norm() < 1e-3));
306        // A rigid rotation about z, F = R sin θ φ̂, has surface curl 2 cos θ.
307        let rot = HarmonicField::vector_from_fn(d.clone(), FieldQuantity::Generic, PolarizationBasis::SPHERICAL, 1.0, TimeConvention::PlusJ, |p| [c(0.0), c(0.0), c(r * p.coords[1].sin())]).unwrap();
308        let curl = rot.surface_curl().unwrap();
309        assert!((0..d.len()).all(|i| (curl.scalar(i) - c(2.0 * d.position_flat(i).coords[1].cos())).norm() < 1e-4));
310    }
311
312    #[test]
313    fn plane_cylinder_and_far_field_domains() {
314        let plane = Arc::new(Domain::plane(Axis::uniform(-1.0, 1.0, 9).unwrap(), Axis::from_values(vec![0.0, 0.2, 0.5, 0.9, 1.0, 1.4]).unwrap(), 0.3).unwrap());
315        let f = scalar(plane.clone(), |p| p.coords[0] * p.coords[0] * p.coords[1]);
316        assert!((0..plane.len()).all(|i| {
317            let [x, y, _] = plane.position_flat(i).coords;
318            (f.laplace_beltrami().unwrap().scalar(i) - c(2.0 * y)).norm() < 1e-9 && (f.surface_gradient().unwrap().vector(i)[0] - c(2.0 * x * y)).norm() < 1e-9
319        }));
320        let swirl = HarmonicField::vector_from_fn(plane.clone(), FieldQuantity::Generic, PolarizationBasis::CARTESIAN, 1.0, TimeConvention::PlusJ, |p| [c(-p.coords[1]), c(p.coords[0]), c(7.0)]).unwrap();
321        assert!(swirl.surface_curl().unwrap().values().iter().all(|v| (v - c(2.0)).norm() < 1e-9));
322        assert!(swirl.surface_divergence().unwrap().values().iter().all(|v| v.norm() < 1e-9));
323        // Cylinder of radius 0.5: ∇ₛ z = ẑ, and F = z φ̂ has surface curl -1 (n̂ = ρ̂).
324        let cyl = Arc::new(Domain::cylinder(0.5, Axis::periodic(0.0, TAU, 32).unwrap(), Axis::uniform(0.0, 2.0, 9).unwrap()).unwrap());
325        let gz = scalar(cyl.clone(), |p| p.coords[2]).surface_gradient().unwrap();
326        assert!((0..cyl.len()).all(|i| (gz.vector(i)[2] - c(1.0)).norm() < 1e-9 && gz.vector(i)[1].norm() < 1e-9));
327        let zphi = HarmonicField::vector_from_fn(cyl.clone(), FieldQuantity::Generic, PolarizationBasis::CYLINDRICAL, 1.0, TimeConvention::PlusJ, |p| [c(0.0), c(p.coords[2]), c(0.0)]).unwrap();
328        assert!(zphi.surface_curl().unwrap().values().iter().all(|v| (v - c(-1.0)).norm() < 1e-9));
329        // Far-field sphere: the angular Laplacian of Y₂⁰ is -6 Y₂⁰.
330        let ff = Arc::new(Domain::far_field_gauss(48, 96).unwrap());
331        let y20 = scalar(ff.clone(), |p| 3.0 * p.coords[1].cos().powi(2) - 1.0);
332        let lap = y20.laplace_beltrami().unwrap();
333        assert!((0..ff.len()).all(|i| (lap.scalar(i) + y20.scalar(i) * 6.0).norm() < 2e-3));
334    }
335
336    #[test]
337    fn poles_volumes_and_time_fields() {
338        // A uniform grid samples the poles, where h_φ = 0: those results are NaN.
339        let uni = Arc::new(Domain::far_field_uniform(19, 24).unwrap());
340        let g = scalar(uni.clone(), |p| p.coords[1].cos()).surface_gradient().unwrap();
341        assert!(g.vector(0)[1].re.is_nan() && g.vector(uni.flatten(&[9, 3]))[1].re.is_finite());
342        let vol = Arc::new(Domain::cartesian_box(Axis::uniform(0.0, 1.0, 3).unwrap(), Axis::uniform(0.0, 1.0, 3).unwrap(), Axis::uniform(0.0, 1.0, 3).unwrap()).unwrap());
343        assert!(scalar(vol, |_| 1.0).surface_gradient().is_err());
344        let d = sphere(1.0);
345        assert!(scalar(d.clone(), |_| 1.0).surface_divergence().is_err());
346        // Time fields agree with the harmonic operators at each step.
347        let t = TimeAxis::new(0.0, 1.0, 2).unwrap();
348        let tf = TimeField::from_fn(d.clone(), FieldQuantity::Generic, Rank::Scalar, t, |p, time| vec![(1.0 + time) * (3.0 * p.coords[1].cos().powi(2) - 1.0)]).unwrap();
349        let lap = tf.laplace_beltrami().unwrap();
350        let i = d.flatten(&[7, 5]);
351        let y = 3.0 * d.position_flat(i).coords[1].cos().powi(2) - 1.0;
352        assert!((lap.at(1, i)[0] + 6.0 * 2.0 * y).abs() < 2e-3);
353        let tv = tf.surface_gradient().unwrap();
354        assert!(tv.surface_curl().unwrap().at(0, i)[0].abs() < 1e-3);
355    }
356
357    #[test]
358    fn operators_converge_at_fourth_order() {
359        let err = |nt: usize| {
360            let d = Arc::new(Domain::far_field_gauss(nt, 2 * nt).unwrap());
361            let y = scalar(d.clone(), |p| 3.0 * p.coords[1].cos().powi(2) - 1.0);
362            let lap = y.laplace_beltrami().unwrap();
363            (0..d.len()).map(|i| (lap.scalar(i) + y.scalar(i) * 6.0).norm()).fold(0.0, f64::max)
364        };
365        let (coarse, fine) = (err(24), err(48));
366        assert!(coarse / fine > 10.0, "{coarse} -> {fine}");
367    }
368}