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
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! # Cartesian Position (Affine Points)
//!
//! This module defines [`Position<C, F, U>`], an **affine point** in 3D space.
//!
//! ## Mathematical Model
//!
//! A position is a point in affine space, not a vector. It represents a location
//! relative to an origin (the reference center). Key properties:
//!
//! - **Center-dependent**: Position is measured from a specific origin `C`
//! - **Frame-dependent**: The orientation is relative to a reference frame `F`
//! - **Dimensioned**: Has a length unit `U`
//!
//! ## Affine Space Operations
//!
//! Positions do **not** form a vector space. The only valid operations are:
//!
//! | Operation | Result | Meaning |
//! |-----------|--------|---------|
//! | `Position - Position` | `Displacement` | Displacement between points |
//! | `Position + Displacement` | `Position` | Translate point by displacement |
//! | `Position - Displacement` | `Position` | Translate point backwards |
//!
//! ## Forbidden Operations
//!
//! The following operations are **mathematically invalid** and do not compile:
//!
//! - `Position + Position` — Adding points has no geometric meaning
//! - `Position * scalar` — Scaling a point makes no sense without an origin
//!
//! ## Example
//!
//! ```rust
//! use affn::cartesian::{Position, Displacement};
//! use affn::centers::ReferenceCenter;
//! use affn::frames::ReferenceFrame;
//! use qtty::*;
//!
//! // Define custom center and frame (astronomy types are in downstream crates)
//! #[derive(Debug, Copy, Clone)]
//! struct MyCenter;
//! impl ReferenceCenter for MyCenter {
//!     type Params = ();
//!     fn center_name() -> &'static str { "MyCenter" }
//! }
//!
//! #[derive(Debug, Copy, Clone)]
//! struct MyFrame;
//! impl ReferenceFrame for MyFrame {
//!     fn frame_name() -> &'static str { "MyFrame" }
//! }
//!
//! // Two positions in the custom coordinate system
//! let pos1 = Position::<MyCenter, MyFrame, AstronomicalUnit>::new(1.0, 0.0, 0.0);
//! let pos2 = Position::<MyCenter, MyFrame, AstronomicalUnit>::new(1.5, 0.0, 0.0);
//!
//! // Displacement between positions
//! let displacement: Displacement<MyFrame, AstronomicalUnit> = pos2 - pos1;
//! assert!((displacement.x().value() - 0.5).abs() < 1e-12);
//!
//! // Translate pos1 by the displacement to get pos2
//! let result = pos1 + displacement;
//! assert!((result.x().value() - 1.5).abs() < 1e-12);
//! ```

use super::vector::Displacement;
use super::xyz::XYZ;
use crate::centers::ReferenceCenter;
use crate::frames::ReferenceFrame;
use qtty::{LengthUnit, Quantity};

use std::marker::PhantomData;
use std::ops::{Add, Sub};

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

// =============================================================================
// Error Types
// =============================================================================

/// Error returned when an operation requires matching center parameters
/// but the two positions have different ones.
///
/// This occurs with **parameterized centers** (e.g., `Topocentric` with `ObserverSite`)
/// when two positions reference different observer sites.
///
/// For centers with `Params = ()` (e.g., `Geocentric`, `Heliocentric`), this error
/// can never occur because all instances share the same (empty) parameters.
#[derive(Debug, Clone)]
pub struct CenterParamsMismatchError {
    /// The operation that detected the mismatch.
    pub operation: &'static str,
}

impl std::fmt::Display for CenterParamsMismatchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "center parameter mismatch in `{}`: \
             positions reference different parameterized centers \
             (e.g., different observer sites)",
            self.operation
        )
    }
}

impl std::error::Error for CenterParamsMismatchError {}

/// An affine point in 3D Cartesian coordinates.
///
/// Positions represent locations in space relative to a reference center (origin).
/// Unlike vectors, positions do not form a vector space.
///
/// # Type Parameters
/// - `C`: The reference center (e.g., `Heliocentric`, `Geocentric`, `Topocentric`)
/// - `F`: The reference frame (e.g., `ICRS`, `EclipticMeanJ2000`, `Equatorial`)
/// - `U`: The length unit (e.g., `AstronomicalUnit`, `Kilometer`)
///
/// # Center Parameters
///
/// Some centers (like `Topocentric`) require runtime parameters stored in `C::Params`.
/// For most centers, `Params = ()` (zero overhead).
#[derive(Debug, Clone, Copy)]
pub struct Position<C: ReferenceCenter, F: ReferenceFrame, U: LengthUnit> {
    xyz: XYZ<Quantity<U>>,
    center_params: C::Params,
    _frame: PhantomData<F>,
}

