sphereql-core 0.3.0

Pure spherical math primitives for sphereQL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use std::f64::consts::{PI, TAU};

use crate::distance::angular_distance;
use crate::error::SphereQlError;
use crate::types::SphericalPoint;

/// Spatial containment test for a [`SphericalPoint`].
pub trait Contains {
    /// Returns `true` if `point` lies inside (or on the boundary of) this region.
    fn contains(&self, point: &SphericalPoint) -> bool;
}

/// A directional cone anchored at the sphere origin.
///
/// `apex` is retained for serialization and downstream tooling but is
/// not consulted by [`Cone::contains`]; containment is decided purely by
/// the angular distance from the test point to `axis`.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Cone {
    pub apex: SphericalPoint,
    pub axis: SphericalPoint,
    pub half_angle: f64,
}

impl Cone {
    /// Creates a new `Cone` with validation.
    ///
    /// Returns an error if `half_angle` is not in (0, π].
    pub fn new(
        apex: SphericalPoint,
        axis: SphericalPoint,
        half_angle: f64,
    ) -> Result<Self, SphereQlError> {
        if half_angle <= 0.0 || half_angle > PI {
            return Err(SphereQlError::InvalidConeAngle(half_angle));
        }
        Ok(Self {
            apex,
            axis,
            half_angle,
        })
    }
}

impl Contains for Cone {
    fn contains(&self, point: &SphericalPoint) -> bool {
        let point_unit = SphericalPoint::new_unchecked(1.0, point.theta, point.phi);
        let axis_unit = SphericalPoint::new_unchecked(1.0, self.axis.theta, self.axis.phi);
        angular_distance(&point_unit, &axis_unit) <= self.half_angle
    }
}

/// A spherical cap: all points within `half_angle` radians of `center` on S².
///
/// Unlike `Cone`, a cap has no apex — containment depends only on angular distance
/// from `center`, regardless of radial distance.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Cap {
    pub center: SphericalPoint,
    pub half_angle: f64,
}

impl Cap {
    /// Creates a new `Cap` with validation.
    ///
    /// Returns an error if `half_angle` is not in (0, π].
    pub fn new(center: SphericalPoint, half_angle: f64) -> Result<Self, SphereQlError> {
        if half_angle <= 0.0 || half_angle > PI {
            return Err(SphereQlError::InvalidCapAngle(half_angle));
        }
        Ok(Self { center, half_angle })
    }
}

impl Contains for Cap {
    fn contains(&self, point: &SphericalPoint) -> bool {
        let point_unit = SphericalPoint::new_unchecked(1.0, point.theta, point.phi);
        let center_unit = SphericalPoint::new_unchecked(1.0, self.center.theta, self.center.phi);
        angular_distance(&point_unit, &center_unit) <= self.half_angle
    }
}

/// A hollow spherical shell bounded by two radii.
///
/// Contains all points with `inner <= r <= outer`.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Shell {
    pub inner: f64,
    pub outer: f64,
}

impl Shell {
    /// Creates a new `Shell` with validation.
    ///
    /// Returns an error if `inner < 0` or `inner >= outer`.
    pub fn new(inner: f64, outer: f64) -> Result<Self, SphereQlError> {
        if inner < 0.0 || inner >= outer {
            return Err(SphereQlError::InvalidShellBounds { inner, outer });
        }
        Ok(Self { inner, outer })
    }
}

impl Contains for Shell {
    fn contains(&self, point: &SphericalPoint) -> bool {
        point.r >= self.inner && point.r <= self.outer
    }
}

/// A latitude band: all points with polar angle `phi` in [`phi_min`, `phi_max`].
///
/// `phi = 0` is the north pole; `phi = π` is the south pole.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Band {
    pub phi_min: f64,
    pub phi_max: f64,
}

impl Band {
    /// Creates a new `Band` with validation.
    ///
    /// Returns an error if `phi_min < 0`, `phi_min >= phi_max`, or `phi_max > π`.
    pub fn new(phi_min: f64, phi_max: f64) -> Result<Self, SphereQlError> {
        if phi_min < 0.0 || phi_min >= phi_max || phi_max > PI {
            return Err(SphereQlError::InvalidBandBounds { phi_min, phi_max });
        }
        Ok(Self { phi_min, phi_max })
    }
}

impl Contains for Band {
    fn contains(&self, point: &SphericalPoint) -> bool {
        point.phi >= self.phi_min && point.phi <= self.phi_max
    }
}

