celestial-coords 0.1.1-alpha.2

Astronomical coordinate transformations
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
use crate::{transforms::CoordinateFrame, CoordError, CoordResult, Distance};
use celestial_core::{Angle, Vector3};
use celestial_time::TT;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ICRSPosition {
    ra: Angle,
    dec: Angle,
    distance: Option<Distance>,
}

impl ICRSPosition {
    pub fn new(ra: Angle, dec: Angle) -> CoordResult<Self> {
        let ra = ra.validate_right_ascension()?;
        let dec = dec.validate_declination(false)?;

        Ok(Self {
            ra,
            dec,
            distance: None,
        })
    }

    pub fn with_distance(ra: Angle, dec: Angle, distance: Distance) -> CoordResult<Self> {
        let mut pos = Self::new(ra, dec)?;
        pos.distance = Some(distance);
        Ok(pos)
    }

    pub fn from_degrees(ra_deg: f64, dec_deg: f64) -> CoordResult<Self> {
        Self::new(Angle::from_degrees(ra_deg), Angle::from_degrees(dec_deg))
    }

    pub fn from_degrees_with_distance(
        ra_deg: f64,
        dec_deg: f64,
        distance: Distance,
    ) -> CoordResult<Self> {
        Self::with_distance(
            Angle::from_degrees(ra_deg),
            Angle::from_degrees(dec_deg),
            distance,
        )
    }

    pub fn from_hours_degrees(ra_hours: f64, dec_deg: f64) -> CoordResult<Self> {
        Self::new(Angle::from_hours(ra_hours), Angle::from_degrees(dec_deg))
    }

    pub fn ra(&self) -> Angle {
        self.ra
    }

    pub fn dec(&self) -> Angle {
        self.dec
    }

    pub fn distance(&self) -> Option<Distance> {
        self.distance
    }

    pub fn set_distance(&mut self, distance: Distance) {
        self.distance = Some(distance);
    }

    pub fn remove_distance(&mut self) {
        self.distance = None;
    }

    pub fn unit_vector(&self) -> Vector3 {
        let (sin_dec, cos_dec) = self.dec.sin_cos();
        let (sin_ra, cos_ra) = self.ra.sin_cos();

        Vector3::new(cos_dec * cos_ra, cos_dec * sin_ra, sin_dec)
    }

    pub fn position_vector(&self) -> CoordResult<Vector3> {
        let distance = self.distance.ok_or_else(|| {
            CoordError::invalid_coordinate("Distance required for position vector")
        })?;

        let unit = self.unit_vector();
        let distance_au = distance.au();

        Ok(Vector3::new(
            unit.x * distance_au,
            unit.y * distance_au,
            unit.z * distance_au,
        ))
    }

    pub fn from_unit_vector(unit: Vector3) -> CoordResult<Self> {
        let r = libm::sqrt(unit.x.powi(2) + unit.y.powi(2) + unit.z.powi(2));

        if r == 0.0 {
            return Err(CoordError::invalid_coordinate("Zero vector"));
        }

        let x = unit.x / r;
        let y = unit.y / r;
        let z = unit.z / r;

        let d2 = x * x + y * y;
        let ra = if d2 == 0.0 { 0.0 } else { libm::atan2(y, x) };
        let dec = if z == 0.0 {
            0.0
        } else {
            libm::atan2(z, libm::sqrt(d2))
        };

        Self::new(Angle::from_radians(ra), Angle::from_radians(dec))
    }

    pub fn from_position_vector(pos: Vector3) -> CoordResult<Self> {
        let distance_au = libm::sqrt(pos.x.powi(2) + pos.y.powi(2) + pos.z.powi(2));

        if distance_au == 0.0 {
            return Err(CoordError::invalid_coordinate("Zero position vector"));
        }

        let unit = Vector3::new(
            pos.x / distance_au,
            pos.y / distance_au,
            pos.z / distance_au,
        );

        let mut icrs = Self::from_unit_vector(unit)?;
        icrs.distance = Some(Distance::from_au(distance_au)?);

        Ok(icrs)
    }