// =============================================================================
// Constructors with explicit center parameters
// =============================================================================

impl<C: ReferenceCenter, F: ReferenceFrame, U: LengthUnit> Position<C, F, U> {
    /// Creates a new position with explicit center parameters.
    ///
    /// # Arguments
    /// - `center_params`: Runtime parameters for the center (e.g., `ObserverSite` for Topocentric)
    /// - `x`, `y`, `z`: Component values (converted to `Quantity<U>`)
    #[inline]
    pub fn new_with_params<T: Into<Quantity<U>>>(
        center_params: C::Params,
        x: T,
        y: T,
        z: T,
    ) -> Self {
        Self {
            xyz: XYZ::new(x.into(), y.into(), z.into()),
            center_params,
            _frame: PhantomData,
        }
    }

    /// Creates a position from internal storage with explicit center parameters.
    #[inline]
    pub(crate) fn from_xyz_with_params(center_params: C::Params, xyz: XYZ<Quantity<U>>) -> Self {
        Self {
            xyz,
            center_params,
            _frame: PhantomData,
        }
    }

    /// Creates a position from a nalgebra Vector3 with explicit center parameters.
    #[inline]
    pub fn from_vec3(center_params: C::Params, vec3: nalgebra::Vector3<Quantity<U>>) -> Self {
        Self {
            xyz: XYZ::from_vec3(vec3),
            center_params,
            _frame: PhantomData,
        }
    }

    /// Const constructor for use in const contexts.
    #[inline]
    pub const fn new_const(
        center_params: C::Params,
        x: Quantity<U>,
        y: Quantity<U>,
        z: Quantity<U>,
    ) -> Self {
        Self {
            xyz: XYZ::new(x, y, z),
            center_params,
            _frame: PhantomData,
        }
    }

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

// =============================================================================
// Convenience constructors for centers with Params = ()
// =============================================================================

impl<C, F, U> Position<C, F, U>
where
    C: ReferenceCenter<Params = ()>,
    F: ReferenceFrame,
    U: LengthUnit,
{
    /// Creates a new position for centers with `Params = ()`.
    ///
    /// This is a convenience constructor that doesn't require passing `()` explicitly.
    ///
    /// # Example
    /// ```rust
    /// use affn::cartesian::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(1.0, 0.0, 0.0);
    /// ```
    #[inline]
    pub fn new<T: Into<Quantity<U>>>(x: T, y: T, z: T) -> Self {
        Self::new_with_params((), x, y, z)
    }

    /// Creates a position from a nalgebra Vector3 for centers with `Params = ()`.
    #[inline]
    pub fn from_vec3_origin(vec3: nalgebra::Vector3<Quantity<U>>) -> Self {
        Self::from_vec3((), vec3)
    }

    /// The origin of this coordinate system (all coordinates zero).
    pub const CENTER: Self = Self::new_const(
        (),
        Quantity::<U>::new(0.0),
        Quantity::<U>::new(0.0),
        Quantity::<U>::new(0.0),
    );
}

// =============================================================================
// Component Access
// =============================================================================

impl<C: ReferenceCenter, F: ReferenceFrame, U: LengthUnit> Position<C, F, U> {
    /// Returns the x-component.
    #[inline]
    pub fn x(&self) -> Quantity<U> {
        self.xyz.x()
    }

    /// Returns the y-component.
    #[inline]
    pub fn y(&self) -> Quantity<U> {
        self.xyz.y()
    }

    /// Returns the z-component.
    #[inline]
    pub fn z(&self) -> Quantity<U> {
        self.xyz.z()
    }

    /// Returns the underlying nalgebra Vector3.
    #[inline]
    pub fn as_vec3(&self) -> &nalgebra::Vector3<Quantity<U>> {
        self.xyz.as_vec3()
    }

