1use super::axis::Axis;
23use crate::coordinates::systems::{CoordinateSystem, Position};
24use lib_jsl_core::ErrorsJSL;
25use std::f64::consts::{PI, TAU};
26
27#[derive(Debug, Clone, Copy, PartialEq)]
29pub enum DomainKind {
30 Plane { z0: f64 },
32 Sphere { radius: f64 },
34 FarFieldSphere,
36 Cylinder { radius: f64 },
38 Box,
40 SphericalShell,
42 CylindricalVolume,
44}
45
46impl DomainKind {
47 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 pub fn dimension(self) -> usize {
62 if self.is_surface() { 2 } else { 3 }
63 }
64}
65
66#[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 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 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 pub fn shape(&self) -> Vec<usize> {
199 self.axes.iter().map(Axis::len).collect()
200 }
201
202 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 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 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 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 pub fn position(&self, index: &[usize]) -> Position {
241 Position { system: self.system(), coords: self.native_coordinates(index) }
242 }
243
244 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 pub fn weights(&self) -> &[f64] {
265 &self.weights
266 }
267
268 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 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 pub fn measure(&self) -> f64 {
283 self.weights.iter().sum()
284 }
285
286 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 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 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 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 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 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(); 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); assert_eq!(d.across_pole(-1, 1), Some((1, 5)));
389 assert_eq!(d.across_pole(7, 0), Some((5, 4))); assert_eq!(d.across_pole(3, 6), Some((3, 6))); 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 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()); assert!(Domain::sphere(1.0, polar(), Axis::uniform(0.0, TAU, 8).unwrap()).is_err()); assert!(Domain::sphere(1.0, polar(), Axis::periodic(0.0, 1.0, 8).unwrap()).is_err()); 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}