affn 0.6.0

Affine geometry primitives: strongly-typed coordinate systems, reference frames, and centers for scientific computing.
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
//! # Spherical Position
//!
//! This module defines the core spherical [`Position`] type (center + frame + distance).
//!
//! ## Mathematical Model
//!
//! A spherical position represents a point in space using:
//! - **polar (θ)**: Latitude / declination / altitude — range `[-90°, +90°]`
//! - **azimuth (φ)**: Longitude / right ascension / azimuth — range `[0°, 360°)`
//! - **distance (r)**: Radial distance from the origin
//!
//! # Type Parameters
//! - `C`: The reference center (defines the origin)
//! - `F`: The reference frame (defines axis orientation)
//! - `U`: The length unit for the distance
//!
//! ## Example
//!
//! ```rust
//! use affn::spherical::Position;
//! use affn::frames::ReferenceFrame;
//! use affn::centers::ReferenceCenter;
//! use qtty::*;
//!
//! #[derive(Debug, Copy, Clone)]
//! struct WorldFrame;
//! impl ReferenceFrame for WorldFrame {
//!     fn frame_name() -> &'static str { "WorldFrame" }
//! }
//!
//! #[derive(Debug, Copy, Clone)]
//! struct WorldOrigin;
//! impl ReferenceCenter for WorldOrigin {
//!     type Params = ();
//!     fn center_name() -> &'static str { "WorldOrigin" }
//! }
//!
//! let pos = Position::<WorldOrigin, WorldFrame, Meter>::new_raw(
//!     45.0 * DEG,  // polar
//!     30.0 * DEG,  // azimuth
//!     1.0 * M      // distance
//! );
//! ```

use crate::centers;
use crate::frames;
use qtty::*;

use std::marker::PhantomData;

// Serde implementations in separate module
#[cfg(feature = "serde")]
#[path = "position_serde.rs"]
mod position_serde;

/// A spherical **position** (center + frame + distance).
///
/// This is the fundamental spherical coordinate type.
/// Spherical directions are represented separately by [`super::direction::Direction<F>`]
/// and intentionally have **no** reference center.
///
/// # Type Parameters
/// - `C`: The reference center (defines the origin)
/// - `F`: The reference frame (defines axis orientation)
/// - `U`: The length unit for the distance
///
/// # Note
///
/// `U` must be a [`LengthUnit`], not just any `Unit`. This ensures that spherical
/// positions always represent physical locations with a meaningful distance.
#[derive(Debug, Clone, Copy)]
pub struct Position<C: centers::ReferenceCenter, F: frames::ReferenceFrame, U: LengthUnit> {
    /// Polar angle (θ) - latitude, declination, or altitude, in degrees.
    pub polar: Degrees,
    /// Azimuthal angle (φ) - longitude, right ascension, or azimuth, in degrees.
    pub azimuth: Degrees,
    /// Radial distance from the origin.
    pub distance: Quantity<U>,

    center_params: C::Params,
    _frame: PhantomData<F>,
}