    /// Converts this position to another length unit.
    ///
    /// The center and frame are preserved while each Cartesian component is
    /// converted independently via `qtty::Quantity::to`.
    #[inline]
    pub fn to_unit<U2: LengthUnit>(&self) -> Position<C, F, U2>
    where
        C::Params: Clone,
    {
        Position::<C, F, U2>::new_with_params(
            self.center_params.clone(),
            self.x().to::<U2>(),
            self.y().to::<U2>(),
            self.z().to::<U2>(),
        )
    }

    /// Reinterprets this position as belonging to a different reference frame.
    ///
    /// This is a **zero-cost** operation: the Cartesian components and center
    /// are preserved unchanged; only the compile-time frame tag `F` is replaced
    /// by `F2`.
    ///
    /// # When to use
    ///
    /// After applying a mathematical rotation (`Rotation3 * position`) whose
    /// result carries the *original* frame tag, call this method to assign the
    /// correct *target* frame tag.
    ///
    /// ```text
    /// // Rotate from EclipticMeanJ2000 into ICRS coordinates:
    /// let rotated = rot * pos_ecl;           // still tagged EclipticMeanJ2000
    /// let pos_icrs = rotated.reinterpret_frame::<ICRS>(); // now tagged ICRS
    /// ```
    #[inline]
    pub fn reinterpret_frame<F2: ReferenceFrame>(self) -> Position<C, F2, U>
    where
        C::Params: Clone,
    {
        Position::new_with_params(self.center_params.clone(), self.x(), self.y(), self.z())
    }
}

// =============================================================================
// Geometric Operations
// =============================================================================

impl<C: ReferenceCenter, F: ReferenceFrame, U: LengthUnit> Position<C, F, U> {
    /// Computes the distance from the reference center.
    #[inline]
    pub fn distance(&self) -> Quantity<U> {
        self.xyz.magnitude()
    }

    /// Computes the distance to another position in the same center and frame.
    ///
    /// # Panics
    ///
    /// Panics if the positions have different center parameters.
    /// For a non-panicking alternative, use [`try_distance_to`](Self::try_distance_to).
    ///
    /// # Note on Parameterized Centers
    ///
    /// For centers with `Params = ()` (e.g., `Geocentric`, `Heliocentric`), this check
    /// is a compile-time guarantee and has zero runtime cost. For parameterized centers
    /// (e.g., `Topocentric` with `ObserverSite`), the check is performed at runtime.
    #[inline]
    pub fn distance_to(&self, other: &Self) -> Quantity<U>
    where
        C::Params: PartialEq,
    {
        assert!(
            self.center_params == other.center_params,
            "Cannot compute distance between positions with different center parameters"
        );
        (self.xyz - other.xyz).magnitude()
    }

    /// Checked version of [`distance_to`](Self::distance_to) that returns `Err`
    /// instead of panicking when center parameters don't match.
    ///
    /// For centers with `Params = ()`, this always succeeds.
    #[inline]
    pub fn try_distance_to(&self, other: &Self) -> Result<Quantity<U>, CenterParamsMismatchError>
    where
        C::Params: PartialEq,
    {
        if self.center_params != other.center_params {
            return Err(CenterParamsMismatchError {
                operation: "distance_to",
            });
        }
        Ok((self.xyz - other.xyz).magnitude())
    }

    /// Returns the direction (unit vector) from the center to this position.
    ///
    /// Note: Directions are frame-only types (no center). This extracts the
    /// normalized direction of the position vector.
    ///
    /// Returns `None` if the position is at the origin.
    #[inline]
    pub fn direction(&self) -> Option<super::Direction<F>> {
        self.xyz
            .to_raw()
            .try_normalize()
            .map(super::Direction::from_xyz_unchecked)
    }

    /// Returns the direction, assuming non-zero distance from origin.
    ///
    /// # Panics
    /// May produce NaN if the position is at the origin.
    #[inline]
    pub fn direction_unchecked(&self) -> super::Direction<F> {
        super::Direction::from_xyz_unchecked(self.xyz.to_raw().normalize_unchecked())
    }

    /// Converts this Cartesian position to spherical coordinates.
    ///
    /// Returns a spherical position with the same center and frame,
    /// with (polar, azimuth, distance) computed from (x, y, z).
    #[must_use]
    #[inline]
    pub fn to_spherical(&self) -> crate::spherical::Position<C, F, U> {
        crate::spherical::Position::from_cartesian(self)
    }

