Skip to main content

stkcraft_time/
contract.rs

1//! Explicit contracts for SPICE-compatible geometry and scientific time.
2//!
3//! [`TimeContext::new`] always selects NAIF ET. Scientific TDB requires
4//! [`ScientificContext`], and its result cannot implicitly become [`NaifEt`].
5//! Existing low-level conversion functions retain their behavior.
6//!
7//! ```compile_fail
8//! use stkcraft_time::contract::{NaifEt, ScientificContext};
9//! use stkcraft_time::Epoch;
10//! fn query_spice_geometry(_: NaifEt) {}
11//! let scientific = ScientificContext::new().to_tdb(Epoch::from_parts(0, 0)).unwrap();
12//! query_spice_geometry(scientific); // Different models require an explicit decision.
13//! ```
14
15use core::fmt;
16
17use crate::calendar::{calendar_to_jdn, Calendar, J2000_JDN};
18use crate::convert;
19use crate::dtdb::{dtdb_minus_tt_at_observer, DtdbError};
20use crate::leap::{LeapSecondPolicy, LeapSecondSource, LeapSecondTable, JDN_1972};
21use crate::{naif, Epoch, TimeError, UtcDateTime};
22
23mod naif_utc;
24pub use naif_utc::{NaifDeltet, NaifUtcContext};
25
26/// Calculation convention. Science is never selected by the default context.
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub enum CalculationProfile {
29    /// NAIF LSK-based ET for SPICE geometry.
30    #[default]
31    NaifSpice,
32    /// Explicit SOFA/ERFA scientific approximation, with TT realized by TAI.
33    IauScientific,
34}
35
36/// Checked-contract failures, separate from legacy low-level API errors.
37#[derive(Debug)]
38#[non_exhaustive]
39pub enum ContractError {
40    /// Civil time or kernel coverage error.
41    Time(TimeError),
42    /// Scientific model domain or observer input error.
43    Scientific(DtdbError),
44    /// Numeric input or evaluated output is not finite.
45    NonFinite,
46    /// A continuous epoch cannot be represented by [`Epoch`].
47    EpochOutOfRange,
48    /// Historical SOFA UTC is a separate convention from this NAIF contract.
49    HistoricalUtcRequiresExplicitModel,
50    /// The raw N0067 Julian UTC path requires an unmodified kernel policy.
51    NaifKernelModelRequired,
52    /// N0067 TTRANS rejects a non-increasing paired TAI leap table.
53    InvalidNaifLeapSeconds,
54}
55
56impl From<TimeError> for ContractError {
57    fn from(value: TimeError) -> Self {
58        Self::Time(value)
59    }
60}
61
62impl From<DtdbError> for ContractError {
63    fn from(value: DtdbError) -> Self {
64        Self::Scientific(value)
65    }
66}
67
68impl fmt::Display for ContractError {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        match self {
71            Self::Time(error) => error.fmt(f),
72            Self::Scientific(error) => error.fmt(f),
73            Self::NonFinite => f.write_str("time contract requires finite inputs and outputs"),
74            Self::EpochOutOfRange => f.write_str("time contract epoch is out of range"),
75            Self::HistoricalUtcRequiresExplicitModel => {
76                f.write_str("historical UTC requires the explicit SOFA conversion API")
77            }
78            Self::NaifKernelModelRequired => {
79                f.write_str("native Julian UTC requires an IERS-only, table-driven LSK model")
80            }
81            Self::InvalidNaifLeapSeconds => f.write_str("SPICE(BADLEAPSECONDS)"),
82        }
83    }
84}
85
86#[cfg(feature = "std")]
87impl std::error::Error for ContractError {}
88
89/// Finite NAIF ET, TDB seconds past `2000-01-01T12:00:00 TDB`.
90///
91/// This type does not by itself guarantee any SPK's coverage or physical
92/// accuracy. [`Self::seconds`] is the explicit boundary to legacy SPICE APIs.
93#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
94pub struct NaifEt(f64);
95
96/// Formal Julian UTC returned by N0067 TTRANS's explicitly selected model.
97///
98/// Before the first LSK entry this uses native's constant-offset convention,
99/// not physically realized historical UTC. During a positive leap second
100/// the formal value stands still. It cannot implicitly become ET:
101///
102/// ```compile_fail
103/// use stkcraft_time::contract::{NaifEt, NaifJulianUtc};
104/// fn geometry_epoch(_: NaifEt) {}
105/// fn wrong_scale(value: NaifJulianUtc) { geometry_epoch(value); }
106/// ```
107#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
108pub struct NaifJulianUtc(f64);
109
110impl NaifJulianUtc {
111    /// Unrounded native Julian days, for an explicitly chosen JDUTC consumer.
112    pub fn days(self) -> f64 {
113        self.0
114    }
115}
116
117impl NaifEt {
118    /// Accepts an explicitly declared ET input, rejecting NaN/infinity.
119    pub fn from_seconds(seconds: f64) -> Result<Self, ContractError> {
120        if seconds.is_finite() {
121            Ok(Self(seconds))
122        } else {
123            Err(ContractError::NonFinite)
124        }
125    }
126    /// TDB seconds past J2000, for a SPICE-compatible geometry interface.
127    pub fn seconds(self) -> f64 {
128        self.0
129    }
130    /// The calculation convention carried by this type.
131    pub fn profile(self) -> CalculationProfile {
132        CalculationProfile::NaifSpice
133    }
134}
135
136/// Scientific model used to obtain an [`IauTdb`] result.
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub enum ScientificModel {
139    /// Fairhead-Bretagnon geocentric model, as in ERFA with u=v=0.
140    GeocentricFairheadBretagnon,
141    /// The geocentric model plus ERFA observer-dependent diurnal terms.
142    ObserverFairheadBretagnon,
143}
144
145/// Explicit scientific TDB seconds past J2000 on the TDB scale.
146///
147/// There is deliberately no `From<IauTdb>` implementation for [`NaifEt`].
148#[derive(Clone, Copy, Debug, PartialEq)]
149pub struct IauTdb {
150    seconds: f64,
151    model: ScientificModel,
152}
153
154impl IauTdb {
155    /// TDB coordinate seconds; not an implicit NAIF ET conversion.
156    pub fn seconds(self) -> f64 {
157        self.seconds
158    }
159    /// Scientific model chosen explicitly by the caller.
160    pub fn model(self) -> ScientificModel {
161        self.model
162    }
163    /// Scientific convention; it never changes the default geometry context.
164    pub fn profile(self) -> CalculationProfile {
165        CalculationProfile::IauScientific
166    }
167}
168
169/// Relevant LSK settings for reproducibility. These are not file identity.
170#[derive(Clone, Copy, Debug, PartialEq)]
171pub struct NaifMetadata {
172    /// First and last leap-entry dates. The last is not an expiry date.
173    pub leap_entry_dates: (i64, i64),
174    /// Historical source selected in the supplied table.
175    pub leap_source: LeapSecondSource,
176    /// Explicit future leap policy selected in the supplied table.
177    pub leap_policy: LeapSecondPolicy,
178    /// LSK values in order DELTA_T_A, K, EB, M0, M1.
179    pub deltet: [f64; 5],
180}
181
182/// Default geometry time contract. The caller selects the LSK explicitly.
183#[derive(Clone, Copy)]
184pub struct TimeContext<'a> {
185    lsk: &'a LeapSecondTable,
186}
187
188impl<'a> TimeContext<'a> {
189    /// Selects NAIF ET, with no scientific-model fallback.
190    pub fn new(lsk: &'a LeapSecondTable) -> Self {
191        Self { lsk }
192    }
193    /// Native TTRANS ET-to-JDUTC, including its historical LSK convention.
194    ///
195    /// This explicit path bypasses integer Epoch and civil-calendar
196    /// quantization. It requires IERS-only/TableDriven kernel settings;
197    /// scientific SOFA and frozen future policies are separate choices.
198    /// N0067 uses the first 140 entries, holds a formal JD during positive
199    /// leap seconds, and assumes the first offset minus one before its
200    /// first entry. This is not a scientific historical UTC realization.
201    /// Existing `et_to_utc` retains its post-1972 coverage contract.
202    pub fn et_to_spice_julian_utc(self, et: NaifEt) -> Result<NaifJulianUtc, ContractError> {
203        if self.lsk.source() != LeapSecondSource::IersOnly
204            || self.lsk.policy() != LeapSecondPolicy::TableDriven
205        {
206            return Err(ContractError::NaifKernelModelRequired);
207        }
208        NaifUtcContext::from_raw_parts(
209            self.lsk.entries(),
210            NaifDeltet {
211                delta_t_a: self.lsk.delta_t_a,
212                k: self.lsk.k,
213                eb: self.lsk.eb,
214                m0: self.lsk.m0,
215                m1: self.lsk.m1,
216            },
217        )?
218        .et_to_spice_julian_utc(et)
219    }
220    /// The default calculation convention.
221    pub fn profile(self) -> CalculationProfile {
222        CalculationProfile::NaifSpice
223    }
224    /// Settings to record alongside the caller's source URL and file hash.
225    pub fn metadata(self) -> NaifMetadata {
226        NaifMetadata {
227            leap_entry_dates: self.lsk.coverage(),
228            leap_source: self.lsk.source(),
229            leap_policy: self.lsk.policy(),
230            deltet: [
231                self.lsk.delta_t_a,
232                self.lsk.k,
233                self.lsk.eb,
234                self.lsk.m0,
235                self.lsk.m1,
236            ],
237        }
238    }
239    /// Converts a continuous TAI epoch to checked, model-specific ET.
240    pub fn to_et(self, epoch: Epoch) -> Result<NaifEt, ContractError> {
241        let tai = (epoch.sec() as i128 - 43_200) as f64 + epoch.nanos() as f64 * 1e-9;
242        self.tai_seconds_to_et(tai)
243    }
244
245    // NAIF N0067 UNITIM evaluates the forward periodic term at TDT.
246    // Preserve its operation order; the low-level legacy fixed point is
247    // retained independently for existing callers. See ATTRIBUTION.md.
248    fn tai_seconds_to_et(self, tai: f64) -> Result<NaifEt, ContractError> {
249        let tt = tai + self.lsk.delta_t_a;
250        NaifEt::from_seconds(naif::tt_to_et(tt, self.lsk))
251    }
252    /// Converts validated civil UTC to NAIF ET. Historical SOFA UTC stays
253    /// in the explicit low-level SOFA API rather than changing this contract.
254    pub fn utc_to_et(self, utc: &UtcDateTime, calendar: Calendar) -> Result<NaifEt, ContractError> {
255        let jdn = calendar_to_jdn(utc.year, utc.month, utc.day, calendar)?;
256        if jdn < JDN_1972 {
257            return Err(ContractError::HistoricalUtcRequiresExplicitModel);
258        }
259        // Validate the civil label and LSK support, including removed seconds.
260        convert::utc_to_tai(utc, calendar, self.lsk)?;
261        // TTRANS keeps a pair of anchors (day-before/day-of) per LSK entry.
262        // Its intermediate rounding is observable for fractional UTC inputs.
263        // Do not replace this with a large absolute Epoch converted to f64.
264        let mut previous_delta = self.lsk.entries()[0].delta_at as i64 - 1;
265        let mut anchor = None;
266        for (index, entry) in self.lsk.entries().iter().enumerate() {
267            if !self.lsk.is_active_index(index) {
268                break;
269            }
270            let formal = (entry.jdn as i128 - J2000_JDN as i128) * 86400 - 43200;
271            if entry.jdn - 1 <= jdn {
272                let tai = i64::try_from(formal - 86400 + previous_delta as i128)
273                    .map_err(|_| ContractError::EpochOutOfRange)?;
274                anchor = Some((entry.jdn - 1, tai));
275            }
276            if entry.jdn <= jdn {
277                let tai = i64::try_from(formal + entry.delta_at as i128)
278                    .map_err(|_| ContractError::EpochOutOfRange)?;
279                anchor = Some((entry.jdn, tai));
280            }
281            previous_delta = entry.delta_at as i64;
282        }
283        let (day, tai_anchor) = anchor.ok_or(TimeError::UtcOutOfRange)?;
284        let mut seconds = (utc.hour as i64 * 3600 + utc.minute as i64 * 60) as f64 + utc.second;
285        seconds += (jdn - day) as f64 * 86400.0;
286        self.tai_seconds_to_et(tai_anchor as f64 + seconds)
287    }
288    /// Checked inverse; finite ET may still exceed the integer epoch range.
289    pub fn to_epoch(self, et: NaifEt) -> Result<Epoch, ContractError> {
290        let tt = naif::et_to_tt(et.0, self.lsk);
291        let tai = (tt - self.lsk.delta_t_a) + 43_200.0;
292        if !tai.is_finite() {
293            return Err(ContractError::NonFinite);
294        }
295        Epoch::checked_from_tai_seconds(tai).ok_or(ContractError::EpochOutOfRange)
296    }
297    /// Converts NAIF ET to UTC under the same explicit LSK contract.
298    pub fn et_to_utc(self, et: NaifEt, calendar: Calendar) -> Result<UtcDateTime, ContractError> {
299        let epoch = self.to_epoch(et)?;
300        let jdn = convert::utc_jdn(epoch, self.lsk).ok_or(TimeError::UtcOutOfRange)?;
301        if jdn < JDN_1972 {
302            return Err(ContractError::HistoricalUtcRequiresExplicitModel);
303        }
304        if jdn > calendar_to_jdn(i32::MAX, 12, 31, calendar)? {
305            return Err(ContractError::EpochOutOfRange);
306        }
307        let utc = convert::tai_to_utc(epoch, calendar, self.lsk)?;
308        Ok(utc)
309    }
310}
311
312/// Explicit scientific time realized through TT(TAI), not TT(BIPM).
313///
314/// No LSK constants, observer location or UT1 measurements are inferred.
315#[derive(Clone, Copy, Debug, Default)]
316pub struct ScientificContext;
317
318impl ScientificContext {
319    /// Selects the scientific context explicitly.
320    pub fn new() -> Self {
321        Self
322    }
323    /// TT(TAI) seconds past J2000 TT, independent of LSK DELTET constants.
324    pub fn tt_seconds(self, epoch: Epoch) -> Result<f64, ContractError> {
325        let tt = Self::tt_epoch(epoch)?;
326        Ok((tt.sec() as i128 - 43_200) as f64 + tt.nanos() as f64 * 1e-9)
327    }
328
329    fn tt_epoch(epoch: Epoch) -> Result<Epoch, ContractError> {
330        epoch
331            .checked_add(crate::Duration::from_parts(32, 184_000_000))
332            .ok_or(ContractError::EpochOutOfRange)
333    }
334
335    fn tt_date(epoch: Epoch) -> Result<(f64, f64), ContractError> {
336        let tt = Self::tt_epoch(epoch)?;
337        let first = Epoch::from_parts((2_433_283 - 2_451_545) * 86400, 0);
338        let last = Epoch::from_parts((2_469_808 - 2_451_545) * 86400, 0);
339        if tt < first || tt > last {
340            return Err(ContractError::Scientific(DtdbError::OutsideModelRange));
341        }
342        let days = tt.sec().div_euclid(86400);
343        let seconds = tt.sec().rem_euclid(86400) as f64 + tt.nanos() as f64 * 1e-9;
344        Ok((2_451_544.5 + days as f64, seconds / 86400.0))
345    }
346    /// Geocentric scientific TDB, checked against the model's stated date domain.
347    pub fn to_tdb(self, epoch: Epoch) -> Result<IauTdb, ContractError> {
348        let tt = self.tt_seconds(epoch)?;
349        let (jd1, jd2) = Self::tt_date(epoch)?;
350        let delta = dtdb_minus_tt_at_observer(jd1, jd2, 0.0, 0.0, 0.0, 0.0)?;
351        Ok(IauTdb {
352            seconds: tt + delta,
353            model: ScientificModel::GeocentricFairheadBretagnon,
354        })
355    }
356    /// Observer-dependent model. UT1 fraction is in [0,1), longitude is
357    /// east-positive radians, and u/v are cylindrical distances in km.
358    /// This is not a spacecraft proper-time conversion or Earth-frame solver.
359    pub fn to_tdb_at_observer(
360        self,
361        epoch: Epoch,
362        ut1_fraction: f64,
363        longitude: f64,
364        u_km: f64,
365        v_km: f64,
366    ) -> Result<IauTdb, ContractError> {
367        let tt = self.tt_seconds(epoch)?;
368        let (jd1, jd2) = Self::tt_date(epoch)?;
369        let delta = dtdb_minus_tt_at_observer(jd1, jd2, ut1_fraction, longitude, u_km, v_km)?;
370        Ok(IauTdb {
371            seconds: tt + delta,
372            model: ScientificModel::ObserverFairheadBretagnon,
373        })
374    }
375}