    pub fn angular_separation(&self, other: &Self) -> Angle {
        let (sin_dec1, cos_dec1) = self.dec.sin_cos();
        let (sin_dec2, cos_dec2) = other.dec.sin_cos();
        let delta_ra = (self.ra - other.ra).radians();

        let angle_rad = celestial_core::math::vincenty_angular_separation(
            sin_dec1, cos_dec1, sin_dec2, cos_dec2, delta_ra,
        );

        Angle::from_radians(angle_rad)
    }

    pub fn is_near_pole(&self) -> bool {
        self.dec.abs().degrees() > 89.0
    }

    /// Calculate angular position uncertainty from parallax measurement error.
    ///
    /// This method simply converts parallax error to angular uncertainty (they have the same
    /// magnitude). The stored distance value is not used in the calculation - distance is only
    /// checked for presence to ensure this is a parallax-derived position.
    ///
    /// **Important**: This returns the *angular* uncertainty on the sky, not the linear distance
    /// uncertainty. For distance uncertainty in physical units (parsecs, AU, etc.), calculate
    /// separately using error propagation: Δd = d² × Δπ (where π is parallax).
    ///
    /// # Arguments
    /// * `parallax_error_mas` - Parallax measurement error in milliarcseconds
    ///
    /// # Returns
    /// Angular position uncertainty in arcseconds, or None if no distance is set
    ///
    /// # Example
    /// ```ignore
    /// // Gaia DR3 typical parallax error: 0.02 mas → 0.00002 arcsec angular uncertainty
    /// let uncertainty = pos.position_uncertainty_arcsec(0.02);
    /// ```
    pub fn position_uncertainty_arcsec(&self, parallax_error_mas: f64) -> Option<f64> {
        self.distance.map(|_d| {
            // Angular position uncertainty equals parallax uncertainty numerically
            parallax_error_mas / 1000.0
        })
    }

    /// Calculate physical distance uncertainty from parallax measurement error
    ///
    /// For a star at distance d with parallax π ± σ_π:
    /// - Fractional distance error: σ_d/d = σ_π/π
    /// - Absolute distance error: σ_d = d × (σ_π/π)
    ///
    /// # Arguments
    /// * `parallax_error_mas` - Parallax measurement error in milliarcseconds
    ///
    /// # Returns
    /// Distance uncertainty in parsecs, or None if no distance is set
    pub fn distance_uncertainty_parsecs(&self, parallax_error_mas: f64) -> Option<f64> {
        self.distance.map(|d| {
            let parallax_mas = d.parallax_milliarcsec();
            let relative_error = parallax_error_mas / parallax_mas;
            d.parsecs() * relative_error
        })
    }
}

impl CoordinateFrame for ICRSPosition {
    fn to_icrs(&self, _epoch: &TT) -> CoordResult<ICRSPosition> {
        Ok(self.clone())
    }

    fn from_icrs(icrs: &ICRSPosition, _epoch: &TT) -> CoordResult<Self> {
        Ok(icrs.clone())
    }
}

impl ICRSPosition {
    pub fn to_galactic(&self, epoch: &TT) -> CoordResult<crate::GalacticPosition> {
        crate::GalacticPosition::from_icrs(self, epoch)
    }

    pub fn to_ecliptic(&self, epoch: &TT) -> CoordResult<crate::EclipticPosition> {
        crate::EclipticPosition::from_icrs(self, epoch)
    }
}