    /// Constructs a Cartesian position from spherical coordinates.
    ///
    /// This is equivalent to `spherical_pos.to_cartesian()`.
    #[must_use]
    #[inline]
    pub fn from_spherical(sph: &crate::spherical::Position<C, F, U>) -> Self {
        sph.to_cartesian()
    }
}

// =============================================================================
// Affine Space Operations: Position - Position -> Vector
// =============================================================================

impl<C, F, U> Sub for Position<C, F, U>
where
    C: ReferenceCenter,
    F: ReferenceFrame,
    U: LengthUnit,
{
    type Output = Displacement<F, U>;

    /// Computes the displacement vector from `other` to `self`.
    ///
    /// # Panics
    ///
    /// Panics if the positions have different center parameters.
    /// For a non-panicking alternative, use [`Position::checked_sub`].
    #[inline]
    fn sub(self, other: Self) -> Self::Output {
        assert!(
            self.center_params == other.center_params,
            "Cannot subtract positions with different center parameters"
        );
        Displacement::from_xyz(self.xyz - other.xyz)
    }
}

impl<C, F, U> Sub<&Position<C, F, U>> for &Position<C, F, U>
where
    C: ReferenceCenter,
    F: ReferenceFrame,
    U: LengthUnit,
{
    type Output = Displacement<F, U>;

    /// Computes the displacement vector from `other` to `self`.
    ///
    /// # Panics
    ///
    /// Panics if the positions have different center parameters.
    #[inline]
    fn sub(self, other: &Position<C, F, U>) -> Self::Output {
        assert!(
            self.center_params == other.center_params,
            "Cannot subtract positions with different center parameters"
        );
        Displacement::from_xyz(self.xyz - other.xyz)
    }
}

impl<C: ReferenceCenter, F: ReferenceFrame, U: LengthUnit> Position<C, F, U> {
    /// Checked subtraction that returns `Err` instead of panicking when
    /// center parameters don't match.
    ///
    /// This is the safe alternative to the `Sub` operator (`pos_a - pos_b`).
    /// For centers with `Params = ()`, this always succeeds.
    #[inline]
    pub fn checked_sub(&self, other: &Self) -> Result<Displacement<F, U>, CenterParamsMismatchError>
    where
        C::Params: PartialEq,
    {
        if self.center_params != other.center_params {
            return Err(CenterParamsMismatchError {
                operation: "sub (Position - Position)",
            });
        }
        Ok(Displacement::from_xyz(self.xyz - other.xyz))
    }
}

// =============================================================================
// Affine Space Operations: Position + Vector -> Position
// =============================================================================

impl<C, F, U> Add<Displacement<F, U>> for Position<C, F, U>
where
    C: ReferenceCenter,
    F: ReferenceFrame,
    U: LengthUnit,
{
    type Output = Self;

    /// Translates the position by a displacement vector.
    #[inline]
    fn add(self, displacement: Displacement<F, U>) -> Self::Output {
        Self::from_xyz_with_params(
            self.center_params.clone(),
            self.xyz + XYZ::from_vec3(*displacement.as_vec3()),
        )
    }
}

impl<C, F, U> Sub<Displacement<F, U>> for Position<C, F, U>
where
    C: ReferenceCenter,
    F: ReferenceFrame,
    U: LengthUnit,
{
    type Output = Self;

    /// Translates the position backwards by a displacement vector.
    #[inline]
    fn sub(self, displacement: Displacement<F, U>) -> Self::Output {
        Self::from_xyz_with_params(
            self.center_params.clone(),
            self.xyz - XYZ::from_vec3(*displacement.as_vec3()),
        )
    }
}

// =============================================================================
// Display
// =============================================================================

impl<C, F, U> std::fmt::Display for Position<C, F, U>
where
    C: ReferenceCenter,
    F: ReferenceFrame,
    U: LengthUnit,
    Quantity<U>: std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Center: {}, Frame: {}, X: ",
            C::center_name(),
            F::frame_name()
        )?;
        std::fmt::Display::fmt(&self.x(), f)?;
        write!(f, ", Y: ")?;
        std::fmt::Display::fmt(&self.y(), f)?;
        write!(f, ", Z: ")?;
        std::fmt::Display::fmt(&self.z(), f)
    }
}