/// A longitude wedge: all points with azimuthal angle `theta` between `theta_min` and
/// `theta_max`.
///
/// Supports wrap-around: if `theta_min > theta_max`, the wedge spans across the 0/2π
/// boundary (e.g. 350° to 10°).
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Wedge {
    pub theta_min: f64,
    pub theta_max: f64,
}

impl Wedge {
    /// Creates a new `Wedge` with validation.
    ///
    /// Returns an error if either bound is outside [0, 2π) or if `theta_min == theta_max`.
    pub fn new(theta_min: f64, theta_max: f64) -> Result<Self, SphereQlError> {
        if !(0.0..TAU).contains(&theta_min)
            || !(0.0..TAU).contains(&theta_max)
            || theta_min == theta_max
        {
            return Err(SphereQlError::InvalidWedgeBounds {
                theta_min,
                theta_max,
            });
        }
        Ok(Self {
            theta_min,
            theta_max,
        })
    }

    fn wraps(&self) -> bool {
        self.theta_min > self.theta_max
    }
}

impl Contains for Wedge {
    fn contains(&self, point: &SphericalPoint) -> bool {
        if self.wraps() {
            point.theta >= self.theta_min || point.theta <= self.theta_max
        } else {
            point.theta >= self.theta_min && point.theta <= self.theta_max
        }
    }
}

/// A composable spatial region on S².
///
/// Regions can be primitive shapes (`Cone`, `Cap`, `Shell`, `Band`, `Wedge`) or
/// boolean combinations (`Intersection`, `Union`). All implement [`Contains`].
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum Region {
    Cone(Cone),
    Cap(Cap),
    Shell(Shell),
    Band(Band),
    Wedge(Wedge),
    Intersection(Vec<Region>),
    Union(Vec<Region>),
}

impl Region {
    /// Creates a region that contains points inside **all** of the given regions.
    pub fn intersection(regions: Vec<Region>) -> Self {
        Region::Intersection(regions)
    }

    /// Creates a region that contains points inside **any** of the given regions.
    pub fn union(regions: Vec<Region>) -> Self {
        Region::Union(regions)
    }
}