impl<C, F, U> Position<C, F, U>
where
    C: centers::ReferenceCenter,
    F: frames::ReferenceFrame,
    U: LengthUnit,
{
    /// Constructs a new spherical position with explicit center parameters.
    pub const fn new_raw_with_params(
        center_params: C::Params,
        polar: Degrees,
        azimuth: Degrees,
        distance: Quantity<U>,
    ) -> Self {
        Self {
            polar,
            azimuth,
            distance,
            center_params,
            _frame: PhantomData,
        }
    }

    /// Returns a reference to the center parameters.
    pub fn center_params(&self) -> &C::Params {
        &self.center_params
    }

    /// Calculates the angular separation between this position and another
    /// using the Vincenty formula (numerically stable).
    pub fn angular_separation(&self, other: Self) -> Degrees {
        super::angular_separation_impl(self.polar, self.azimuth, other.polar, other.azimuth)
    }

    /// Extracts the corresponding spherical **direction** (frame-only).
    #[must_use]
    pub fn direction(&self) -> super::direction::Direction<F> {
        super::direction::Direction::new_raw(self.polar, self.azimuth)
    }

    /// Converts to Cartesian position.
    #[must_use]
    pub fn to_cartesian(&self) -> crate::cartesian::Position<C, F, U>
    where
        F: frames::ReferenceFrame,
    {
        let polar_rad = self.polar.to::<Radian>();
        let azimuth_rad = self.azimuth.to::<Radian>();

        let x = self.distance * azimuth_rad.cos() * polar_rad.cos();
        let y = self.distance * azimuth_rad.sin() * polar_rad.cos();
        let z = self.distance * polar_rad.sin();

        crate::cartesian::Position::<C, F, U>::new_with_params(self.center_params.clone(), x, y, z)
    }

    /// Constructs from a Cartesian position.
    #[must_use]
    pub fn from_cartesian(cart: &crate::cartesian::Position<C, F, U>) -> Self
    where
        F: frames::ReferenceFrame,
    {
        let x = cart.x().value();
        let y = cart.y().value();
        let z = cart.z().value();
        let r = cart.distance().value();

        let (polar, azimuth) = if r.abs() < f64::EPSILON {
            (Degrees::new(0.0), Degrees::new(0.0))
        } else {
            super::xyz_to_polar_azimuth(x / r, y / r, z / r)
        };

        Self::new_raw_with_params(
            cart.center_params().clone(),
            polar,
            azimuth,
            cart.distance(),
        )
    }
}

impl<C, F, U> Position<C, F, U>
where
    C: centers::ReferenceCenter<Params = ()>,
    F: frames::ReferenceFrame,
    U: LengthUnit,
{
    /// Convenience constructor for centers with `Params = ()`.
    pub const fn new_raw(polar: Degrees, azimuth: Degrees, distance: Quantity<U>) -> Self {
        Self::new_raw_with_params((), polar, azimuth, distance)
    }

    /// The *origin* of this coordinate system (all angles 0, radius 0). AKA Null Vector.
    pub const CENTER: Self = Self::new_raw(
        Degrees::new(0.0),
        Degrees::new(0.0),
        Quantity::<U>::new(0.0),
    );
}

impl<C, F, U> Position<C, F, U>
where
    C: centers::ReferenceCenter,
    F: frames::ReferenceFrame,
    U: LengthUnit,
{
    /// Euclidean distance to another position **in the same centre & frame**.
    ///
    /// The result is expressed in the *same unit `U`* as the inputs.
    #[must_use]
    pub fn distance_to(&self, other: &Self) -> Quantity<U>
    where
        U: std::cmp::PartialEq + std::fmt::Debug,
        F: frames::ReferenceFrame,
    {
        self.to_cartesian().distance_to(&other.to_cartesian())
    }
}

impl<C, F, U> std::fmt::Display for Position<C, F, U>
where
    C: centers::ReferenceCenter,
    F: frames::ReferenceFrame,
    U: LengthUnit,
    Quantity<U>: std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (polar_name, azimuth_name, distance_name) =
            F::spherical_names().unwrap_or(("\u{03b8}", "\u{03c6}", "r"));
        write!(
            f,
            "Center: {}, Frame: {}, {}: ",
            C::center_name(),
            F::frame_name(),
            polar_name
        )?;
        std::fmt::Display::fmt(&self.polar, f)?;
        write!(f, ", {}: ", azimuth_name)?;
        std::fmt::Display::fmt(&self.azimuth, f)?;
        write!(f, ", {}: ", distance_name)?;
        std::fmt::Display::fmt(&self.distance, f)
    }
}

impl<C, F, U> std::fmt::LowerExp for Position<C, F, U>
where
    C: centers::ReferenceCenter,
    F: frames::ReferenceFrame,
    U: LengthUnit,
    Quantity<U>: std::fmt::LowerExp,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (polar_name, azimuth_name, distance_name) =
            F::spherical_names().unwrap_or(("\u{03b8}", "\u{03c6}", "r"));
        write!(
            f,
            "Center: {}, Frame: {}, {}: ",
            C::center_name(),
            F::frame_name(),
            polar_name
        )?;
        std::fmt::LowerExp::fmt(&self.polar, f)?;
        write!(f, ", {}: ", azimuth_name)?;
        std::fmt::LowerExp::fmt(&self.azimuth, f)?;
        write!(f, ", {}: ", distance_name)?;
        std::fmt::LowerExp::fmt(&self.distance, f)
    }
}