impl<C, F, U> std::fmt::LowerExp for Position<C, F, U>
where
    C: ReferenceCenter,
    F: ReferenceFrame,
    U: LengthUnit,
    Quantity<U>: std::fmt::LowerExp,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Center: {}, Frame: {}, X: ",
            C::center_name(),
            F::frame_name()
        )?;
        std::fmt::LowerExp::fmt(&self.x(), f)?;
        write!(f, ", Y: ")?;
        std::fmt::LowerExp::fmt(&self.y(), f)?;
        write!(f, ", Z: ")?;
        std::fmt::LowerExp::fmt(&self.z(), f)
    }
}

impl<C, F, U> std::fmt::UpperExp for Position<C, F, U>
where
    C: ReferenceCenter,
    F: ReferenceFrame,
    U: LengthUnit,
    Quantity<U>: std::fmt::UpperExp,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Center: {}, Frame: {}, X: ",
            C::center_name(),
            F::frame_name()
        )?;
        std::fmt::UpperExp::fmt(&self.x(), f)?;
        write!(f, ", Y: ")?;
        std::fmt::UpperExp::fmt(&self.y(), f)?;
        write!(f, ", Z: ")?;
        std::fmt::UpperExp::fmt(&self.z(), f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    // Import the derives
    use crate::{DeriveReferenceCenter as ReferenceCenter, DeriveReferenceFrame as ReferenceFrame};
    use qtty::*;

    // 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;

    type TestPos = Position<TestCenter, TestFrame, Meter>;
    type TestDisp = Displacement<TestFrame, Meter>;

    #[test]
    fn test_position_minus_position_gives_vector() {
        let a = TestPos::new(1.0, 2.0, 3.0);
        let b = TestPos::new(4.0, 5.0, 6.0);

        let displacement: TestDisp = b - a;
        assert!((displacement.x().value() - 3.0).abs() < 1e-12);
        assert!((displacement.y().value() - 3.0).abs() < 1e-12);
        assert!((displacement.z().value() - 3.0).abs() < 1e-12);
    }

    #[test]
    fn test_position_plus_vector_gives_position() {
        let pos = TestPos::new(1.0, 2.0, 3.0);
        let vec = TestDisp::new(1.0, 1.0, 1.0);

        let result: TestPos = pos + vec;
        assert!((result.x().value() - 2.0).abs() < 1e-12);
        assert!((result.y().value() - 3.0).abs() < 1e-12);
        assert!((result.z().value() - 4.0).abs() < 1e-12);
    }

    #[test]
    fn test_position_roundtrip() {
        let a = TestPos::new(1.0, 2.0, 3.0);
        let b = TestPos::new(4.0, 5.0, 6.0);

        // a + (b - a) == b
        let displacement = b - a;
        let result = a + displacement;
        assert!((result.x().value() - b.x().value()).abs() < 1e-12);
        assert!((result.y().value() - b.y().value()).abs() < 1e-12);
        assert!((result.z().value() - b.z().value()).abs() < 1e-12);
    }

    #[test]
    fn test_position_distance() {
        let pos = TestPos::new(3.0, 4.0, 0.0);
        assert!((pos.distance().value() - 5.0).abs() < 1e-12);
    }

    #[test]
    fn test_position_direction() {
        let pos = TestPos::new(3.0, 4.0, 0.0);
        let dir = pos.direction().expect("non-zero position");
        let norm = (dir.x() * dir.x() + dir.y() * dir.y() + dir.z() * dir.z()).sqrt();
        assert!((norm - 1.0).abs() < 1e-12);
        assert!((dir.x() - 0.6).abs() < 1e-12);
        assert!((dir.y() - 0.8).abs() < 1e-12);
    }

    #[test]
    fn test_position_with_params_and_from_vec3() {
        let params = TestParams { id: 42 };
        let pos = Position::<ParamCenter, TestFrame, Meter>::new_with_params(
            params.clone(),
            1.0,
            2.0,
            3.0,
        );
        assert_eq!(pos.center_params(), &params);

        let vec3 = nalgebra::Vector3::new(1.0 * M, 2.0 * M, 3.0 * M);
        let pos_from_vec =
            Position::<ParamCenter, TestFrame, Meter>::from_vec3(params.clone(), vec3);
        assert_eq!(pos_from_vec.center_params(), &params);
        assert!((pos_from_vec.z().value() - 3.0).abs() < 1e-12);
    }

    #[test]
    fn test_position_from_vec3_origin_and_center() {
        let vec3 = nalgebra::Vector3::new(1.0 * M, 2.0 * M, 3.0 * M);
        let pos = Position::<TestCenter, TestFrame, Meter>::from_vec3_origin(vec3);
        assert!((pos.x().value() - 1.0).abs() < 1e-12);

        let origin = Position::<TestCenter, TestFrame, Meter>::CENTER;
        assert!(origin.distance().value().abs() < 1e-12);
    }

    #[test]
    fn test_position_distance_to_and_sub_methods() {
        let a = TestPos::new(0.0, 0.0, 0.0);
        let b = TestPos::new(0.0, 3.0, 4.0);
        let dist = a.distance_to(&b);
        assert!((dist.value() - 5.0).abs() < 1e-12);

        let disp: TestDisp = b - a;
        assert!((disp.y().value() - 3.0).abs() < 1e-12);
    }

    #[test]
    fn test_position_direction_unchecked_and_sub_displacement() {
        let pos = TestPos::new(0.0, 3.0, 4.0);
        let dir = pos.direction_unchecked();
        assert!((dir.y() - 0.6).abs() < 1e-12);
        assert!((dir.z() - 0.8).abs() < 1e-12);

        let disp = TestDisp::new(1.0, 1.0, 1.0);
        let moved = pos - disp;
        assert!((moved.y().value() - 2.0).abs() < 1e-12);
    }

    #[test]
    fn test_position_spherical_roundtrip() {
        let pos = TestPos::new(1.0, 1.0, 1.0);
        let sph = pos.to_spherical();
        let back = TestPos::from_spherical(&sph);
        assert!((back.x().value() - pos.x().value()).abs() < 1e-12);
        assert!((back.y().value() - pos.y().value()).abs() < 1e-12);
        assert!((back.z().value() - pos.z().value()).abs() < 1e-12);
    }

    #[test]
    fn test_position_const_vec3_and_display() {
        let pos =
            Position::<TestCenter, TestFrame, Meter>::new_const((), 1.0 * M, 2.0 * M, 3.0 * M);
        let vec3 = pos.as_vec3();
        assert!((vec3[0].value() - 1.0).abs() < 1e-12);
        assert!((vec3[1].value() - 2.0).abs() < 1e-12);
        assert!((vec3[2].value() - 3.0).abs() < 1e-12);

        let text = pos.to_string();
        assert!(text.contains("Center: TestCenter"));
        assert!(text.contains("Frame: TestFrame"));
    }

    #[test]
    fn test_position_display_respects_format_specifiers() {
        let pos = TestPos::new(1.234_567, -2.0, 3.5);

        let text_prec = format!("{:.2}", pos);
        let expected_x_prec = format!("{:.2}", pos.x());
        assert!(text_prec.contains(&format!("X: {expected_x_prec}")));

        let text_exp = format!("{:.3e}", pos);
        let expected_z_exp = format!("{:.3e}", pos.z());
        assert!(text_exp.contains(&format!("Z: {expected_z_exp}")));
    }

    #[test]
    fn test_position_sub_ref_ref() {
        let a = TestPos::new(1.0, 2.0, 3.0);
        let b = TestPos::new(4.0, 6.0, 9.0);
        let displacement: TestDisp = b - a;
        assert!((displacement.x().value() - 3.0).abs() < 1e-12);
        assert!((displacement.y().value() - 4.0).abs() < 1e-12);
        assert!((displacement.z().value() - 6.0).abs() < 1e-12);
    }

    // =========================================================================
    // Parameterized-center runtime invariant tests
    // =========================================================================

    type ParamPos = Position<ParamCenter, TestFrame, Meter>;

    #[test]
    fn test_distance_to_same_params_succeeds() {
        let params = TestParams { id: 1 };
        let a = ParamPos::new_with_params(params.clone(), 0.0, 0.0, 0.0);
        let b = ParamPos::new_with_params(params, 3.0, 4.0, 0.0);
        assert!((a.distance_to(&b).value() - 5.0).abs() < 1e-12);
    }

    #[test]
    #[should_panic(expected = "different center parameters")]
    fn test_distance_to_mismatched_params_panics() {
        let a = ParamPos::new_with_params(TestParams { id: 1 }, 0.0, 0.0, 0.0);
        let b = ParamPos::new_with_params(TestParams { id: 2 }, 3.0, 4.0, 0.0);
        let _ = a.distance_to(&b);
    }

    #[test]
    fn test_try_distance_to_same_params_ok() {
        let params = TestParams { id: 1 };
        let a = ParamPos::new_with_params(params.clone(), 0.0, 0.0, 0.0);
        let b = ParamPos::new_with_params(params, 3.0, 4.0, 0.0);
        let result = a.try_distance_to(&b);
        assert!(result.is_ok());
        assert!((result.unwrap().value() - 5.0).abs() < 1e-12);
    }

    #[test]
    fn test_try_distance_to_mismatched_params_err() {
        let a = ParamPos::new_with_params(TestParams { id: 1 }, 0.0, 0.0, 0.0);
        let b = ParamPos::new_with_params(TestParams { id: 2 }, 3.0, 4.0, 0.0);
        let result = a.try_distance_to(&b);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("center parameter mismatch"));
    }

    #[test]
    #[should_panic(expected = "different center parameters")]
    fn test_sub_mismatched_params_panics() {
        let a = ParamPos::new_with_params(TestParams { id: 1 }, 1.0, 2.0, 3.0);
        let b = ParamPos::new_with_params(TestParams { id: 2 }, 4.0, 5.0, 6.0);
        let _ = a - b;
    }

    #[test]
    fn test_checked_sub_same_params_ok() {
        let params = TestParams { id: 1 };
        let a = ParamPos::new_with_params(params.clone(), 0.0, 0.0, 0.0);
        let b = ParamPos::new_with_params(params, 3.0, 4.0, 0.0);
        let result = b.checked_sub(&a);
        assert!(result.is_ok());
        let disp = result.unwrap();
        assert!((disp.x().value() - 3.0).abs() < 1e-12);
        assert!((disp.y().value() - 4.0).abs() < 1e-12);
    }

    #[test]
    fn test_checked_sub_mismatched_params_err() {
        let a = ParamPos::new_with_params(TestParams { id: 1 }, 0.0, 0.0, 0.0);
        let b = ParamPos::new_with_params(TestParams { id: 2 }, 3.0, 4.0, 0.0);
        let result = b.checked_sub(&a);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("center parameter mismatch"));
    }

    #[test]
    fn test_unit_params_operations_always_succeed() {
        // For Params = (), operations are trivially valid (compile-time guarantee)
        let a = TestPos::new(0.0, 0.0, 0.0);
        let b = TestPos::new(3.0, 4.0, 0.0);
        assert!((a.distance_to(&b).value() - 5.0).abs() < 1e-12);
        assert!(a.try_distance_to(&b).is_ok());
        assert!(b.checked_sub(&a).is_ok());
    }

    #[test]
    fn test_center_params_mismatch_error_display() {
        let err = CenterParamsMismatchError {
            operation: "test_op",
        };
        let msg = err.to_string();
        assert!(msg.contains("test_op"));
        assert!(msg.contains("center parameter mismatch"));

        // Verify it implements std::error::Error
        let _: &dyn std::error::Error = &err;
    }

    #[test]
    fn test_position_to_unit_roundtrip() {
        let p_au = Position::<TestCenter, TestFrame, AstronomicalUnit>::new(1.0, -0.5, 2.25);
        let p_km: Position<TestCenter, TestFrame, Kilometer> = p_au.to_unit();
        let back: Position<TestCenter, TestFrame, AstronomicalUnit> = p_km.to_unit();

        assert!((back.x().value() - p_au.x().value()).abs() < 1e-12);
        assert!((back.y().value() - p_au.y().value()).abs() < 1e-12);
        assert!((back.z().value() - p_au.z().value()).abs() < 1e-12);
    }

    #[test]
    fn test_position_to_unit_preserves_center_params() {
        let p_m = ParamPos::new_with_params(TestParams { id: 7 }, 1.0, 2.0, 3.0);
        let p_km: Position<ParamCenter, TestFrame, Kilometer> = p_m.to_unit();

        assert_eq!(p_km.center_params().id, 7);
        assert!((p_km.x().value() - 0.001).abs() < 1e-12);
        assert!((p_km.y().value() - 0.002).abs() < 1e-12);
        assert!((p_km.z().value() - 0.003).abs() < 1e-12);
    }
}