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
use crate::{
    aberration::{
        apply_aberration, apply_light_deflection, compute_earth_state, remove_aberration,
        remove_light_deflection,
    },
    frames::{ICRSPosition, TIRSPosition},
    transforms::CoordinateFrame,
    CoordError, CoordResult, Distance,
};
use celestial_core::{matrix::RotationMatrix3, Angle, Vector3};
use celestial_time::{
    scales::conversions::ToUT1WithDeltaT, sidereal::GAST, transforms::NutationCalculator, TT,
};

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

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

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

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

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

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

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

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

    pub fn epoch(&self) -> TT {
        self.epoch
    }

    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 from_unit_vector(unit: Vector3, epoch: TT) -> 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), epoch)
    }

    fn icrs_to_cirs_matrix(epoch: &TT) -> CoordResult<RotationMatrix3> {
        Self::icrs_to_cirs_matrix_with_eop(epoch, None)
    }

    fn icrs_to_cirs_matrix_with_eop(
        epoch: &TT,
        eop: Option<&crate::eop::EopParameters>,
    ) -> CoordResult<RotationMatrix3> {
        let jd = epoch.to_julian_date();
        let t = celestial_core::utils::jd_to_centuries(jd.jd1(), jd.jd2());

        let nutation = epoch
            .nutation_iau2006a()
            .map_err(|e| CoordError::CoreError {
                message: format!("Nutation calculation failed: {}", e),
            })?;

        let precession_calc = celestial_core::precession::PrecessionIAU2006::new();
        let npb_matrix = precession_calc.npb_matrix_iau2006a(
            t,
            nutation.nutation_longitude(),
            nutation.nutation_obliquity(),
        );

        let cio_solution = celestial_core::CioSolution::calculate(&npb_matrix, t).map_err(|e| {
            CoordError::CoreError {
                message: format!("CIO calculation failed: {}", e),
            }
        })?;

        let (x, y) = match eop {
            Some(eop) => (
                eop.corrected_cip_x(cio_solution.cip.x),
                eop.corrected_cip_y(cio_solution.cip.y),
            ),
            None => (cio_solution.cip.x, cio_solution.cip.y),
        };

        Ok(celestial_core::gcrs_to_cirs_matrix(x, y, cio_solution.s))
    }

    /// Transforms this CIRS position to Terrestrial Intermediate Reference System (TIRS).
    ///
    /// The position vector is scaled by distance (in AU) before transformation. If no distance
    /// is set, a unit vector is used. The resulting TIRS vector will have the same units (AU or
    /// dimensionless) as the input.
    pub fn to_tirs(&self, eop: &crate::eop::EopParameters) -> CoordResult<TIRSPosition> {
        let cirs_vec = if let Some(distance) = self.distance {
            self.unit_vector() * distance.au()
        } else {
            self.unit_vector()
        };

        TIRSPosition::from_cirs(cirs_vec, &self.epoch, eop)
    }

    pub fn to_hour_angle(
        &self,
        observer: &celestial_core::Location,
        delta_t: f64,
    ) -> CoordResult<crate::frames::HourAnglePosition> {
        let ut1 = self.epoch.to_ut1_with_delta_t(delta_t)?;
        let gast = GAST::from_ut1_and_tt(&ut1, &self.epoch)?;

        let last = gast.to_last(observer);

        let ha_rad = last.radians() - self.ra.radians();
        let ha = celestial_core::angle::wrap_pm_pi(ha_rad);

        crate::frames::HourAnglePosition::new(
            Angle::from_radians(ha),
            self.dec,
            *observer,
            self.epoch,
        )
    }
}

impl CoordinateFrame for CIRSPosition {
    fn to_icrs(&self, _epoch: &TT) -> CoordResult<ICRSPosition> {
        let icrs_to_cirs = Self::icrs_to_cirs_matrix(&self.epoch)?;
        let cirs_to_icrs = icrs_to_cirs.transpose();

        // Step 1: Remove precession-nutation
        let cirs_vec = self.unit_vector();
        let apparent_vec = cirs_to_icrs * cirs_vec;

        let earth_state = compute_earth_state(&self.epoch)?;
        let sun_earth_dist = earth_state.heliocentric_position.magnitude();

        // Step 2: Remove stellar aberration
        let deflected_vec = remove_aberration(
            apparent_vec,
            earth_state.barycentric_velocity,
            sun_earth_dist,
        );

        // Sun to observer unit vector (heliocentric position normalized)
        let sun_to_earth = Vector3::new(
            earth_state.heliocentric_position.x / sun_earth_dist,
            earth_state.heliocentric_position.y / sun_earth_dist,
            earth_state.heliocentric_position.z / sun_earth_dist,
        );

        // Step 3: Remove gravitational light deflection
        let icrs_vec = remove_light_deflection(deflected_vec, sun_to_earth, sun_earth_dist);

        let mut icrs = ICRSPosition::from_unit_vector(icrs_vec)?;

        if let Some(distance) = self.distance {
            icrs.set_distance(distance);
        }

        Ok(icrs)
    }