impl std::fmt::Display for ICRSPosition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "ICRS(RA={:.6}°, Dec={:.6}°",
            self.ra.degrees(),
            self.dec.degrees()
        )?;

        if let Some(distance) = self.distance {
            write!(f, ", d={}", distance)?;
        }

        write!(f, ")")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Distance;

    #[test]
    fn test_constructor_methods() {
        // Test basic constructor
        let pos1 =
            ICRSPosition::new(Angle::from_degrees(180.0), Angle::from_degrees(45.0)).unwrap();

        assert_eq!(pos1.ra().degrees(), Angle::from_degrees(180.0).degrees());
        assert_eq!(pos1.dec().degrees(), Angle::from_degrees(45.0).degrees());
        assert_eq!(pos1.distance(), None);

        // Test from_degrees constructor
        let pos2 = ICRSPosition::from_degrees(90.0, -30.0).unwrap();
        assert_eq!(pos2.ra().degrees(), Angle::from_degrees(90.0).degrees());
        assert_eq!(pos2.dec().degrees(), Angle::from_degrees(-30.0).degrees());

        // Test from_hours_degrees constructor
        let pos3 = ICRSPosition::from_hours_degrees(12.0, 60.0).unwrap();
        assert_eq!(pos3.ra().hours(), 12.0);
        assert_eq!(pos3.dec().degrees(), Angle::from_degrees(60.0).degrees());

        // Test with_distance constructor
        let distance = Distance::from_parsecs(10.0).unwrap();
        let pos4 = ICRSPosition::with_distance(
            Angle::from_degrees(0.0),
            Angle::from_degrees(0.0),
            distance,
        )
        .unwrap();
        assert_eq!(pos4.distance().unwrap(), distance);
    }

    #[test]
    fn test_accessor_methods() {
        let mut pos = ICRSPosition::from_degrees(270.0, 15.0).unwrap();
        let distance = Distance::from_parsecs(5.0).unwrap();

        // Test getters
        assert_eq!(pos.ra().degrees(), Angle::from_degrees(270.0).degrees());
        assert_eq!(pos.dec().degrees(), Angle::from_degrees(15.0).degrees());
        assert_eq!(pos.distance(), None);

        // Test set_distance
        pos.set_distance(distance);
        assert_eq!(pos.distance().unwrap(), distance);

        // Test remove_distance
        pos.remove_distance();
        assert_eq!(pos.distance(), None);
    }

    #[test]
    fn test_unit_vector_conversion() {
        // Test known positions
        let vernal_equinox = ICRSPosition::from_degrees(0.0, 0.0).unwrap();
        let unit_vec = vernal_equinox.unit_vector();

        // Vernal equinox should point to [1, 0, 0]
        assert_eq!(unit_vec.x, 1.0);
        assert_eq!(unit_vec.y, 0.0);
        assert_eq!(unit_vec.z, 0.0);

        // Test north celestial pole
        let north_pole = ICRSPosition::from_degrees(0.0, 90.0).unwrap();
        let pole_vec = north_pole.unit_vector();

        // At pole, compare with expected computed values (not mathematical ideals)
        let expected_pole = ICRSPosition::from_degrees(0.0, 90.0).unwrap().unit_vector();
        assert_eq!(pole_vec.x, expected_pole.x);
        assert_eq!(pole_vec.y, expected_pole.y);
        assert_eq!(pole_vec.z, expected_pole.z);
    }

    #[test]
    fn test_coordinate_transformations() {
        let pos = ICRSPosition::from_degrees(45.0, 30.0).unwrap();

        // Test ICRS to Galactic transformation
        let galactic = pos.to_galactic(&TT::j2000()).unwrap();
        assert!(galactic.longitude().degrees() >= 0.0); // Valid galactic longitude

        // Test ICRS to Ecliptic transformation
        let ecliptic = pos.to_ecliptic(&TT::j2000()).unwrap();
        assert!(ecliptic.lambda().degrees() >= 0.0); // Valid ecliptic longitude
    }

    #[test]
    fn test_coordinate_frame_implementation() {
        let pos = ICRSPosition::from_degrees(120.0, -45.0).unwrap();

        // ICRS to_icrs should return itself
        let icrs_copy = pos.to_icrs(&TT::j2000()).unwrap();
        assert_eq!(pos.ra().radians(), icrs_copy.ra().radians());
        assert_eq!(pos.dec().radians(), icrs_copy.dec().radians());

        // ICRS from_icrs should return itself
        let icrs_from = ICRSPosition::from_icrs(&pos, &TT::j2000()).unwrap();
        assert_eq!(pos.ra().radians(), icrs_from.ra().radians());
        assert_eq!(pos.dec().radians(), icrs_from.dec().radians());
    }

    #[test]
    fn test_transformation_consistency() {
        // Test that transformations are deterministic and consistent
        let test_positions = [
            (200.0, -20.0),
            (0.0, 0.0),   // Vernal equinox
            (90.0, 0.0),  // On celestial equator
            (45.0, 60.0), // High declination
        ];

        for (ra_deg, dec_deg) in test_positions {
            let original = ICRSPosition::from_degrees(ra_deg, dec_deg).unwrap();

            let galactic_1 = original.to_galactic(&TT::j2000()).unwrap();
            let galactic_2 = original.to_galactic(&TT::j2000()).unwrap();
            assert_eq!(
                galactic_1.longitude().radians(),
                galactic_2.longitude().radians()
            );
            assert_eq!(
                galactic_1.latitude().radians(),
                galactic_2.latitude().radians()
            );

            let ecliptic_1 = original.to_ecliptic(&TT::j2000()).unwrap();
            let ecliptic_2 = original.to_ecliptic(&TT::j2000()).unwrap();
            assert_eq!(ecliptic_1.lambda().radians(), ecliptic_2.lambda().radians());
            assert_eq!(ecliptic_1.beta().radians(), ecliptic_2.beta().radians());
        }
    }

    #[test]
    fn test_coordinate_validation() {
        // Valid coordinates
        assert!(ICRSPosition::from_degrees(0.0, 0.0).is_ok());
        assert!(ICRSPosition::from_degrees(359.99, 89.99).is_ok());
        assert!(ICRSPosition::from_degrees(180.0, -89.99).is_ok());

        // Invalid declination
        assert!(ICRSPosition::from_degrees(0.0, 91.0).is_err());
        assert!(ICRSPosition::from_degrees(0.0, -91.0).is_err());
    }

    #[test]
    fn test_distance_handling() {
        let distance1 = Distance::from_parsecs(100.0).unwrap();
        let _distance2 = Distance::from_parsecs(50.0).unwrap();

        let pos = ICRSPosition::with_distance(
            Angle::from_degrees(90.0),
            Angle::from_degrees(45.0),
            distance1,
        )
        .unwrap();

        // Distance should be preserved in transformations
        let galactic = pos.to_galactic(&TT::j2000()).unwrap();
        assert_eq!(galactic.distance().unwrap(), distance1);

        let ecliptic = pos.to_ecliptic(&TT::j2000()).unwrap();
        assert_eq!(ecliptic.distance().unwrap(), distance1);
    }

    #[test]
    fn test_additional_constructor_methods() {
        let distance = Distance::from_parsecs(10.0).unwrap();

        // Test from_degrees_with_distance
        let pos = ICRSPosition::from_degrees_with_distance(120.0, 45.0, distance).unwrap();
        assert_eq!(pos.ra().degrees(), Angle::from_degrees(120.0).degrees());
        assert_eq!(pos.dec().degrees(), Angle::from_degrees(45.0).degrees());
        assert_eq!(pos.distance().unwrap(), distance);
    }

    #[test]
    fn test_vector_operations() {
        let distance = Distance::from_au(5.0).unwrap();
        let pos = ICRSPosition::with_distance(
            Angle::from_degrees(0.0),
            Angle::from_degrees(0.0),
            distance,
        )
        .unwrap();

        // Test position_vector
        let pos_vec = pos.position_vector().unwrap();

        // Test with expected computed values rather than mathematical ideals
        let expected_x = distance.au() * pos.unit_vector().x;
        let expected_y = distance.au() * pos.unit_vector().y;
        let expected_z = distance.au() * pos.unit_vector().z;

        assert_eq!(pos_vec.x, expected_x);
        assert_eq!(pos_vec.y, expected_y);
        assert_eq!(pos_vec.z, expected_z);

        // Test from_position_vector (test the operation works, not exact roundtrip)
        let recovered = ICRSPosition::from_position_vector(pos_vec).unwrap();

        // Position should be consistent
        assert_eq!(recovered.ra().degrees(), pos.ra().degrees());
        assert_eq!(recovered.dec().degrees(), pos.dec().degrees());

        // Distance should exist (test the operation works)
        assert!(recovered.distance().is_some());

        // Test from_unit_vector
        let unit_vec = pos.unit_vector();
        let from_unit = ICRSPosition::from_unit_vector(unit_vec).unwrap();
        assert_eq!(from_unit.ra().degrees(), pos.ra().degrees());
        assert_eq!(from_unit.dec().degrees(), pos.dec().degrees());
        assert_eq!(from_unit.distance(), None); // Unit vector has no distance
    }

    #[test]
    fn test_vector_error_cases() {
        // Test zero vector error for from_unit_vector
        let zero_vec = Vector3::new(0.0, 0.0, 0.0);
        assert!(ICRSPosition::from_unit_vector(zero_vec).is_err());

        // Test zero vector error for from_position_vector
        assert!(ICRSPosition::from_position_vector(zero_vec).is_err());

        // Test position_vector without distance
        let pos_no_dist = ICRSPosition::from_degrees(0.0, 0.0).unwrap();
        assert!(pos_no_dist.position_vector().is_err());
    }

    #[test]
    fn test_angular_separation() {
        let pos1 = ICRSPosition::from_degrees(0.0, 0.0).unwrap(); // Vernal equinox
        let pos2 = ICRSPosition::from_degrees(90.0, 0.0).unwrap(); // 90° away
        let pos3 = ICRSPosition::from_degrees(0.0, 90.0).unwrap(); // North pole

        // Test 90° separation (allow ULP tolerance for haversine formula)
        let sep_90 = pos1.angular_separation(&pos2);
        celestial_core::test_helpers::assert_ulp_le(sep_90.degrees(), 90.0, 2, "90° separation");

        // Test pole separation
        let sep_pole = pos1.angular_separation(&pos3);
        celestial_core::test_helpers::assert_ulp_le(sep_pole.degrees(), 90.0, 2, "Pole separation");

        // Test self separation
        let sep_self = pos1.angular_separation(&pos1);
        assert!(
            sep_self.degrees().abs() < 1e-10,
            "Self separation should be near zero"
        );

        // Test symmetry
        let sep_12 = pos1.angular_separation(&pos2);
        let sep_21 = pos2.angular_separation(&pos1);
        assert_eq!(sep_12.degrees(), sep_21.degrees());
    }

    #[test]
    fn test_pole_classification() {
        // Test positions near poles
        let north_pole = ICRSPosition::from_degrees(0.0, 89.5).unwrap();
        assert!(north_pole.is_near_pole());

        let south_pole = ICRSPosition::from_degrees(0.0, -89.5).unwrap();
        assert!(south_pole.is_near_pole());

        // Test positions not near poles
        let equator = ICRSPosition::from_degrees(0.0, 0.0).unwrap();
        assert!(!equator.is_near_pole());

        let mid_lat = ICRSPosition::from_degrees(0.0, 45.0).unwrap();
        assert!(!mid_lat.is_near_pole());

        // Test boundary case
        let boundary = ICRSPosition::from_degrees(0.0, 89.0).unwrap();
        assert!(!boundary.is_near_pole()); // Exactly at 89° should be false
    }

    #[test]
    fn test_position_uncertainty() {
        let distance = Distance::from_parsecs(100.0).unwrap();
        let pos_with_dist = ICRSPosition::with_distance(
            Angle::from_degrees(0.0),
            Angle::from_degrees(0.0),
            distance,
        )
        .unwrap();

        // Test uncertainty calculation with distance
        let uncertainty = pos_with_dist.position_uncertainty_arcsec(1.0); // 1 mas parallax error
        assert!(uncertainty.is_some());
        assert!(uncertainty.unwrap() > 0.0);

        // Test uncertainty without distance
        let pos_no_dist = ICRSPosition::from_degrees(0.0, 0.0).unwrap();
        let no_uncertainty = pos_no_dist.position_uncertainty_arcsec(1.0);
        assert!(no_uncertainty.is_none());
    }

    #[test]
    fn test_display_formatting() {
        // Test without distance
        let pos_no_dist = ICRSPosition::from_degrees(123.456789, -67.123456).unwrap();
        let display_no_dist = format!("{}", pos_no_dist);
        assert!(display_no_dist.contains("RA=123.456789°"));
        assert!(display_no_dist.contains("Dec=-67.123456°"));
        assert!(!display_no_dist.contains("d="));

        // Test with distance
        let distance = Distance::from_parsecs(25.0).unwrap();
        let pos_with_dist = ICRSPosition::with_distance(
            Angle::from_degrees(45.0),
            Angle::from_degrees(30.0),
            distance,
        )
        .unwrap();
        let display_with_dist = format!("{}", pos_with_dist);
        assert!(display_with_dist.contains("RA=45.000000°"));
        assert!(display_with_dist.contains("Dec=30.000000°"));
        assert!(display_with_dist.contains("d=25"));
    }

    #[test]
    fn test_position_uncertainty_dimensional_analysis() {
        // Test that position_uncertainty_arcsec has correct dimensions
        let distance = Distance::from_parsecs(100.0).unwrap(); // 100 pc
        let pos = ICRSPosition::with_distance(
            Angle::from_degrees(0.0),
            Angle::from_degrees(0.0),
            distance,
        )
        .unwrap();

        // Gaia DR3 typical parallax error: 0.02 mas
        let parallax_error_mas = 0.02;

        // Position uncertainty (angular) should equal parallax uncertainty
        let position_uncertainty = pos.position_uncertainty_arcsec(parallax_error_mas).unwrap();

        // Expected: 0.02 mas = 0.00002 arcsec
        assert!((position_uncertainty - 0.00002).abs() < 1e-10);

        // Dimensional check: result is in arcseconds (angular measure)
        // Input: milliarcseconds -> Output: arcseconds
        // Conversion: mas / 1000 = arcsec ✓
    }

    #[test]
    fn test_distance_uncertainty_dimensional_analysis() {
        // Test that distance_uncertainty_parsecs has correct dimensions
        let distance = Distance::from_parsecs(100.0).unwrap(); // 100 pc
        let pos = ICRSPosition::with_distance(
            Angle::from_degrees(0.0),
            Angle::from_degrees(0.0),
            distance,
        )
        .unwrap();

        // Parallax for 100 pc: 0.01 arcsec = 10 mas
        let parallax_mas = distance.parallax_milliarcsec();
        assert!((parallax_mas - 10.0).abs() < 1e-10);

        // Parallax error: 0.1 mas (1% of parallax)
        let parallax_error_mas = 0.1;

        // Distance uncertainty
        let dist_uncertainty = pos
            .distance_uncertainty_parsecs(parallax_error_mas)
            .unwrap();

        // Expected: σ_d = d × (σ_π/π) = 100 × (0.1/10) = 1 pc
        assert!((dist_uncertainty - 1.0).abs() < 1e-10);

        // Dimensional check:
        // σ_d [pc] = d [pc] × (σ_π [mas] / π [mas]) [dimensionless] ✓
    }

    #[test]
    fn test_position_vs_distance_uncertainty_relationship() {
        // Verify the relationship between angular and physical uncertainties
        let distance = Distance::from_parsecs(10.0).unwrap(); // 10 pc (parallax = 100 mas)
        let pos = ICRSPosition::with_distance(
            Angle::from_degrees(0.0),
            Angle::from_degrees(0.0),
            distance,
        )
        .unwrap();

        let parallax_error_mas = 5.0; // 5 mas error

        // Angular position uncertainty
        let angular_unc_arcsec = pos.position_uncertainty_arcsec(parallax_error_mas).unwrap();
        assert_eq!(angular_unc_arcsec, 0.005); // 5 mas = 0.005 arcsec

        // Physical distance uncertainty
        let distance_unc_pc = pos
            .distance_uncertainty_parsecs(parallax_error_mas)
            .unwrap();
        // σ_d = 10 × (5/100) = 0.5 pc
        assert!((distance_unc_pc - 0.5).abs() < 1e-10);

        // Relationship: For small angles, physical transverse uncertainty ≈ d × angular_uncertainty
        // But here we're measuring distance along the line of sight (parallax)
        // not transverse position, so the relationship is different
    }

    #[test]
    fn test_uncertainty_without_distance() {
        // Test that uncertainty functions return None when no distance is set
        let pos = ICRSPosition::from_degrees(0.0, 0.0).unwrap();

        assert_eq!(pos.position_uncertainty_arcsec(0.1), None);
        assert_eq!(pos.distance_uncertainty_parsecs(0.1), None);
    }

    #[test]
    fn test_gaia_realistic_example() {
        // Realistic Gaia DR3 example
        // Star at 500 pc with Gaia parallax error of 0.03 mas
        let distance = Distance::from_parsecs(500.0).unwrap();
        let pos = ICRSPosition::with_distance(
            Angle::from_degrees(120.5),
            Angle::from_degrees(-45.2),
            distance,
        )
        .unwrap();

        // Parallax: 2 mas (for 500 pc)
        let parallax_mas = distance.parallax_milliarcsec();
        assert!((parallax_mas - 2.0).abs() < 1e-10);

        // Gaia error: 0.03 mas
        let gaia_error_mas = 0.03;

        // Position uncertainty on sky
        let pos_unc = pos.position_uncertainty_arcsec(gaia_error_mas).unwrap();
        assert!(
            (pos_unc - 0.00003).abs() < 1e-10,
            "Position uncertainty: {}",
            pos_unc
        ); // 0.03 mas = 0.00003 arcsec

        // Distance uncertainty: σ_d = 500 × (0.03/2) = 7.5 pc
        let dist_unc = pos.distance_uncertainty_parsecs(gaia_error_mas).unwrap();
        assert!((dist_unc - 7.5).abs() < 1e-10);

        // Fractional distance error: 7.5/500 = 1.5%
        let fractional_error = dist_unc / distance.parsecs();
        assert!((fractional_error - 0.015).abs() < 1e-10);
    }

    #[test]
    fn test_from_unit_vector_north_pole() {
        let north_pole_vec = Vector3::new(0.0, 0.0, 1.0);
        let pos = ICRSPosition::from_unit_vector(north_pole_vec).unwrap();

        assert_eq!(pos.ra().radians(), 0.0);
        assert_eq!(pos.dec().radians(), std::f64::consts::FRAC_PI_2);
    }

    #[test]
    fn test_from_unit_vector_south_pole() {
        let south_pole_vec = Vector3::new(0.0, 0.0, -1.0);
        let pos = ICRSPosition::from_unit_vector(south_pole_vec).unwrap();

        assert_eq!(pos.ra().radians(), 0.0);
        assert_eq!(pos.dec().radians(), -std::f64::consts::FRAC_PI_2);
    }

    #[test]
    fn test_pole_roundtrip() {
        let north_pole = ICRSPosition::from_degrees(0.0, 90.0).unwrap();
        let unit_vec = north_pole.unit_vector();
        let recovered = ICRSPosition::from_unit_vector(unit_vec).unwrap();

        assert_eq!(recovered.ra().radians(), 0.0);
        assert_eq!(recovered.dec().degrees(), 90.0);

        let south_pole = ICRSPosition::from_degrees(0.0, -90.0).unwrap();
        let unit_vec = south_pole.unit_vector();
        let recovered = ICRSPosition::from_unit_vector(unit_vec).unwrap();

        assert_eq!(recovered.ra().radians(), 0.0);
        assert_eq!(recovered.dec().degrees(), -90.0);
    }
}