impl<C, F, U> std::fmt::UpperExp for Position<C, F, U>
where
    C: centers::ReferenceCenter,
    F: frames::ReferenceFrame,
    U: LengthUnit,
    Quantity<U>: std::fmt::UpperExp,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (polar_name, azimuth_name, distance_name) =
            F::spherical_names().unwrap_or(("\u{03b8}", "\u{03c6}", "r"));
        write!(
            f,
            "Center: {}, Frame: {}, {}: ",
            C::center_name(),
            F::frame_name(),
            polar_name
        )?;
        std::fmt::UpperExp::fmt(&self.polar, f)?;
        write!(f, ", {}: ", azimuth_name)?;
        std::fmt::UpperExp::fmt(&self.azimuth, f)?;
        write!(f, ", {}: ", distance_name)?;
        std::fmt::UpperExp::fmt(&self.distance, f)
    }
}

// =============================================================================
// Serde Implementation with Frame-Specific Field Names
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    // Import the derives and traits
    use crate::{DeriveReferenceCenter as ReferenceCenter, DeriveReferenceFrame as ReferenceFrame};
    use std::f64::consts::SQRT_2;

    // Define test-specific frame and center
    #[derive(Debug, Copy, Clone, ReferenceFrame)]
    struct TestFrame;
    #[derive(Debug, Copy, Clone, ReferenceCenter)]
    struct TestCenter;

    #[derive(Clone, Debug, Default, PartialEq)]
    struct TestParams {
        id: i32,
    }

    #[derive(Debug, Copy, Clone, ReferenceCenter)]
    #[center(params = TestParams)]
    struct ParamCenter;

    const EPS: f64 = 1e-6;

    #[test]
    fn test_spherical_coord_creation() {
        // new_raw(polar, azimuth, distance)
        let coord = Position::<TestCenter, TestFrame, Meter>::new_raw(
            Degrees::new(90.0),
            Degrees::new(45.0),
            1.0 * M,
        );
        assert_eq!(coord.polar.value(), 90.0);
        assert_eq!(coord.azimuth.value(), 45.0);
        assert_eq!(coord.distance.value(), 1.0);
    }

    #[test]
    fn test_spherical_coord_to_string() {
        // new_raw(polar, azimuth, distance)
        let coord = Position::<TestCenter, TestFrame, Meter>::new_raw(
            Degrees::new(60.0),
            Degrees::new(30.0),
            1000.0 * M,
        );
        let coord_string = coord.to_string();
        assert!(coord_string.contains("θ: 60"));
        assert!(coord_string.contains("φ: 30"));
        assert!(coord_string.contains("r: 1000"));
    }

    #[test]
    fn test_spherical_coord_format_specifiers() {
        let coord =
            Position::<TestCenter, TestFrame, Meter>::new_raw(60.0 * DEG, 30.0 * DEG, 1000.0 * M);

        let text_prec = format!("{:.2}", coord);
        let expected_r_prec = format!("{:.2}", coord.distance);
        assert!(text_prec.contains(&format!("r: {expected_r_prec}")));

        let text_exp = format!("{:.3e}", coord);
        let expected_theta_exp = format!("{:.3e}", coord.polar);
        assert!(text_exp.contains(&format!("θ: {expected_theta_exp}")));
    }

    #[test]
    fn test_spherical_coord_zero_values() {
        let coord =
            Position::<TestCenter, TestFrame, Meter>::new_raw(0.0 * DEG, 0.0 * DEG, 0.0 * M);
        assert_eq!(coord.polar.value(), 0.0);
        assert_eq!(coord.azimuth.value(), 0.0);
        assert_eq!(coord.distance.value(), 0.0);
    }

    #[test]
    fn test_spherical_coord_precision() {
        // new_raw(polar, azimuth, distance)
        let coord = Position::<TestCenter, TestFrame, Meter>::new_raw(
            45.123456 * DEG,
            90.654321 * DEG,
            1234.56789 * M,
        );
        assert!((coord.polar.value() - 45.123456).abs() < 1e-6);
        assert!((coord.azimuth.value() - 90.654321).abs() < 1e-6);
        assert!((coord.distance - 1234.56789 * M).abs() < 1e-6 * M);
    }

    #[test]
    fn direction_returns_unit_vector() {
        let pos =
            Position::<TestCenter, TestFrame, Meter>::new_raw(10.0 * DEG, 20.0 * DEG, 2.5 * M);
        let dir = pos.direction();

        // Direction has implicit radius 1
        // We verify by converting to cartesian and checking the magnitude
        let cart = dir.to_cartesian();
        let magnitude = (cart.x().powi(2) + cart.y().powi(2) + cart.z().powi(2)).sqrt();
        assert!(
            (magnitude - 1.0).abs() < EPS,
            "magnitude should be 1.0, got {}",
            magnitude
        );

        // angular components are preserved
        assert!((dir.polar - 10.0 * DEG).abs() < EPS * DEG);
        assert!((dir.azimuth - 20.0 * DEG).abs() < EPS * DEG);
    }

    #[test]
    fn center_constant_is_origin() {
        let c = Position::<TestCenter, TestFrame, Meter>::CENTER;
        assert_eq!(c.polar.value(), 0.0);
        assert_eq!(c.azimuth.value(), 0.0);
        assert_eq!(c.distance.value(), 0.0);
    }

    #[test]
    fn from_degrees_matches_new_raw() {
        let a = Position::<TestCenter, TestFrame, Meter>::new_raw(45.0 * DEG, 30.0 * DEG, 3.0 * M);
        let b = Position::<TestCenter, TestFrame, Meter>::new_raw(45.0 * DEG, 30.0 * DEG, 3.0 * M);
        assert_eq!(a.polar, b.polar);
        assert_eq!(a.azimuth, b.azimuth);
        assert_eq!(a.distance, b.distance);
    }

    #[test]
    fn distance_identity_zero_and_orthogonal() {
        // identity
        let a = Position::<TestCenter, TestFrame, Meter>::new_raw(0.0 * DEG, 0.0 * DEG, 1.0 * M);
        let d0 = a.distance_to(&a);
        assert!(d0.abs().value() < EPS);

        // orthogonal points on unit sphere → chord length sqrt(2) * r
        let b = Position::<TestCenter, TestFrame, Meter>::new_raw(0.0 * DEG, 90.0 * DEG, 1.0 * M);
        let d = a.distance_to(&b);
        assert!((d.value() - SQRT_2).abs() < EPS);
    }

    #[test]
    fn position_with_params_and_center_params() {
        let params = TestParams { id: 9 };
        let pos = Position::<ParamCenter, TestFrame, Meter>::new_raw_with_params(
            params.clone(),
            5.0 * DEG,
            10.0 * DEG,
            2.0 * M,
        );
        assert_eq!(pos.center_params(), &params);
        assert!((pos.distance.value() - 2.0).abs() < EPS);
    }

    #[test]
    fn angular_separation_quarter_turn() {
        let a = Position::<TestCenter, TestFrame, Meter>::new_raw(0.0 * DEG, 0.0 * DEG, 1.0 * M);
        let b = Position::<TestCenter, TestFrame, Meter>::new_raw(0.0 * DEG, 90.0 * DEG, 1.0 * M);
        let sep = a.angular_separation(b);
        assert!((sep.value() - 90.0).abs() < EPS);
    }

    #[test]
    fn cartesian_roundtrip_and_zero_radius() {
        type CartPos = crate::cartesian::Position<TestCenter, TestFrame, Meter>;

        let cart = CartPos::new(1.0, -1.0, 0.0);
        let sph = Position::from_cartesian(&cart);
        assert!((sph.polar.value()).abs() < EPS);
        assert!((sph.azimuth.value() - 315.0).abs() < EPS);

        let back = sph.to_cartesian();
        assert!((back.x().value() - cart.x().value()).abs() < EPS);
        assert!((back.y().value() - cart.y().value()).abs() < EPS);

        let origin = CartPos::new(0.0, 0.0, 0.0);
        let sph_origin = Position::from_cartesian(&origin);
        assert!((sph_origin.polar.value()).abs() < EPS);
        assert!((sph_origin.azimuth.value()).abs() < EPS);
        assert!(sph_origin.distance.value().abs() < EPS);
    }
}