impl Contains for Region {
    fn contains(&self, point: &SphericalPoint) -> bool {
        match self {
            Region::Cone(c) => c.contains(point),
            Region::Cap(c) => c.contains(point),
            Region::Shell(s) => s.contains(point),
            Region::Band(b) => b.contains(point),
            Region::Wedge(w) => w.contains(point),
            Region::Intersection(regions) => regions.iter().all(|r| r.contains(point)),
            Region::Union(regions) => regions.iter().any(|r| r.contains(point)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::f64::consts::{FRAC_PI_2, FRAC_PI_4, PI};

    fn point(r: f64, theta: f64, phi: f64) -> SphericalPoint {
        SphericalPoint::new_unchecked(r, theta, phi)
    }

    // --- Cone tests ---

    #[test]
    fn cone_contains_point_inside() {
        let cone = Cone::new(point(0.0, 0.0, 0.0), point(1.0, 0.0, FRAC_PI_4), FRAC_PI_2).unwrap();
        let p = point(2.0, 0.0, FRAC_PI_4);
        assert!(cone.contains(&p));
    }

    #[test]
    fn cone_excludes_point_outside() {
        let cone = Cone::new(point(0.0, 0.0, 0.0), point(1.0, 0.0, 0.1), 0.05).unwrap();
        let p = point(1.0, PI, FRAC_PI_2);
        assert!(!cone.contains(&p));
    }

    #[test]
    fn cone_contains_point_on_boundary() {
        let half = FRAC_PI_4;
        let cone = Cone::new(point(0.0, 0.0, 0.0), point(1.0, 0.0, 0.0), half).unwrap();
        // axis is at phi=0 (north pole), point at phi=half_angle should be on boundary
        let p = point(1.0, 0.0, half);
        assert!(cone.contains(&p));
    }

    #[test]
    fn cone_various_half_angles() {
        // Narrow cone
        let narrow = Cone::new(point(0.0, 0.0, 0.0), point(1.0, 0.0, FRAC_PI_2), 0.01).unwrap();
        let near = point(1.0, 0.0, FRAC_PI_2);
        let far = point(1.0, 0.0, FRAC_PI_2 + 0.1);
        assert!(narrow.contains(&near));
        assert!(!narrow.contains(&far));

        // Full hemisphere
        let wide = Cone::new(point(0.0, 0.0, 0.0), point(1.0, 0.0, FRAC_PI_2), FRAC_PI_2).unwrap();
        assert!(wide.contains(&point(1.0, 0.5, FRAC_PI_2 + 0.3)));
    }

    #[test]
    fn cone_invalid_half_angle() {
        assert!(Cone::new(point(0.0, 0.0, 0.0), point(1.0, 0.0, 0.0), 0.0).is_err());
        assert!(Cone::new(point(0.0, 0.0, 0.0), point(1.0, 0.0, 0.0), -0.1).is_err());
        assert!(Cone::new(point(0.0, 0.0, 0.0), point(1.0, 0.0, 0.0), PI + 0.1).is_err());
        // PI is valid
        assert!(Cone::new(point(0.0, 0.0, 0.0), point(1.0, 0.0, 0.0), PI).is_ok());
    }

    // --- Cap tests ---

    #[test]
    fn cap_contains_point_inside() {
        let cap = Cap::new(point(1.0, 0.0, FRAC_PI_2), FRAC_PI_4).unwrap();
        let p = point(5.0, 0.0, FRAC_PI_2);
        assert!(cap.contains(&p));
    }

    #[test]
    fn cap_excludes_point_outside() {
        let cap = Cap::new(point(1.0, 0.0, 0.1), 0.05).unwrap();
        let p = point(1.0, PI, PI - 0.1);
        assert!(!cap.contains(&p));
    }

    #[test]
    fn cap_ignores_radius() {
        let cap = Cap::new(point(1.0, 0.0, FRAC_PI_2), FRAC_PI_4).unwrap();
        let near = point(0.1, 0.0, FRAC_PI_2);
        let far = point(1000.0, 0.0, FRAC_PI_2);
        assert!(cap.contains(&near));
        assert!(cap.contains(&far));
    }

    #[test]
    fn cap_invalid_half_angle() {
        assert!(Cap::new(point(1.0, 0.0, 0.0), 0.0).is_err());
        assert!(Cap::new(point(1.0, 0.0, 0.0), -1.0).is_err());
    }

    #[test]
    fn cap_error_is_cap_specific() {
        let err = Cap::new(point(1.0, 0.0, 0.0), 0.0).unwrap_err();
        assert!(
            matches!(err, SphereQlError::InvalidCapAngle(_)),
            "expected InvalidCapAngle, got {err:?}"
        );
    }

    // --- Shell tests ---

    #[test]
    fn shell_contains_point_inside() {
        let shell = Shell::new(1.0, 5.0).unwrap();
        assert!(shell.contains(&point(3.0, 0.0, 0.0)));
    }

    #[test]
    fn shell_excludes_point_outside() {
        let shell = Shell::new(1.0, 5.0).unwrap();
        assert!(!shell.contains(&point(0.5, 0.0, 0.0)));
        assert!(!shell.contains(&point(6.0, 0.0, 0.0)));
    }

    #[test]
    fn shell_boundary_inclusive() {
        let shell = Shell::new(1.0, 5.0).unwrap();
        assert!(shell.contains(&point(1.0, 0.0, 0.0)));
        assert!(shell.contains(&point(5.0, 0.0, 0.0)));
    }

    #[test]
    fn shell_invalid_bounds() {
        assert!(Shell::new(5.0, 1.0).is_err());
        assert!(Shell::new(3.0, 3.0).is_err());
        assert!(Shell::new(-1.0, 5.0).is_err());
    }

    // --- Band tests ---

    #[test]
    fn band_contains_point_inside() {
        let band = Band::new(FRAC_PI_4, 3.0 * FRAC_PI_4).unwrap();
        assert!(band.contains(&point(1.0, 0.0, FRAC_PI_2)));
    }

    #[test]
    fn band_excludes_point_outside() {
        let band = Band::new(FRAC_PI_4, FRAC_PI_2).unwrap();
        assert!(!band.contains(&point(1.0, 0.0, 0.1)));
        assert!(!band.contains(&point(1.0, 0.0, PI - 0.1)));
    }

    #[test]
    fn band_boundary_inclusive() {
        let band = Band::new(FRAC_PI_4, FRAC_PI_2).unwrap();
        assert!(band.contains(&point(1.0, 0.0, FRAC_PI_4)));
        assert!(band.contains(&point(1.0, 0.0, FRAC_PI_2)));
    }

    #[test]
    fn band_poles() {
        // Band covering north pole area
        let north = Band::new(0.0 + 0.001, FRAC_PI_4).unwrap();
        assert!(north.contains(&point(1.0, 0.0, 0.01)));
        assert!(!north.contains(&point(1.0, 0.0, FRAC_PI_2)));

        // Band covering south pole area
        let south = Band::new(3.0 * FRAC_PI_4, PI).unwrap();
        assert!(south.contains(&point(1.0, 0.0, PI - 0.1)));
        assert!(!south.contains(&point(1.0, 0.0, FRAC_PI_4)));
    }

    #[test]
    fn band_invalid_bounds() {
        assert!(Band::new(FRAC_PI_2, FRAC_PI_4).is_err());
        assert!(Band::new(FRAC_PI_4, FRAC_PI_4).is_err());
        assert!(Band::new(-0.1, FRAC_PI_2).is_err());
        assert!(Band::new(0.0, PI + 0.1).is_err());
    }

    // --- Wedge tests ---

    #[test]
    fn wedge_contains_normal_range() {
        let wedge = Wedge::new(0.5, 2.0).unwrap();
        assert!(wedge.contains(&point(1.0, 1.0, FRAC_PI_2)));
        assert!(!wedge.contains(&point(1.0, 3.0, FRAC_PI_2)));
    }

    #[test]
    fn wedge_wraparound() {
        // 350° to 10° in radians: ~6.1087 to ~0.1745
        let theta_min = 350.0_f64.to_radians();
        let theta_max = 10.0_f64.to_radians();
        let wedge = Wedge::new(theta_min, theta_max).unwrap();

        let inside_high = point(1.0, 355.0_f64.to_radians(), FRAC_PI_2);
        let inside_low = point(1.0, 5.0_f64.to_radians(), FRAC_PI_2);
        let outside = point(1.0, 180.0_f64.to_radians(), FRAC_PI_2);

        assert!(wedge.contains(&inside_high));
        assert!(wedge.contains(&inside_low));
        assert!(!wedge.contains(&outside));
    }

    #[test]
    fn wedge_boundary_inclusive() {
        let wedge = Wedge::new(1.0, 2.0).unwrap();
        assert!(wedge.contains(&point(1.0, 1.0, FRAC_PI_2)));
        assert!(wedge.contains(&point(1.0, 2.0, FRAC_PI_2)));
    }

    #[test]
    fn wedge_rejects_invalid_theta() {
        assert!(Wedge::new(-0.1, 1.0).is_err());
        assert!(Wedge::new(0.0, 7.0).is_err());
    }

    // --- Compound region tests ---

    #[test]
    fn intersection_shell_and_band() {
        let shell = Region::Shell(Shell::new(1.0, 5.0).unwrap());
        let band = Region::Band(Band::new(FRAC_PI_4, 3.0 * FRAC_PI_4).unwrap());
        let region = Region::intersection(vec![shell, band]);

        // Inside both
        assert!(region.contains(&point(3.0, 0.0, FRAC_PI_2)));
        // Inside shell but outside band
        assert!(!region.contains(&point(3.0, 0.0, 0.1)));
        // Inside band but outside shell
        assert!(!region.contains(&point(10.0, 0.0, FRAC_PI_2)));
    }

    #[test]
    fn union_two_caps() {
        let cap_a = Region::Cap(Cap::new(point(1.0, 0.0, 0.1), 0.2).unwrap());
        let cap_b = Region::Cap(Cap::new(point(1.0, 0.0, PI - 0.1), 0.2).unwrap());
        let region = Region::union(vec![cap_a, cap_b]);

        // Near north pole (cap_a)
        assert!(region.contains(&point(1.0, 0.0, 0.05)));
        // Near south pole (cap_b)
        assert!(region.contains(&point(1.0, 0.0, PI - 0.05)));
        // Equator (neither)
        assert!(!region.contains(&point(1.0, 0.0, FRAC_PI_2)));
    }

    #[test]
    fn empty_intersection_contains_everything() {
        let region = Region::intersection(vec![]);
        assert!(region.contains(&point(1.0, 0.0, FRAC_PI_2)));
    }

    #[test]
    fn empty_union_contains_nothing() {
        let region = Region::union(vec![]);
        assert!(!region.contains(&point(1.0, 0.0, FRAC_PI_2)));
    }

    // --- Region enum dispatch ---

    #[test]
    fn region_dispatches_to_inner_types() {
        let shell_region = Region::Shell(Shell::new(1.0, 5.0).unwrap());
        assert!(shell_region.contains(&point(3.0, 0.0, 0.0)));
        assert!(!shell_region.contains(&point(10.0, 0.0, 0.0)));

        let wedge_region = Region::Wedge(Wedge::new(0.5, 2.0).unwrap());
        assert!(wedge_region.contains(&point(1.0, 1.0, FRAC_PI_2)));
    }
}