1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub enum CalculationProfile {
29 #[default]
31 NaifSpice,
32 IauScientific,
34}
35
36#[derive(Debug)]
38#[non_exhaustive]
39pub enum ContractError {
40 Time(TimeError),
42 Scientific(DtdbError),
44 NonFinite,
46 EpochOutOfRange,
48 HistoricalUtcRequiresExplicitModel,
50 NaifKernelModelRequired,
52 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#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
94pub struct NaifEt(f64);
95
96#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
108pub struct NaifJulianUtc(f64);
109
110impl NaifJulianUtc {
111 pub fn days(self) -> f64 {
113 self.0
114 }
115}
116
117impl NaifEt {
118 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 pub fn seconds(self) -> f64 {
128 self.0
129 }
130 pub fn profile(self) -> CalculationProfile {
132 CalculationProfile::NaifSpice
133 }
134}
135
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub enum ScientificModel {
139 GeocentricFairheadBretagnon,
141 ObserverFairheadBretagnon,
143}
144
145#[derive(Clone, Copy, Debug, PartialEq)]
149pub struct IauTdb {
150 seconds: f64,
151 model: ScientificModel,
152}
153
154impl IauTdb {
155 pub fn seconds(self) -> f64 {
157 self.seconds
158 }
159 pub fn model(self) -> ScientificModel {
161 self.model
162 }
163 pub fn profile(self) -> CalculationProfile {
165 CalculationProfile::IauScientific
166 }
167}
168
169#[derive(Clone, Copy, Debug, PartialEq)]
171pub struct NaifMetadata {
172 pub leap_entry_dates: (i64, i64),
174 pub leap_source: LeapSecondSource,
176 pub leap_policy: LeapSecondPolicy,
178 pub deltet: [f64; 5],
180}
181
182#[derive(Clone, Copy)]
184pub struct TimeContext<'a> {
185 lsk: &'a LeapSecondTable,
186}
187
188impl<'a> TimeContext<'a> {
189 pub fn new(lsk: &'a LeapSecondTable) -> Self {
191 Self { lsk }
192 }
193 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 pub fn profile(self) -> CalculationProfile {
222 CalculationProfile::NaifSpice
223 }
224 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 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 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 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 convert::utc_to_tai(utc, calendar, self.lsk)?;
261 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 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 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#[derive(Clone, Copy, Debug, Default)]
316pub struct ScientificContext;
317
318impl ScientificContext {
319 pub fn new() -> Self {
321 Self
322 }
323 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 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 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}