    fn from_icrs(icrs: &ICRSPosition, epoch: &TT) -> CoordResult<Self> {
        let icrs_to_cirs = Self::icrs_to_cirs_matrix(epoch)?;

        let icrs_vec = icrs.unit_vector();

        let earth_state = compute_earth_state(epoch)?;
        let sun_earth_dist = earth_state.heliocentric_position.magnitude();

        // Sun to observer unit vector (heliocentric position normalized)
        // heliocentric_position is Earth's position relative to Sun, so normalizing gives Sun→Earth direction
        let sun_to_earth = Vector3::new(
            earth_state.heliocentric_position.x / sun_earth_dist,
            earth_state.heliocentric_position.y / sun_earth_dist,
            earth_state.heliocentric_position.z / sun_earth_dist,
        );

        // Step 1: Apply gravitational light deflection by the Sun
        let deflected_vec = apply_light_deflection(icrs_vec, sun_to_earth, sun_earth_dist);

        // Step 2: Apply stellar aberration
        let apparent_vec = apply_aberration(
            deflected_vec,
            earth_state.barycentric_velocity,
            sun_earth_dist,
        );

        // Step 3: Apply precession-nutation (C2I matrix)
        let cirs_vec = icrs_to_cirs * apparent_vec;

        let mut cirs = Self::from_unit_vector(cirs_vec, *epoch)?;

        if let Some(distance) = icrs.distance() {
            cirs.distance = Some(distance);
        }

        Ok(cirs)
    }
}

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

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

        write!(f, ")")
    }
}

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

    #[test]
    fn test_cirs_creation() {
        let epoch = TT::j2000();
        let pos = CIRSPosition::from_degrees(180.0, 45.0, epoch).unwrap();

        assert_eq!(pos.ra().degrees(), 180.0);
        assert_eq!(pos.dec().degrees(), 45.0);
        assert_eq!(pos.epoch(), epoch);
        assert_eq!(pos.distance(), None);
    }

    #[test]
    fn test_cirs_with_distance() {
        let epoch = TT::j2000();
        let distance = Distance::from_parsecs(10.0).unwrap();
        let pos = CIRSPosition::with_distance(
            Angle::from_degrees(90.0),
            Angle::from_degrees(30.0),
            epoch,
            distance,
        )
        .unwrap();

        assert_eq!(pos.distance().unwrap(), distance);
    }

    #[test]
    fn test_unit_vector_conversion() {
        let epoch = TT::j2000();

        // Test vernal equinox direction
        let vernal_equinox = CIRSPosition::from_degrees(0.0, 0.0, epoch).unwrap();
        let unit_vec = vernal_equinox.unit_vector();

        assert_eq!(unit_vec.x, 1.0);
        assert_eq!(unit_vec.y, 0.0);
        assert_eq!(unit_vec.z, 0.0);

        // Test round-trip
        let recovered = CIRSPosition::from_unit_vector(unit_vec, epoch).unwrap();
        assert_eq!(recovered.ra().degrees(), vernal_equinox.ra().degrees());
        assert_eq!(recovered.dec().degrees(), vernal_equinox.dec().degrees());
    }

    #[test]
    fn test_icrs_to_cirs_transformation() {
        let epoch = TT::j2000();
        let icrs = ICRSPosition::from_degrees(180.0, 45.0).unwrap();

        // Transform to CIRS
        let cirs = CIRSPosition::from_icrs(&icrs, &epoch).unwrap();

        // At J2000, CIRS should be very close to ICRS (small precession/nutation effects)
        // But not exactly equal due to frame bias
        assert!((cirs.ra().degrees() - icrs.ra().degrees()).abs() < 1.0);
        assert!((cirs.dec().degrees() - icrs.dec().degrees()).abs() < 1.0);
    }

    #[test]
    fn test_cirs_to_icrs_roundtrip() {
        let epoch = TT::j2000();
        let original_icrs = ICRSPosition::from_degrees(120.0, 30.0).unwrap();

        // ICRS → CIRS → ICRS
        let cirs = CIRSPosition::from_icrs(&original_icrs, &epoch).unwrap();
        let recovered_icrs = cirs.to_icrs(&epoch).unwrap();

        // Iterative inverse (aberration + light deflection) gives ~50 nano-arcsec precision
        let diff_arcsec = original_icrs
            .angular_separation(&recovered_icrs)
            .arcseconds();
        assert!(
            diff_arcsec < 1e-7,
            "CIRS roundtrip should be < 100 nano-arcsec, got {:.2e} arcsec",
            diff_arcsec
        );
    }

    #[test]
    fn test_coordinate_validation() {
        let epoch = TT::j2000();

        // Valid coordinates
        assert!(CIRSPosition::from_degrees(0.0, 0.0, epoch).is_ok());
        assert!(CIRSPosition::from_degrees(359.99, 89.99, epoch).is_ok());

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

    #[test]
    fn test_distance_preservation() {
        let epoch = TT::j2000();
        let distance = Distance::from_parsecs(100.0).unwrap();
        let icrs = ICRSPosition::from_degrees_with_distance(90.0, 45.0, distance).unwrap();

        // Distance should be preserved through transformation
        let cirs = CIRSPosition::from_icrs(&icrs, &epoch).unwrap();
        assert_eq!(cirs.distance().unwrap(), distance);

        let recovered_icrs = cirs.to_icrs(&epoch).unwrap();
        assert_eq!(recovered_icrs.distance().unwrap(), distance);
    }

    #[test]
    fn test_display_formatting() {
        let epoch = TT::j2000();
        let pos = CIRSPosition::from_degrees(123.456789, -67.123456, epoch).unwrap();
        let display = format!("{}", pos);

        assert!(display.contains("CIRS"));
        assert!(display.contains("RA=123.456789°"));
        assert!(display.contains("Dec=-67.123456°"));
        assert!(display.contains("J2000.0"));
    }

    #[test]
    fn test_aberration_applied_in_transformation() {
        let epoch = TT::j2000();
        let icrs = ICRSPosition::from_degrees(90.0, 23.0).unwrap();

        let icrs_vec = icrs.unit_vector();
        let cirs = CIRSPosition::from_icrs(&icrs, &epoch).unwrap();
        let cirs_vec = cirs.unit_vector();

        let npb_only = CIRSPosition::icrs_to_cirs_matrix(&epoch).unwrap() * icrs_vec;

        let diff_with_aberr = (cirs_vec.x - npb_only.x).powi(2)
            + (cirs_vec.y - npb_only.y).powi(2)
            + (cirs_vec.z - npb_only.z).powi(2);
        let aberr_arcsec = libm::sqrt(diff_with_aberr) * 206264.806247;

        assert!(
            aberr_arcsec > 15.0 && aberr_arcsec < 25.0,
            "Aberration should be ~20 arcsec, got {:.2} arcsec",
            aberr_arcsec
        );
    }

    #[test]
    fn test_aberration_varies_with_epoch() {
        let icrs = ICRSPosition::from_degrees(180.0, 45.0).unwrap();

        let epoch_jan = TT::from_julian_date(celestial_time::JulianDate::new(2451545.0, 0.0));
        let epoch_jul = TT::from_julian_date(celestial_time::JulianDate::new(2451545.0, 182.5));

        let cirs_jan = CIRSPosition::from_icrs(&icrs, &epoch_jan).unwrap();
        let cirs_jul = CIRSPosition::from_icrs(&icrs, &epoch_jul).unwrap();

        let ra_diff_arcsec = (cirs_jan.ra().degrees() - cirs_jul.ra().degrees()).abs() * 3600.0;
        let dec_diff_arcsec = (cirs_jan.dec().degrees() - cirs_jul.dec().degrees()).abs() * 3600.0;

        assert!(
            ra_diff_arcsec > 1.0 || dec_diff_arcsec > 1.0,
            "Aberration should cause measurable difference between epochs: RA={:.2}\", Dec={:.2}\"",
            ra_diff_arcsec,
            dec_diff_arcsec
        );
    }

    #[test]
    fn test_aberration_roundtrip_precision() {
        let test_positions = [
            (0.0, 0.0),
            (90.0, 0.0),
            (180.0, 45.0),
            (270.0, -60.0),
            (45.0, 89.0),
        ];

        for (ra, dec) in test_positions {
            let epoch = TT::j2000();
            let icrs = ICRSPosition::from_degrees(ra, dec).unwrap();
            let cirs = CIRSPosition::from_icrs(&icrs, &epoch).unwrap();
            let recovered = cirs.to_icrs(&epoch).unwrap();

            // Iterative inverse (aberration + light deflection) gives ~70 nano-arcsec precision
            let diff_arcsec = icrs.angular_separation(&recovered).arcseconds();
            assert!(
                diff_arcsec < 1e-7,
                "Roundtrip for ({}, {}) should be < 100 nano-arcsec, got {:.2e} arcsec",
                ra,
                dec,
                diff_arcsec
            );
        }
    }

    #[test]
    fn test_from_unit_vector_north_pole() {
        let epoch = TT::j2000();
        let north_pole_vec = Vector3::new(0.0, 0.0, 1.0);
        let pos = CIRSPosition::from_unit_vector(north_pole_vec, epoch).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 epoch = TT::j2000();
        let south_pole_vec = Vector3::new(0.0, 0.0, -1.0);
        let pos = CIRSPosition::from_unit_vector(south_pole_vec, epoch).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 epoch = TT::j2000();

        let north_pole = CIRSPosition::from_degrees(0.0, 90.0, epoch).unwrap();
        let unit_vec = north_pole.unit_vector();
        let recovered = CIRSPosition::from_unit_vector(unit_vec, epoch).unwrap();

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

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

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