Skip to main content

lib_jsl_electromagnetics/fields/domain/
structured.rs

1//! Structured surface and volume domains.
2//!
3//! A [`Domain`] is a tensor-product grid of [`Axis`] samples in a native coordinate system. It
4//! knows the position of every sample and the quadrature weight of every sample **with the
5//! Jacobian included**, so `Σ w f` approximates `∫ f dA` (surfaces), `∫ f dV` (volumes) or
6//! `∫ f dΩ` (the far-field sphere). Integrals elsewhere in the crate always use these weights and
7//! never form a Jacobian themselves.
8//!
9//! | Kind | Axes (in order) | Element |
10//! |------|-----------------|---------|
11//! | plane | `x`, `y` at height `z₀` | `dx dy` |
12//! | sphere | `θ`, `φ` at radius `R` | `R² sin θ dθ dφ` |
13//! | far-field sphere | `θ`, `φ` (directions) | `sin θ dθ dφ` (solid angle) |
14//! | cylinder | `φ`, `z` at radius `ρ₀` | `ρ₀ dφ dz` |
15//! | box | `x`, `y`, `z` | `dx dy dz` |
16//! | spherical shell | `r`, `θ`, `φ` | `r² sin θ dr dθ dφ` |
17//! | cylindrical volume | `ρ`, `φ`, `z` | `ρ dρ dφ dz` |
18//!
19//! Azimuth axes must be periodic with period `2π`; polar axes must lie within `[0, π]`; radii
20//! must be non-negative. Samples are stored row-major (the last axis varies fastest).
21
22use super::axis::Axis;
23use crate::coordinates::systems::{CoordinateSystem, Position};
24use lib_jsl_core::ErrorsJSL;
25use std::f64::consts::{PI, TAU};
26
27/// The geometry a [`Domain`] describes.
28#[derive(Debug, Clone, Copy, PartialEq)]
29pub enum DomainKind {
30    /// The plane `z = z0`, axes `(x, y)`.
31    Plane { z0: f64 },
32    /// The sphere of radius `radius`, axes `(θ, φ)`.
33    Sphere { radius: f64 },
34    /// Directions on the sphere at infinity (far fields), axes `(θ, φ)`; positions are unit vectors.
35    FarFieldSphere,
36    /// The cylinder `ρ = radius`, axes `(φ, z)`.
37    Cylinder { radius: f64 },
38    /// A Cartesian box, axes `(x, y, z)`.
39    Box,
40    /// A spherical shell or ball, axes `(r, θ, φ)`.
41    SphericalShell,
42    /// A cylindrical volume, axes `(ρ, φ, z)`.
43    CylindricalVolume,
44}
45
46impl DomainKind {
47    /// The coordinate system the axes are expressed in.
48    pub fn system(self) -> CoordinateSystem {
49        match self {
50            DomainKind::Plane { .. } | DomainKind::Box => CoordinateSystem::Cartesian,
51            DomainKind::Sphere { .. } | DomainKind::FarFieldSphere | DomainKind::SphericalShell => CoordinateSystem::Spherical,
52            DomainKind::Cylinder { .. } | DomainKind::CylindricalVolume => CoordinateSystem::Cylindrical,
53        }
54    }
55
56    pub fn is_surface(self) -> bool {
57        matches!(self, DomainKind::Plane { .. } | DomainKind::Sphere { .. } | DomainKind::FarFieldSphere | DomainKind::Cylinder { .. })
58    }
59
60    /// The number of axes: 2 for surfaces, 3 for volumes.
61    pub fn dimension(self) -> usize {
62        if self.is_surface() { 2 } else { 3 }
63    }
64}
65
66/// A tensor-product grid with quadrature weights; see the module documentation.
67#[derive(Debug, Clone, PartialEq)]
68pub struct Domain {
69    kind: DomainKind,
70    axes: Vec<Axis>,
71    weights: Vec<f64>,
72}
73
74fn check_polar(a: &Axis) -> Result<(), ErrorsJSL> {
75    if a.is_periodic() || a.first() < -1e-12 || a.last() > PI + 1e-12 {
76        return Err(ErrorsJSL::InvalidInputRange("A polar axis must be non-periodic within [0, π]."));
77    }
78    Ok(())
79}
80
81fn check_azimuth(a: &Axis) -> Result<(), ErrorsJSL> {
82    if a.period().is_none_or(|p| (p - TAU).abs() > 1e-9) {
83        return Err(ErrorsJSL::InvalidInputRange("An azimuth axis must be periodic with period 2π."));
84    }
85    Ok(())
86}
87
88fn check_plain(a: &Axis) -> Result<(), ErrorsJSL> {
89    if a.is_periodic() {
90        return Err(ErrorsJSL::InvalidInputRange("This axis must not be periodic."));
91    }
92    Ok(())
93}
94
95fn check_radial(a: &Axis) -> Result<(), ErrorsJSL> {
96    check_plain(a)?;
97    if a.first() < 0.0 {
98        return Err(ErrorsJSL::InvalidInputRange("A radial axis must be non-negative."));
99    }
100    Ok(())
101}
102
103impl Domain {
104    fn build(kind: DomainKind, axes: Vec<Axis>) -> Self {
105        let mut d = Domain { kind, axes, weights: Vec::new() };
106        d.weights = (0..d.len()).map(|f| d.compute_weight(&d.unflatten(f))).collect();
107        d
108    }
109
110    pub fn plane(x: Axis, y: Axis, z0: f64) -> Result<Self, ErrorsJSL> {
111        check_plain(&x)?;
112        check_plain(&y)?;
113        Ok(Self::build(DomainKind::Plane { z0 }, vec![x, y]))
114    }
115
116    pub fn sphere(radius: f64, theta: Axis, phi: Axis) -> Result<Self, ErrorsJSL> {
117        if radius.is_nan() || radius < 0.0 {
118            return Err(ErrorsJSL::InvalidInputRange("The sphere radius must be non-negative."));
119        }
120        check_polar(&theta)?;
121        check_azimuth(&phi)?;
122        Ok(Self::build(DomainKind::Sphere { radius }, vec![theta, phi]))
123    }
124
125    pub fn far_field_sphere(theta: Axis, phi: Axis) -> Result<Self, ErrorsJSL> {
126        check_polar(&theta)?;
127        check_azimuth(&phi)?;
128        Ok(Self::build(DomainKind::FarFieldSphere, vec![theta, phi]))
129    }
130
131    /// A far-field sphere with `n_theta` Gauss-Legendre polar nodes and `n_phi` uniform azimuths:
132    /// exact for band-limited patterns, never samples the poles.
133    pub fn far_field_gauss(n_theta: usize, n_phi: usize) -> Result<Self, ErrorsJSL> {
134        Self::far_field_sphere(Axis::gauss_legendre_polar(n_theta)?, Axis::periodic(0.0, TAU, n_phi)?)
135    }
136
137    /// A far-field sphere with uniform θ samples including both poles (`n_theta >= 2`), the usual
138    /// layout of measured or simulated patterns.
139    pub fn far_field_uniform(n_theta: usize, n_phi: usize) -> Result<Self, ErrorsJSL> {
140        Self::far_field_sphere(Axis::uniform(0.0, PI, n_theta)?, Axis::periodic(0.0, TAU, n_phi)?)
141    }
142
143    pub fn cylinder(radius: f64, phi: Axis, z: Axis) -> Result<Self, ErrorsJSL> {
144        if radius.is_nan() || radius < 0.0 {
145            return Err(ErrorsJSL::InvalidInputRange("The cylinder radius must be non-negative."));
146        }
147        check_azimuth(&phi)?;
148        check_plain(&z)?;
149        Ok(Self::build(DomainKind::Cylinder { radius }, vec![phi, z]))
150    }
151
152    pub fn cartesian_box(x: Axis, y: Axis, z: Axis) -> Result<Self, ErrorsJSL> {
153        for a in [&x, &y, &z] {
154            check_plain(a)?;
155        }
156        Ok(Self::build(DomainKind::Box, vec![x, y, z]))
157    }
158
159    pub fn spherical_shell(r: Axis, theta: Axis, phi: Axis) -> Result<Self, ErrorsJSL> {
160        check_radial(&r)?;
161        check_polar(&theta)?;
162        check_azimuth(&phi)?;
163        Ok(Self::build(DomainKind::SphericalShell, vec![r, theta, phi]))
164    }
165
166    pub fn cylindrical_volume(rho: Axis, phi: Axis, z: Axis) -> Result<Self, ErrorsJSL> {
167        check_radial(&rho)?;
168        check_azimuth(&phi)?;
169        check_plain(&z)?;
170        Ok(Self::build(DomainKind::CylindricalVolume, vec![rho, phi, z]))
171    }
172
173    pub fn kind(&self) -> DomainKind {
174        self.kind
175    }
176
177    pub fn system(&self) -> CoordinateSystem {
178        self.kind.system()
179    }
180
181    pub fn axes(&self) -> &[Axis] {
182        &self.axes
183    }
184
185    pub fn axis(&self, i: usize) -> &Axis {
186        &self.axes[i]
187    }
188
189    pub fn is_surface(&self) -> bool {
190        self.kind.is_surface()
191    }
192
193    pub fn is_far_field(&self) -> bool {
194        self.kind == DomainKind::FarFieldSphere
195    }
196
197    /// Samples per axis.
198    pub fn shape(&self) -> Vec<usize> {
199        self.axes.iter().map(Axis::len).collect()
200    }
201
202    /// Total number of samples.
203    pub fn len(&self) -> usize {
204        self.axes.iter().map(Axis::len).product()
205    }
206
207    pub fn is_empty(&self) -> bool {
208        self.len() == 0
209    }
210
211    /// Row-major flat index of a multi-index.
212    pub fn flatten(&self, index: &[usize]) -> usize {
213        index.iter().zip(&self.axes).fold(0, |acc, (&i, a)| acc * a.len() + i)
214    }
215
216    /// Multi-index of a flat index.
217    pub fn unflatten(&self, mut flat: usize) -> Vec<usize> {
218        let mut out = vec![0; self.axes.len()];
219        for (slot, a) in out.iter_mut().zip(&self.axes).rev() {
220            *slot = flat % a.len();
221            flat /= a.len();
222        }
223        out
224    }
225
226    /// The native coordinates `(u₁, u₂, u₃)` of a sample (the fixed coordinate of a surface filled in).
227    pub fn native_coordinates(&self, index: &[usize]) -> [f64; 3] {
228        let u = |i: usize| self.axes[i].values()[index[i]];
229        match self.kind {
230            DomainKind::Plane { z0 } => [u(0), u(1), z0],
231            DomainKind::Sphere { radius } => [radius, u(0), u(1)],
232            DomainKind::FarFieldSphere => [1.0, u(0), u(1)],
233            DomainKind::Cylinder { radius } => [radius, u(0), u(1)],
234            DomainKind::Box | DomainKind::SphericalShell | DomainKind::CylindricalVolume => [u(0), u(1), u(2)],
235        }
236    }
237
238    /// The position of a sample in the domain's native system. On the far-field sphere this is
239    /// the unit direction (radius 1).
240    pub fn position(&self, index: &[usize]) -> Position {
241        Position { system: self.system(), coords: self.native_coordinates(index) }
242    }
243
244    /// The position of the sample with a given flat index.
245    pub fn position_flat(&self, flat: usize) -> Position {
246        self.position(&self.unflatten(flat))
247    }
248
249    fn compute_weight(&self, index: &[usize]) -> f64 {
250        let w: f64 = index.iter().zip(&self.axes).map(|(&i, a)| a.weights()[i]).product();
251        let c = self.native_coordinates(index);
252        let jacobian = match self.kind {
253            DomainKind::Plane { .. } | DomainKind::Box => 1.0,
254            DomainKind::Sphere { radius } => radius * radius * c[1].sin(),
255            DomainKind::FarFieldSphere => c[1].sin(),
256            DomainKind::Cylinder { radius } => radius,
257            DomainKind::SphericalShell => c[0] * c[0] * c[1].sin(),
258            DomainKind::CylindricalVolume => c[0],
259        };
260        w * jacobian
261    }
262
263    /// Quadrature weights (area, volume or solid-angle elements) in flat order.
264    pub fn weights(&self) -> &[f64] {
265        &self.weights
266    }
267
268    /// `Σ wᵢ fᵢ`: the integral of samples given in flat order.
269    pub fn integrate(&self, values: &[f64]) -> Result<f64, ErrorsJSL> {
270        if values.len() != self.len() {
271            return Err(ErrorsJSL::IncompatibleArraySizes((values.len(), self.len())));
272        }
273        Ok(values.iter().zip(&self.weights).map(|(v, w)| v * w).sum())
274    }
275
276    /// The integral of a function of position over the domain.
277    pub fn integrate_fn(&self, f: impl Fn(&Position) -> f64) -> f64 {
278        (0..self.len()).map(|i| self.weights[i] * f(&self.position_flat(i))).sum()
279    }
280
281    /// The total area, volume or solid angle according to the quadrature rule.
282    pub fn measure(&self) -> f64 {
283        self.weights.iter().sum()
284    }
285
286    /// The index of the polar axis on spherical domains.
287    fn polar_axis(&self) -> Option<usize> {
288        match self.kind {
289            DomainKind::Sphere { .. } | DomainKind::FarFieldSphere => Some(0),
290            DomainKind::SphericalShell => Some(1),
291            _ => None,
292        }
293    }
294
295    /// Continues a grid index across a pole on spherical domains: stepping to polar index
296    /// `theta_index` (which may be negative or beyond the last sample) at azimuth index
297    /// `phi_index` lands on the reflected sample `(θ' , φ + π)`. Requires the polar axis to be
298    /// symmetric about the pole being crossed (true for uniform grids that include the pole and
299    /// for Gauss-Legendre grids) and the azimuth grid to contain `φ + π`. Returns
300    /// `(theta_index, phi_index)` of the equivalent sample, or `None` if it is not on the grid.
301    pub fn across_pole(&self, theta_index: isize, phi_index: usize) -> Option<(usize, usize)> {
302        let pa = self.polar_axis()?;
303        let theta = &self.axes[pa];
304        let phi = &self.axes[pa + 1];
305        let n = theta.len() as isize;
306        let target_theta = if theta_index < 0 {
307            // Mirror about θ = 0: the sample at index |i| (or |i| - 1 if the pole itself is not sampled).
308            let k = if theta.first().abs() < 1e-12 { -theta_index } else { -theta_index - 1 };
309            *theta.values().get(k as usize)?
310        } else if theta_index >= n {
311            let over = theta_index - (n - 1);
312            let k = if (theta.last() - PI).abs() < 1e-12 { n - 1 - over } else { n - over };
313            *theta.values().get(usize::try_from(k).ok()?)?
314        } else {
315            return Some((theta_index as usize, phi_index));
316        };
317        let ti = theta.values().iter().position(|&v| (v - target_theta).abs() < 1e-9)?;
318        let p = phi.values()[phi_index] + PI;
319        let pj = phi.nearest(p);
320        let found = phi.values()[pj];
321        ((phi.reduce(found) - phi.reduce(p)).abs() < 1e-9 || ((phi.reduce(found) - phi.reduce(p)).abs() - TAU).abs() < 1e-9).then_some((ti, pj))
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    fn close(a: f64, b: f64, tol: f64) -> bool {
330        (a - b).abs() <= tol * b.abs().max(1.0)
331    }
332
333    #[test]
334    fn surface_measures() {
335        let plane = Domain::plane(Axis::uniform(-1.0, 1.0, 5).unwrap(), Axis::uniform(0.0, 3.0, 4).unwrap(), 2.0).unwrap();
336        assert!(close(plane.measure(), 6.0, 1e-14) && plane.is_surface() && plane.shape() == vec![5, 4]);
337        let r = 2.5;
338        let gauss = Domain::sphere(r, Axis::gauss_legendre_polar(8).unwrap(), Axis::periodic(0.0, TAU, 16).unwrap()).unwrap();
339        assert!(close(gauss.measure(), 4.0 * PI * r * r, 1e-13));
340        let uniform = Domain::sphere(r, Axis::uniform(0.0, PI, 91).unwrap(), Axis::periodic(0.0, TAU, 72).unwrap()).unwrap();
341        assert!(close(uniform.measure(), 4.0 * PI * r * r, 1e-3));
342        assert!(close(Domain::far_field_gauss(10, 20).unwrap().measure(), 4.0 * PI, 1e-13));
343        let cyl = Domain::cylinder(0.5, Axis::periodic(0.0, TAU, 32).unwrap(), Axis::uniform(0.0, 4.0, 9).unwrap()).unwrap();
344        assert!(close(cyl.measure(), TAU * 0.5 * 4.0, 1e-13));
345    }
346
347    #[test]
348    fn volume_measures() {
349        let b = Domain::cartesian_box(Axis::uniform(0.0, 1.0, 3).unwrap(), Axis::uniform(0.0, 2.0, 4).unwrap(), Axis::uniform(-1.0, 2.0, 5).unwrap()).unwrap();
350        assert!(close(b.measure(), 6.0, 1e-14) && !b.is_surface() && b.len() == 60);
351        let shell = Domain::spherical_shell(Axis::gauss_legendre(1.0, 2.0, 4).unwrap(), Axis::gauss_legendre_polar(6).unwrap(), Axis::periodic(0.0, TAU, 12).unwrap()).unwrap();
352        assert!(close(shell.measure(), 4.0 / 3.0 * PI * (8.0 - 1.0), 1e-13));
353        let cv = Domain::cylindrical_volume(Axis::gauss_legendre(0.0, 2.0, 3).unwrap(), Axis::periodic(0.0, TAU, 8).unwrap(), Axis::uniform(0.0, 3.0, 2).unwrap()).unwrap();
354        assert!(close(cv.measure(), PI * 4.0 * 3.0, 1e-13));
355    }
356
357    #[test]
358    fn weights_integrate_functions_with_the_right_jacobian() {
359        // ∫ cos²θ dΩ = 4π/3, ∫ sin²θ cos²φ dΩ = 4π/3, and spherical harmonics are orthogonal.
360        let s = Domain::far_field_gauss(8, 16).unwrap();
361        assert!(close(s.integrate_fn(|p| p.coords[1].cos().powi(2)), 4.0 * PI / 3.0, 1e-13));
362        assert!(close(s.integrate_fn(|p| (p.coords[1].sin() * p.coords[2].cos()).powi(2)), 4.0 * PI / 3.0, 1e-13));
363        let y10 = |p: &Position| p.coords[1].cos();
364        let y20 = |p: &Position| 3.0 * p.coords[1].cos().powi(2) - 1.0;
365        assert!(s.integrate_fn(|p| y10(p) * y20(p)).abs() < 1e-13);
366        // ∫ x² over a ball of radius 1 is 4π/15.
367        let ball = Domain::spherical_shell(Axis::gauss_legendre(0.0, 1.0, 6).unwrap(), Axis::gauss_legendre_polar(6).unwrap(), Axis::periodic(0.0, TAU, 12).unwrap()).unwrap();
368        assert!(close(ball.integrate_fn(|p| p.to_cartesian()[0].powi(2)), 4.0 * PI / 15.0, 1e-12));
369        // ∫ ρ² over a cylinder of radius 1 and height 2 is π.
370        let cv = Domain::cylindrical_volume(Axis::gauss_legendre(0.0, 1.0, 4).unwrap(), Axis::periodic(0.0, TAU, 4).unwrap(), Axis::uniform(0.0, 2.0, 2).unwrap()).unwrap();
371        assert!(close(cv.integrate_fn(|p| p.coords[0].powi(2)), PI, 1e-12));
372        let values: Vec<f64> = (0..s.len()).map(|i| y10(&s.position_flat(i)).powi(2)).collect();
373        assert!(close(s.integrate(&values).unwrap(), 4.0 * PI / 3.0, 1e-13));
374        assert!(s.integrate(&values[1..]).is_err());
375    }
376
377    #[test]
378    fn indexing_positions_and_poles() {
379        let d = Domain::far_field_uniform(7, 8).unwrap(); // θ = 0, 30°, ..., 180°; φ every 45°
380        for f in [0, 5, 17, d.len() - 1] {
381            assert_eq!(d.flatten(&d.unflatten(f)), f);
382        }
383        let p = d.position(&[3, 2]);
384        assert_eq!(p.system, CoordinateSystem::Spherical);
385        assert!(close(p.coords[0], 1.0, 1e-15) && close(p.coords[1], PI / 2.0, 1e-12) && close(p.coords[2], PI / 2.0, 1e-12));
386        assert!(d.is_far_field() && d.weights()[0] == 0.0); // the pole sample carries no solid angle
387        // One step past the north pole at φ = 45° lands on θ = 30°, φ = 225°.
388        assert_eq!(d.across_pole(-1, 1), Some((1, 5)));
389        assert_eq!(d.across_pole(7, 0), Some((5, 4))); // one past the south pole
390        assert_eq!(d.across_pole(3, 6), Some((3, 6))); // inside: unchanged
391        // Gauss-Legendre grids do not sample the poles: index -1 mirrors to index 0.
392        let g = Domain::far_field_gauss(4, 6).unwrap();
393        assert_eq!(g.across_pole(-1, 0), Some((0, 3)));
394        assert_eq!(g.across_pole(4, 1), Some((3, 4)));
395        // An odd number of azimuths has no sample at φ + π.
396        assert_eq!(Domain::far_field_uniform(5, 5).unwrap().across_pole(-1, 0), None);
397        let plane = Domain::plane(Axis::uniform(0.0, 1.0, 2).unwrap(), Axis::uniform(0.0, 1.0, 2).unwrap(), 0.0).unwrap();
398        assert_eq!(plane.across_pole(-1, 0), None);
399        assert_eq!(plane.native_coordinates(&[1, 0]), [1.0, 0.0, 0.0]);
400    }
401
402    #[test]
403    fn validation() {
404        let az = || Axis::periodic(0.0, TAU, 8).unwrap();
405        let polar = || Axis::uniform(0.0, PI, 5).unwrap();
406        assert!(Domain::sphere(-1.0, polar(), az()).is_err());
407        assert!(Domain::sphere(1.0, Axis::uniform(0.0, 4.0, 5).unwrap(), az()).is_err()); // θ beyond π
408        assert!(Domain::sphere(1.0, polar(), Axis::uniform(0.0, TAU, 8).unwrap()).is_err()); // φ not periodic
409        assert!(Domain::sphere(1.0, polar(), Axis::periodic(0.0, 1.0, 8).unwrap()).is_err()); // wrong period
410        assert!(Domain::cylinder(1.0, az(), az()).is_err());
411        assert!(Domain::spherical_shell(Axis::uniform(-1.0, 1.0, 3).unwrap(), polar(), az()).is_err());
412        assert!(Domain::cartesian_box(az(), polar(), polar()).is_err());
413        assert!(Domain::plane(polar(), az(), 0.0).is_err());
414    }
415}