Skip to main content

lib_jsl_electromagnetics/fields/
vector_calculus.rs

1//! Differential operators on volume fields: gradient, divergence, curl, Laplacians, and time
2//! derivatives.
3//!
4//! Spatial derivatives are taken along each native axis with Lagrange stencils (five points,
5//! fourth order, when an axis has at least five samples, otherwise three; any spacing; wrapping
6//! on periodic axes; shifted inside the axis near the ends of bounded ones), and
7//! combined into Cartesian derivatives through the local frame and scale factors,
8//! `∂/∂x_j = Σ_a (û_a)_j / h_a ∂/∂u_a`, which is the curvilinear formula applied to the smooth
9//! Cartesian components. Results on samples where a scale factor vanishes (r = 0, ρ = 0, or a pole
10//! inside a spherical shell) are undefined and returned as NaN. Gradients and curls are returned
11//! in the linear basis of the domain's coordinate system; use `to_basis` for another.
12//!
13//! These operators need volume domains with at least two samples per axis; surface fields have
14//! no full 3D derivatives.
15//!
16//! See the book entry [Fields on grids](https://jwkunz.github.io/lib_jsl/book/em-arrays/fields.html).
17
18use crate::conventions::C64;
19use crate::coordinates::polarization::PolarizationBasis;
20use crate::fields::domain::Domain;
21use crate::fields::field_container::{FieldQuantity, HarmonicField, Rank, TimeField};
22use lib_jsl_core::ErrorsJSL;
23use ndarray::{Array2, Array3};
24use num_traits::Zero;
25use std::ops::{Add, Mul, Sub};
26
27/// Values the operators work on: real (time domain) or complex (harmonic).
28pub trait FieldScalar: Copy + Zero + Add<Output = Self> + Sub<Output = Self> + Mul<f64, Output = Self> {
29    fn nan() -> Self;
30}
31impl FieldScalar for f64 {
32    fn nan() -> Self {
33        f64::NAN
34    }
35}
36impl FieldScalar for C64 {
37    fn nan() -> Self {
38        C64::new(f64::NAN, f64::NAN)
39    }
40}
41
42/// Weights `w` such that `f'(x) ≈ Σ w_a f(nodes_a)` (derivative of the Lagrange interpolant).
43pub(crate) fn derivative_weights(nodes: &[f64], x: f64) -> Vec<f64> {
44    let n = nodes.len();
45    (0..n)
46        .map(|a| {
47            let denom: f64 = (0..n).filter(|&b| b != a).map(|b| nodes[a] - nodes[b]).product();
48            let numer: f64 = (0..n).filter(|&m| m != a).map(|m| (0..n).filter(|&b| b != a && b != m).map(|b| x - nodes[b]).product::<f64>()).sum();
49            numer / denom
50        })
51        .collect()
52}
53
54fn require_volume(domain: &Domain) -> Result<(), ErrorsJSL> {
55    if domain.is_surface() {
56        return Err(ErrorsJSL::InvalidInputRange("Spatial derivatives need a volume domain."));
57    }
58    if domain.axes().iter().any(|a| a.len() < 2) {
59        return Err(ErrorsJSL::InvalidInputRange("Every axis needs at least two samples for derivatives."));
60    }
61    Ok(())
62}
63
64/// The derivative stencil along axis `a` at the multi-index `idx`: `(flat neighbour, weight)`
65/// pairs with `∂f/∂u_a ≈ Σ w f(neighbour)`. Five points (fourth order) when the axis has at least
66/// five samples, else three (or two); centred where possible, wrapping on periodic axes and
67/// shifted inside bounded ones near their ends.
68pub(crate) fn axis_stencil(domain: &Domain, idx: &[usize], a: usize) -> Vec<(usize, f64)> {
69    let axis = domain.axis(a);
70    let len = axis.len() as isize;
71    let i = idx[a] as isize;
72    let width: isize = if len >= 5 { 5 } else { len.min(3) };
73    let half = width / 2;
74    let start = if axis.is_periodic() { i - half } else { (i - half).clamp(0, len - width) };
75    let window: Vec<isize> = (start..start + width).collect();
76    let coord = |k: isize| match axis.period() {
77        Some(p) => axis.values()[k.rem_euclid(len) as usize] + p * k.div_euclid(len) as f64,
78        None => axis.values()[k as usize],
79    };
80    let nodes: Vec<f64> = window.iter().map(|&k| coord(k)).collect();
81    let weights = derivative_weights(&nodes, axis.values()[idx[a]]);
82    window
83        .iter()
84        .zip(weights)
85        .map(|(&k, w)| {
86            let mut neighbour = idx.to_vec();
87            neighbour[a] = axis.wrap_index(k).expect("stencil index inside the axis");
88            (domain.flatten(&neighbour), w)
89        })
90        .collect()
91}
92
93/// For each sample, the Jacobian `J[k][j] = ∂F_k/∂x_j` of Cartesian components `F_k`.
94// ANCHOR: cartesian_jacobians
95fn cartesian_jacobians<T: FieldScalar>(domain: &Domain, cart: &[[T; 3]]) -> Vec<[[T; 3]; 3]> {
96    let n = domain.len();
97    let mut out = vec![[[T::zero(); 3]; 3]; n];
98    for (flat, jac) in out.iter_mut().enumerate() {
99        let idx = domain.unflatten(flat);
100        let pos = domain.position(&idx);
101        let h = pos.scale_factors(domain.system());
102        if h.iter().any(|&v| v.abs() < 1e-300) {
103            *jac = [[T::nan(); 3]; 3];
104            continue;
105        }
106        let frame = pos.frame(domain.system());
107        for a in 0..domain.axes().len() {
108            let mut d = [T::zero(); 3];
109            for (neighbour, w) in axis_stencil(domain, &idx, a) {
110                let v = cart[neighbour];
111                for c in 0..3 {
112                    d[c] = d[c] + v[c] * w;
113                }
114            }
115            for c in 0..3 {
116                for j in 0..3 {
117                    jac[c][j] = jac[c][j] + d[c] * (frame[a][j] / h[a]);
118                }
119            }
120        }
121    }
122    out
123}
124// ANCHOR_END: cartesian_jacobians
125
126fn harmonic_cartesian(field: &HarmonicField) -> Vec<[C64; 3]> {
127    (0..field.len()).map(|i| field.cartesian(i)).collect()
128}
129
130fn vector_field_from_cartesian(template: &HarmonicField, cart: Vec<[C64; 3]>) -> Result<HarmonicField, ErrorsJSL> {
131    let domain = template.domain().clone();
132    let basis = PolarizationBasis::Linear(domain.system());
133    let mut values = Array2::<C64>::zeros((domain.len(), 3));
134    for (i, v) in cart.iter().enumerate() {
135        let b = basis.from_cartesian(*v, &domain.position_flat(i), template.convention());
136        for k in 0..3 {
137            values[[i, k]] = b[k];
138        }
139    }
140    HarmonicField::new(domain, FieldQuantity::Generic, Rank::Vector(basis), template.frequency(), template.convention(), values)
141}
142
143fn scalar_field(template: &HarmonicField, values: Vec<C64>) -> Result<HarmonicField, ErrorsJSL> {
144    let domain = template.domain().clone();
145    let arr = Array2::from_shape_fn((domain.len(), 1), |(i, _)| values[i]);
146    HarmonicField::new(domain, FieldQuantity::Generic, Rank::Scalar, template.frequency(), template.convention(), arr)
147}
148
149impl HarmonicField {
150    /// `∇f` of a scalar field (quantity `Generic`, linear basis of the domain's system).
151    pub fn gradient(&self) -> Result<HarmonicField, ErrorsJSL> {
152        require_volume(self.domain())?;
153        if !self.is_scalar() {
154            return Err(ErrorsJSL::InvalidInputRange("The gradient needs a scalar field."));
155        }
156        let cart: Vec<[C64; 3]> = (0..self.len()).map(|i| [self.scalar(i), C64::zero(), C64::zero()]).collect();
157        let j = cartesian_jacobians(self.domain(), &cart);
158        vector_field_from_cartesian(self, j.iter().map(|m| m[0]).collect())
159    }
160
161    /// `∇·F` of a vector field.
162    pub fn divergence(&self) -> Result<HarmonicField, ErrorsJSL> {
163        require_volume(self.domain())?;
164        if self.is_scalar() {
165            return Err(ErrorsJSL::InvalidInputRange("The divergence needs a vector field."));
166        }
167        let j = cartesian_jacobians(self.domain(), &harmonic_cartesian(self));
168        scalar_field(self, j.iter().map(|m| m[0][0] + m[1][1] + m[2][2]).collect())
169    }
170
171    /// `∇×F` of a vector field.
172    pub fn curl(&self) -> Result<HarmonicField, ErrorsJSL> {
173        require_volume(self.domain())?;
174        if self.is_scalar() {
175            return Err(ErrorsJSL::InvalidInputRange("The curl needs a vector field."));
176        }
177        let j = cartesian_jacobians(self.domain(), &harmonic_cartesian(self));
178        vector_field_from_cartesian(self, j.iter().map(|m| [m[2][1] - m[1][2], m[0][2] - m[2][0], m[1][0] - m[0][1]]).collect())
179    }
180
181    /// `∇²f` of a scalar field (as `∇·∇f`).
182    pub fn laplacian(&self) -> Result<HarmonicField, ErrorsJSL> {
183        self.gradient()?.divergence()
184    }
185
186    /// The vector Laplacian `∇²F`, the scalar Laplacian of each Cartesian component.
187    pub fn vector_laplacian(&self) -> Result<HarmonicField, ErrorsJSL> {
188        require_volume(self.domain())?;
189        if self.is_scalar() {
190            return Err(ErrorsJSL::InvalidInputRange("The vector Laplacian needs a vector field."));
191        }
192        let cart = harmonic_cartesian(self);
193        let mut out = vec![[C64::zero(); 3]; self.len()];
194        for k in 0..3 {
195            let comp: Vec<[C64; 3]> = cart.iter().map(|v| [v[k], C64::zero(), C64::zero()]).collect();
196            let grad: Vec<[C64; 3]> = cartesian_jacobians(self.domain(), &comp).iter().map(|m| m[0]).collect();
197            let second = cartesian_jacobians(self.domain(), &grad);
198            for (o, m) in out.iter_mut().zip(&second) {
199                o[k] = m[0][0] + m[1][1] + m[2][2];
200            }
201        }
202        vector_field_from_cartesian(self, out)
203    }
204
205    /// `∂F/∂t`, which for a phasor is multiplication by `+jω` (or `-iω`).
206    pub fn time_derivative(&self) -> HarmonicField {
207        self.scaled(self.convention().time_derivative(self.omega()))
208    }
209}
210
211impl TimeField {
212    fn cartesian_step(&self, t: usize) -> Result<Vec<[f64; 3]>, ErrorsJSL> {
213        (0..self.domain().len())
214            .map(|i| match self.rank() {
215                Rank::Scalar => Ok([self.values()[[t, i, 0]], 0.0, 0.0]),
216                Rank::Vector(b) => b.convert_real([self.values()[[t, i, 0]], self.values()[[t, i, 1]], self.values()[[t, i, 2]]], PolarizationBasis::CARTESIAN, &self.domain().position_flat(i)),
217            })
218            .collect()
219    }
220
221    fn assemble_steps(&self, rank: Rank, per_step: Vec<Vec<[f64; 3]>>) -> Result<TimeField, ErrorsJSL> {
222        let domain = self.domain().clone();
223        let (steps, n, c) = (per_step.len(), domain.len(), rank.components());
224        let mut values = Array3::<f64>::zeros((steps, n, c));
225        for (t, cart) in per_step.iter().enumerate() {
226            for i in 0..n {
227                let v = match rank {
228                    Rank::Scalar => [cart[i][0], 0.0, 0.0],
229                    Rank::Vector(b) => PolarizationBasis::CARTESIAN.convert_real(cart[i], b, &domain.position_flat(i))?,
230                };
231                for k in 0..c {
232                    values[[t, i, k]] = v[k];
233                }
234            }
235        }
236        TimeField::new(domain, FieldQuantity::Generic, rank, self.time_axis(), values)
237    }
238
239    fn vector_rank(&self) -> Rank {
240        Rank::Vector(PolarizationBasis::Linear(self.domain().system()))
241    }
242
243    /// `∇f` of a scalar time field, at every time step.
244    pub fn gradient(&self) -> Result<TimeField, ErrorsJSL> {
245        require_volume(self.domain())?;
246        if self.rank() != Rank::Scalar {
247            return Err(ErrorsJSL::InvalidInputRange("The gradient needs a scalar field."));
248        }
249        let steps = (0..self.time_axis().count).map(|t| Ok(cartesian_jacobians(self.domain(), &self.cartesian_step(t)?).iter().map(|m| m[0]).collect())).collect::<Result<Vec<_>, ErrorsJSL>>()?;
250        self.assemble_steps(self.vector_rank(), steps)
251    }
252
253    /// `∇·F` of a vector time field.
254    pub fn divergence(&self) -> Result<TimeField, ErrorsJSL> {
255        require_volume(self.domain())?;
256        if self.rank() == Rank::Scalar {
257            return Err(ErrorsJSL::InvalidInputRange("The divergence needs a vector field."));
258        }
259        let steps = (0..self.time_axis().count).map(|t| Ok(cartesian_jacobians(self.domain(), &self.cartesian_step(t)?).iter().map(|m| [m[0][0] + m[1][1] + m[2][2], 0.0, 0.0]).collect())).collect::<Result<Vec<_>, ErrorsJSL>>()?;
260        self.assemble_steps(Rank::Scalar, steps)
261    }
262
263    /// `∇×F` of a vector time field.
264    pub fn curl(&self) -> Result<TimeField, ErrorsJSL> {
265        require_volume(self.domain())?;
266        if self.rank() == Rank::Scalar {
267            return Err(ErrorsJSL::InvalidInputRange("The curl needs a vector field."));
268        }
269        let steps = (0..self.time_axis().count)
270            .map(|t| Ok(cartesian_jacobians(self.domain(), &self.cartesian_step(t)?).iter().map(|m| [m[2][1] - m[1][2], m[0][2] - m[2][0], m[1][0] - m[0][1]]).collect()))
271            .collect::<Result<Vec<_>, ErrorsJSL>>()?;
272        self.assemble_steps(self.vector_rank(), steps)
273    }
274
275    /// `∂F/∂t` by second-order finite differences in time (one-sided at the ends).
276    pub fn time_derivative(&self) -> Result<TimeField, ErrorsJSL> {
277        let (steps, n, c) = self.values().dim();
278        if steps < 3 {
279            return Err(ErrorsJSL::InvalidInputRange("A time derivative needs at least three time steps."));
280        }
281        let dt = self.time_axis().step;
282        let v = self.values();
283        let mut out = Array3::<f64>::zeros((steps, n, c));
284        for i in 0..n {
285            for k in 0..c {
286                out[[0, i, k]] = (-3.0 * v[[0, i, k]] + 4.0 * v[[1, i, k]] - v[[2, i, k]]) / (2.0 * dt);
287                out[[steps - 1, i, k]] = (3.0 * v[[steps - 1, i, k]] - 4.0 * v[[steps - 2, i, k]] + v[[steps - 3, i, k]]) / (2.0 * dt);
288                for t in 1..steps - 1 {
289                    out[[t, i, k]] = (v[[t + 1, i, k]] - v[[t - 1, i, k]]) / (2.0 * dt);
290                }
291            }
292        }
293        TimeField::new(self.domain().clone(), FieldQuantity::Generic, self.rank(), self.time_axis(), out)
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300    use crate::conventions::TimeConvention;
301    use crate::fields::domain::Axis;
302    use crate::fields::field_container::TimeAxis;
303    use std::f64::consts::TAU;
304    use std::sync::Arc;
305
306    fn c(re: f64) -> C64 {
307        C64::new(re, 0.0)
308    }
309
310    fn cube() -> Arc<Domain> {
311        Arc::new(Domain::cartesian_box(Axis::uniform(-1.0, 1.0, 7).unwrap(), Axis::from_values(vec![0.0, 0.3, 0.5, 1.0, 1.2]).unwrap(), Axis::uniform(0.0, 2.0, 5).unwrap()).unwrap())
312    }
313
314    fn harmonic_scalar(d: Arc<Domain>, f: impl Fn([f64; 3]) -> f64) -> HarmonicField {
315        HarmonicField::scalar_from_fn(d, FieldQuantity::ScalarPotential, 1.0, TimeConvention::PlusJ, |p| c(f(p.to_cartesian()))).unwrap()
316    }
317
318    fn harmonic_vector(d: Arc<Domain>, f: impl Fn([f64; 3]) -> [f64; 3]) -> HarmonicField {
319        HarmonicField::vector_from_fn(d, FieldQuantity::Generic, PolarizationBasis::CARTESIAN, 1.0, TimeConvention::PlusJ, |p| f(p.to_cartesian()).map(c)).unwrap()
320    }
321
322    #[test]
323    fn exact_for_quadratics_on_a_nonuniform_box() {
324        let d = cube();
325        let f = harmonic_scalar(d.clone(), |[x, y, z]| x * x * y + 3.0 * z - y * z);
326        let g = f.gradient().unwrap();
327        for i in 0..d.len() {
328            let [x, y, z] = d.position_flat(i).to_cartesian();
329            let v = g.vector(i);
330            assert!((v[0] - c(2.0 * x * y)).norm() < 1e-10 && (v[1] - c(x * x - z)).norm() < 1e-10 && (v[2] - c(3.0 - y)).norm() < 1e-10);
331        }
332        // ∇²(x² + y² + z²) = 6, and the identities hold exactly for polynomials of this degree.
333        let r2 = harmonic_scalar(d.clone(), |[x, y, z]| x * x + y * y + z * z);
334        assert!(r2.laplacian().unwrap().values().iter().all(|v| (v - c(6.0)).norm() < 1e-9));
335        assert!(r2.gradient().unwrap().curl().unwrap().values().iter().all(|v| v.norm() < 1e-9));
336        let quad = harmonic_vector(d.clone(), |[x, y, z]| [y * z, x * x, x * y + z * z]);
337        assert!(quad.curl().unwrap().divergence().unwrap().values().iter().all(|v| v.norm() < 1e-9));
338        let vl = quad.vector_laplacian().unwrap();
339        assert!((0..d.len()).all(|i| (vl.vector(i)[0]).norm() < 1e-8 && (vl.vector(i)[1] - c(2.0)).norm() < 1e-8 && (vl.vector(i)[2] - c(2.0)).norm() < 1e-8));
340    }
341
342    #[test]
343    fn curvilinear_domains_match_the_analytic_operators() {
344        // Spherical shell: ∇·r = 3 and ∇(r²) = 2r r̂ (radial component 2r in the native basis).
345        let shell = Arc::new(Domain::spherical_shell(Axis::uniform(1.0, 2.0, 6).unwrap(), Axis::gauss_legendre_polar(10).unwrap(), Axis::periodic(0.0, TAU, 48).unwrap()).unwrap());
346        let pos = harmonic_vector(shell.clone(), |p| p);
347        let div = pos.divergence().unwrap();
348        assert!(div.values().iter().all(|v| (v - c(3.0)).norm() < 2e-3), "max err {}", div.values().iter().map(|v| (v - c(3.0)).norm()).fold(0.0, f64::max));
349        let g = harmonic_scalar(shell.clone(), |[x, y, z]| x * x + y * y + z * z).gradient().unwrap();
350        assert_eq!(g.basis(), Some(PolarizationBasis::SPHERICAL));
351        for i in (0..shell.len()).step_by(37) {
352            let r = shell.position_flat(i).coords[0];
353            let v = g.vector(i);
354            assert!((v[0] - c(2.0 * r)).norm() < 2e-3 * r && v[1].norm() < 2e-3 && v[2].norm() < 2e-3);
355        }
356        // Cylindrical volume: the rotation field (-y, x, 0) has curl 2ẑ and no divergence.
357        let cyl = Arc::new(Domain::cylindrical_volume(Axis::uniform(0.5, 2.0, 5).unwrap(), Axis::periodic(0.0, TAU, 64).unwrap(), Axis::uniform(0.0, 1.0, 3).unwrap()).unwrap());
358        let swirl = harmonic_vector(cyl.clone(), |[x, y, _]| [-y, x, 0.0]);
359        let curl = swirl.curl().unwrap();
360        assert!((0..cyl.len()).all(|i| (curl.vector(i)[2] - c(2.0)).norm() < 1e-5 && curl.vector(i)[0].norm() < 1e-5));
361        assert!(swirl.divergence().unwrap().values().iter().all(|v| v.norm() < 1e-5));
362    }
363
364    #[test]
365    fn singular_samples_surfaces_and_time_derivatives() {
366        // A ball including r = 0: the centre samples are flagged as NaN rather than wrong numbers.
367        let ball = Arc::new(Domain::spherical_shell(Axis::uniform(0.0, 1.0, 4).unwrap(), Axis::gauss_legendre_polar(4).unwrap(), Axis::periodic(0.0, TAU, 8).unwrap()).unwrap());
368        let div = harmonic_vector(ball.clone(), |p| p).divergence().unwrap();
369        assert!(div.scalar(0).re.is_nan() && div.scalar(ball.flatten(&[2, 1, 3])).re.is_finite());
370        let surf = Arc::new(Domain::far_field_gauss(4, 8).unwrap());
371        assert!(harmonic_scalar(surf, |_| 1.0).gradient().is_err());
372        let d = cube();
373        assert!(harmonic_scalar(d.clone(), |_| 1.0).divergence().is_err() && harmonic_vector(d.clone(), |p| p).gradient().is_err());
374        // Harmonic: ∂/∂t = jω.
375        let h = harmonic_scalar(d.clone(), |_| 2.0);
376        assert!((h.time_derivative().scalar(0) - C64::new(0.0, 2.0 * TAU)).norm() < 1e-12);
377        // Time domain: d/dt sin(ωt) = ω cos(ωt), second order.
378        let omega = 3.0;
379        let t = TimeAxis::new(0.0, 1e-3, 400).unwrap();
380        let tf = TimeField::from_fn(d.clone(), FieldQuantity::Generic, Rank::Scalar, t, |_, time| vec![(omega * time).sin()]).unwrap();
381        let dt = tf.time_derivative().unwrap();
382        for k in [0, 7, 200, 399] {
383            assert!((dt.at(k, 0)[0] - omega * (omega * t.time(k)).cos()).abs() < 1e-4, "step {k}");
384        }
385        assert!(TimeField::from_fn(d.clone(), FieldQuantity::Generic, Rank::Scalar, TimeAxis::new(0.0, 1.0, 2).unwrap(), |_, _| vec![0.0]).unwrap().time_derivative().is_err());
386        // Time-domain spatial operators agree with the harmonic ones at each step.
387        let tv = TimeField::from_fn(d.clone(), FieldQuantity::Generic, Rank::Vector(PolarizationBasis::CARTESIAN), TimeAxis::new(0.0, 1.0, 2).unwrap(), |p, time| {
388            let [x, y, _] = p.to_cartesian();
389            vec![-y * (1.0 + time), x, 0.0]
390        })
391        .unwrap();
392        let tc = tv.curl().unwrap();
393        assert!((tc.at(1, 10)[2] - 3.0).abs() < 1e-9 && tv.divergence().unwrap().at(0, 3)[0].abs() < 1e-9);
394        let tg = TimeField::from_fn(d.clone(), FieldQuantity::Generic, Rank::Scalar, TimeAxis::new(0.0, 1.0, 1).unwrap(), |p, _| vec![p.to_cartesian()[2] * 2.0]).unwrap().gradient().unwrap();
395        assert!((tg.at(0, 4)[2] - 2.0).abs() < 1e-12);
396    }
397}