lox-space 0.1.0-alpha.48

The Lox toolbox for space mission analysis and design
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
// SPDX-FileCopyrightText: 2024 Helge Eichhorn <git@helgeeichhorn.de>
//
// SPDX-License-Identifier: MPL-2.0

use std::ops::{Add, Sub};
use std::str::FromStr;

use lox_test_utils::{ApproxEq, approx_eq};
use lox_time::subsecond::Subsecond;
use pyo3::basic::CompareOp;
use pyo3::exceptions::{PyException, PyTypeError, PyValueError};
use pyo3::types::{PyAnyMethods, PyType};
use pyo3::{
    Bound, IntoPyObjectExt, Py, PyAny, PyErr, PyResult, Python, create_exception, pyclass,
    pymethods,
};

use crate::earth::python::ut1::{PyEopProvider, PyEopProviderError};
use crate::time::calendar_dates::{CalendarDate, Date};
use crate::time::deltas::{TimeDelta, ToDelta};
use crate::time::julian_dates::{Epoch, JulianDate, Unit};
use crate::time::python::deltas::PyTimeDelta;
use crate::time::time_of_day::{CivilTime, TimeOfDay};
use crate::time::time_scales::Tai;
use crate::time::utc::transformations::ToUtc;
use crate::time::{DynTime, Time, TimeError, TimeScaleMismatch};

use super::time_scales::PyTimeScale;
use super::utc::PyUtc;

create_exception!(
    lox_space,
    NonFiniteTimeError,
    PyException,
    "Python exception raised when a non-finite `Time` is accessed."
);

/// Wrapper converting [`TimeError`] into a Python `ValueError`.
pub struct PyTimeError(pub TimeError);

impl From<PyTimeError> for PyErr {
    fn from(err: PyTimeError) -> Self {
        PyValueError::new_err(err.0.to_string())
    }
}

struct PyTimeScaleMismatch(TimeScaleMismatch);

impl From<PyTimeScaleMismatch> for PyErr {
    fn from(err: PyTimeScaleMismatch) -> Self {
        PyValueError::new_err(err.0.to_string())
    }
}

/// Wrapper parsing a Julian date epoch string into a [`lox_time::julian_dates::Epoch`].
pub struct PyEpoch(pub Epoch);

impl FromStr for PyEpoch {
    type Err = PyErr;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "jd" | "JD" => Ok(Epoch::JulianDate),
            "mjd" | "MJD" => Ok(Epoch::ModifiedJulianDate),
            "j1950" | "J1950" => Ok(Epoch::J1950),
            "j2000" | "J2000" => Ok(Epoch::J2000),
            _ => Err(PyValueError::new_err(format!("unknown epoch: {s}"))),
        }
        .map(PyEpoch)
    }
}

/// Wrapper parsing a Julian date unit string into a [`lox_time::julian_dates::Unit`].
pub struct PyUnit(pub Unit);

impl FromStr for PyUnit {
    type Err = PyErr;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "seconds" => Ok(Unit::Seconds),
            "days" => Ok(Unit::Days),
            "centuries" => Ok(Unit::Centuries),
            _ => Err(PyValueError::new_err(format!("unknown unit: {s}"))),
        }
        .map(PyUnit)
    }
}

/// Represents an instant in time on a specific astronomical time scale.
///
/// `Time` is the fundamental time representation in lox, providing
/// femtosecond precision and support for multiple astronomical time scales
/// (TAI, TT, TDB, TCB, TCG, UT1).
///
/// Args:
///     scale: Time scale ("TAI", "TT", "TDB", "TCB", "TCG", "UT1") or TimeScale object.
///     year: Calendar year.
///     month: Calendar month (1-12).
///     day: Day of month (1-31).
///     hour: Hour of day (0-23). Defaults to 0.
///     minute: Minute of hour (0-59). Defaults to 0.
///     seconds: Seconds with fractional part (0.0-60.0). Defaults to 0.0.
///
/// Raises:
///     ValueError: If date or time components are out of valid range.
///
/// See Also:
///     TimeDelta: For representing time differences.
///     UTC: For UTC time with leap second handling.
#[pyclass(name = "Time", module = "lox_space", frozen, from_py_object)]
#[derive(Clone, Debug, Eq, PartialEq, ApproxEq)]
pub struct PyTime(pub DynTime);

#[pymethods]
impl PyTime {
    #[new]
    /// Constructs a `Time` from a time scale and calendar date/time components.
    #[pyo3(signature=(scale, year, month, day, hour = 0, minute = 0, seconds = 0.0))]
    pub fn new(
        scale: &Bound<'_, PyAny>,
        year: i64,
        month: u8,
        day: u8,
        hour: u8,
        minute: u8,
        seconds: f64,
    ) -> PyResult<PyTime> {
        let scale: PyTimeScale = scale.try_into()?;
        let time = Time::builder_with_scale(scale.0)
            .with_ymd(year, month, day)
            .with_hms(hour, minute, seconds)
            .build()
            .map_err(PyTimeError)?;
        Ok(PyTime(time))
    }

    fn __getnewargs__<'py>(
        &self,
        py: Python<'py>,
    ) -> (Bound<'py, PyAny>, i64, u8, u8, u8, u8, f64) {
        (
            self.scale().into_bound_py_any(py).unwrap(),
            self.0.year(),
            self.0.month(),
            self.0.day(),
            self.0.hour(),
            self.0.minute(),
            self.0.as_seconds_f64(),
        )
    }

    /// Create a Time from a Julian date.
    ///
    /// Args:
    ///     scale: Time scale for the resulting Time object.
    ///     jd: Julian date value.
    ///     epoch: Reference epoch ("jd", "mjd", "j1950", "j2000"). Defaults to "jd".
    ///
    /// Returns:
    ///     A new Time object.
    ///
    /// Examples:
    ///     >>> t = Time.from_julian_date("TAI", 2451545.0, "jd")  # J2000.0
    #[classmethod]
    #[pyo3(signature = (scale, jd, epoch = "jd"))]
    pub fn from_julian_date(
        _cls: &Bound<'_, PyType>,
        scale: &Bound<'_, PyAny>,
        jd: f64,
        epoch: &str,
    ) -> PyResult<Self> {
        let scale: PyTimeScale = scale.try_into()?;
        let epoch: PyEpoch = epoch.parse()?;
        Ok(Self(Time::from_julian_date(scale.0, jd, epoch.0)))
    }

    /// Create a Time from a two-part Julian date for maximum precision.
    ///
    /// This method preserves full precision by accepting the Julian date
    /// as two separate float components that are added together.
    ///
    /// Args:
    ///     scale: Time scale for the resulting Time object.
    ///     jd1: First part of the Julian date (typically the integer part).
    ///     jd2: Second part of the Julian date (typically the fractional part).
    ///
    /// Returns:
    ///     A new Time object.
    #[classmethod]
    pub fn from_two_part_julian_date(
        _cls: &Bound<'_, PyType>,
        scale: &Bound<'_, PyAny>,
        jd1: f64,
        jd2: f64,
    ) -> PyResult<Self> {
        let scale: PyTimeScale = scale.try_into()?;
        Ok(Self(Time::from_two_part_julian_date(scale.0, jd1, jd2)))
    }

    /// Create a Time from year and day of year.
    ///
    /// Args:
    ///     scale: Time scale for the resulting Time object.
    ///     year: Calendar year.
    ///     day: Day of year (1-366).
    ///     hour: Hour of day (0-23). Defaults to 0.
    ///     minute: Minute of hour (0-59). Defaults to 0.
    ///     seconds: Seconds with fractional part. Defaults to 0.0.
    ///
    /// Returns:
    ///     A new Time object.
    ///
    /// Raises:
    ///     ValueError: If day of year is out of range for the given year.
    ///
    /// Examples:
    ///     >>> t = Time.from_day_of_year("TAI", 2024, 1)  # Jan 1, 2024
    ///     >>> t = Time.from_day_of_year("TAI", 2024, 366)  # Dec 31, 2024 (leap year)
    #[classmethod]
    #[pyo3(signature=(scale, year, day, hour=0, minute=0, seconds=0.0))]
    pub fn from_day_of_year(
        _cls: &Bound<'_, PyType>,
        scale: &Bound<'_, PyAny>,
        year: i64,
        day: u16,
        hour: u8,
        minute: u8,
        seconds: f64,
    ) -> PyResult<PyTime> {
        let scale: PyTimeScale = scale.try_into()?;
        let time = Time::builder_with_scale(scale.0)
            .with_doy(year, day)
            .with_hms(hour, minute, seconds)
            .build()
            .map_err(PyTimeError)?;
        Ok(PyTime(time))
    }

    /// Create a Time from an ISO 8601 formatted string.
    ///
    /// Args:
    ///     iso: ISO 8601 formatted datetime string (e.g., "2024-06-15T12:30:45.5 TAI").
    ///     scale: Time scale. If not provided, the scale must be in the ISO string.
    ///
    /// Returns:
    ///     A new Time object.
    ///
    /// Raises:
    ///     ValueError: If the ISO string is invalid or the scale cannot be determined.
    ///
    /// Examples:
    ///     >>> t = Time.from_iso("2024-06-15T12:30:45.5 TAI")
    ///     >>> t = Time.from_iso("2024-06-15T12:30:45.5", "TAI")
    #[classmethod]
    #[pyo3(signature = (iso, scale=None))]
    pub fn from_iso(
        _cls: &Bound<'_, PyType>,
        iso: &str,
        scale: Option<&Bound<'_, PyAny>>,
    ) -> PyResult<PyTime> {
        let scale: PyTimeScale =
            scale.map_or(Ok(PyTimeScale::default()), |scale| scale.try_into())?;
        let time = Time::from_iso(scale.0, iso).map_err(PyTimeError)?;
        Ok(PyTime(time))
    }

    /// Create a Time from raw seconds and subsecond components.
    ///
    /// This is a low-level constructor for maximum precision.
    ///
    /// Args:
    ///     scale: Time scale for the resulting Time object.
    ///     seconds: Integer seconds since the internal epoch.
    ///     subsecond: Fractional second component (0.0 to 1.0).
    ///
    /// Returns:
    ///     A new Time object.
    ///
    /// Raises:
    ///     ValueError: If subsecond is not in the valid range.
    #[classmethod]
    pub fn from_seconds(
        _cls: &Bound<'_, PyType>,
        scale: &Bound<'_, PyAny>,
        seconds: i64,
        subsecond: f64,
    ) -> PyResult<PyTime> {
        let scale: PyTimeScale = scale.try_into()?;
        let subsecond =
            Subsecond::from_f64(subsecond).ok_or(PyValueError::new_err("invalid subsecond"))?;
        let time = Time::new(scale.0, seconds, subsecond);
        Ok(PyTime(time))
    }

    /// Return the integer seconds component of the internal representation.
    ///
    /// Returns:
    ///     Integer seconds since the internal epoch.
    ///
    /// Raises:
    ///     NonFiniteTimeError: If the time is non-finite.
    pub fn seconds(&self) -> PyResult<i64> {
        self.0.seconds().ok_or(NonFiniteTimeError::new_err(
            "cannot access seconds for non-finite time",
        ))
    }

    /// Return the subsecond (fractional second) component.
    ///
    /// Returns:
    ///     Fractional seconds (0.0 to 1.0).
    ///
    /// Raises:
    ///     NonFiniteTimeError: If the time is non-finite.
    pub fn subsecond(&self) -> PyResult<f64> {
        self.0.subsecond().ok_or(NonFiniteTimeError::new_err(
            "cannot access subsecond for non-finite time",
        ))
    }

    #[classattr]
    const __hash__: Option<Py<PyAny>> = None;

    /// Returns the human-readable string representation of the `Time`.
    pub fn __str__(&self) -> String {
        self.0.to_string()
    }

    /// Returns the developer representation of the `Time`.
    pub fn __repr__(&self) -> String {
        format!(
            "Time(\"{}\", {}, {}, {}, {}, {}, {})",
            self.scale().abbreviation(),
            self.0.year(),
            self.0.month(),
            self.0.day(),
            self.0.hour(),
            self.0.minute(),
            self.0.as_seconds_f64(),
        )
    }

    /// Returns the `Time` advanced by a `TimeDelta`.
    pub fn __add__(&self, delta: PyTimeDelta) -> Self {
        PyTime(self.0 + delta.0)
    }

    /// Returns the `Time` or `TimeDelta` resulting from subtracting a `Time` or `TimeDelta`.
    pub fn __sub__<'py>(
        &self,
        py: Python<'py>,
        rhs: &Bound<'py, PyAny>,
    ) -> PyResult<Bound<'py, PyAny>> {
        if let Ok(delta) = rhs.extract::<PyTimeDelta>() {
            Ok(Bound::new(py, PyTime(self.0 - delta.0))?.into_any())
        } else if let Ok(rhs) = rhs.extract::<PyTime>() {
            if self.scale() != rhs.scale() {
                return Err(PyValueError::new_err(
                    "cannot subtract `Time` objects with different time scales",
                ));
            }
            Ok(Bound::new(py, PyTimeDelta(self.0 - rhs.0))?.into_any())
        } else {
            Err(PyTypeError::new_err(
                "`rhs` must be either a `Time` or a `TimeDelta` object",
            ))
        }
    }

    fn __richcmp__(&self, other: PyTime, op: CompareOp) -> PyResult<bool> {
        let ordering = self.0.checked_cmp(&other.0).map_err(PyTimeScaleMismatch)?;
        Ok(op.matches(ordering))
    }

    /// Check if two Time objects are approximately equal.
    ///
    /// Args:
    ///     rhs: The other Time object to compare.
    ///     rel_tol: Relative tolerance. Defaults to 1e-8.
    ///     abs_tol: Absolute tolerance. Defaults to 1e-14.
    ///
    /// Returns:
    ///     True if the times are approximately equal within the tolerances.
    ///
    /// Raises:
    ///     ValueError: If the Time objects have different time scales.
    #[pyo3(signature = (rhs, rel_tol = 1e-8, abs_tol = 1e-14))]
    pub fn isclose(&self, rhs: PyTime, rel_tol: f64, abs_tol: f64) -> PyResult<bool> {
        if self.scale() != rhs.scale() {
            return Err(PyValueError::new_err(
                "cannot compare `Time` objects with different time scales",
            ));
        }
        Ok(approx_eq!(self, &rhs, rtol <= rel_tol, atol <= abs_tol))
    }

    /// Return the Julian date relative to the specified epoch.
    ///
    /// Args:
    ///     epoch: Reference epoch ("jd", "mjd", "j1950", "j2000"). Defaults to "jd".
    ///     unit: Output unit ("seconds", "days", "centuries"). Defaults to "days".
    ///
    /// Returns:
    ///     The Julian date in the specified units relative to the epoch.
    ///
    /// Raises:
    ///     ValueError: If epoch or unit is invalid.
    #[pyo3(signature = (epoch = "jd", unit = "days"))]
    pub fn julian_date(&self, epoch: &str, unit: &str) -> PyResult<f64> {
        let epoch: PyEpoch = epoch.parse()?;
        let unit: PyUnit = unit.parse()?;
        Ok(self.0.julian_date(epoch.0, unit.0))
    }

    /// Return the two-part Julian date for maximum precision.
    ///
    /// Returns:
    ///     A tuple of (jd1, jd2) where the Julian date is jd1 + jd2.
    pub fn two_part_julian_date(&self) -> (f64, f64) {
        self.0.two_part_julian_date()
    }

    /// Return the time scale of this Time object.
    ///
    /// Returns:
    ///     The TimeScale of this Time.
    pub fn scale(&self) -> PyTimeScale {
        PyTimeScale(self.0.scale())
    }

    /// Return the year component.
    pub fn year(&self) -> i64 {
        self.0.year()
    }

    /// Return the month component (1-12).
    pub fn month(&self) -> u8 {
        self.0.month()
    }

    /// Return the day of month component (1-31).
    pub fn day(&self) -> u8 {
        self.0.day()
    }

    /// Return the day of year (1-366).
    pub fn day_of_year(&self) -> u16 {
        self.0.day_of_year()
    }

    /// Return the hour component (0-23).
    pub fn hour(&self) -> u8 {
        self.0.hour()
    }

    /// Return the minute component (0-59).
    pub fn minute(&self) -> u8 {
        self.0.minute()
    }

    /// Return the integer second component (0-59, or 60 for leap second).
    pub fn second(&self) -> u8 {
        self.0.second()
    }

    /// Return the millisecond component (0-999).
    pub fn millisecond(&self) -> u32 {
        self.0.millisecond()
    }

    /// Return the microsecond component (0-999).
    pub fn microsecond(&self) -> u32 {
        self.0.microsecond()
    }

    /// Return the nanosecond component (0-999).
    pub fn nanosecond(&self) -> u32 {
        self.0.nanosecond()
    }

    /// Return the picosecond component (0-999).
    pub fn picosecond(&self) -> u32 {
        self.0.picosecond()
    }

    /// Return the femtosecond component (0-999).
    pub fn femtosecond(&self) -> u32 {
        self.0.femtosecond()
    }

    /// Return the decimal seconds (seconds + fractional part).
    pub fn decimal_seconds(&self) -> f64 {
        self.0.as_seconds_f64()
    }

    /// Convert this Time to another time scale.
    ///
    /// Args:
    ///     scale: Target time scale.
    ///     provider: EOP provider for UT1 conversions. Required when converting
    ///         to/from UT1.
    ///
    /// Returns:
    ///     A new Time object in the target scale.
    ///
    /// Raises:
    ///     ValueError: If conversion requires EOP data but no provider is given.
    ///
    /// Examples:
    ///     >>> t_tai = Time("TAI", 2024, 1, 1)
    ///     >>> t_tt = t_tai.to_scale("TT")
    #[pyo3(signature = (scale, provider=None))]
    pub fn to_scale(
        &self,
        scale: &Bound<'_, PyAny>,
        provider: Option<&Bound<'_, PyEopProvider>>,
    ) -> PyResult<PyTime> {
        let scale: PyTimeScale = scale.try_into()?;
        let provider = provider.map(|p| &p.get().0);
        let time = match provider {
            Some(provider) => self
                .0
                .try_to_scale(scale.0, provider)
                .map_err(PyEopProviderError)?,
            None => self.0.to_scale(scale.0),
        };
        Ok(PyTime(time))
    }

    /// Convert this Time to UTC.
    ///
    /// Args:
    ///     provider: EOP provider for UT1 conversions.
    ///
    /// Returns:
    ///     A UTC object representing this instant in UTC.
    ///
    /// Raises:
    ///     ValueError: If the time is outside the valid UTC range.
    #[pyo3(signature = (provider=None))]
    pub fn to_utc(&self, provider: Option<&Bound<'_, PyEopProvider>>) -> PyResult<PyUtc> {
        let provider = provider.map(|p| &p.get().0);
        let utc = match provider {
            Some(provider) => self
                .0
                .try_to_scale(Tai, provider)
                .map_err(PyEopProviderError)?,
            None => self.0.to_scale(Tai),
        }
        .to_utc();
        Ok(PyUtc(utc))
    }
}

impl ToDelta for PyTime {
    fn to_delta(&self) -> TimeDelta {
        self.0.to_delta()
    }
}

impl JulianDate for PyTime {
    fn julian_date(&self, epoch: Epoch, unit: Unit) -> f64 {
        self.0.julian_date(epoch, unit)
    }
}

impl Add<TimeDelta> for PyTime {
    type Output = PyTime;

    fn add(self, rhs: TimeDelta) -> Self::Output {
        PyTime(self.0 + rhs)
    }
}

impl Sub<TimeDelta> for PyTime {
    type Output = PyTime;

    fn sub(self, rhs: TimeDelta) -> Self::Output {
        PyTime(self.0 - rhs)
    }
}

impl Sub<PyTime> for PyTime {
    type Output = TimeDelta;

    fn sub(self, rhs: PyTime) -> TimeDelta {
        self.0 - rhs.0
    }
}

impl CalendarDate for PyTime {
    fn date(&self) -> Date {
        self.0.date()
    }
}

impl CivilTime for PyTime {
    fn time(&self) -> TimeOfDay {
        self.0.time()
    }
}