-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
mod.rs
1461 lines (1282 loc) · 57.3 KB
/
mod.rs
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Hifitime, part of the Nyx Space tools
* Copyright (C) 2023 Christopher Rabotin <[email protected]> et al. (cf. https://github.com/nyx-space/hifitime/graphs/contributors)
* This Source Code Form is subject to the terms of the Apache
* v. 2.0. If a copy of the Apache License was not distributed with this
* file, You can obtain one at https://www.apache.org/licenses/LICENSE-2.0.
*
* Documentation: https://nyxspace.com/
*/
mod formatting;
mod gregorian;
mod ops;
mod with_funcs;
#[cfg(feature = "std")]
mod leap_seconds_file;
#[cfg(feature = "std")]
mod system_time;
#[cfg(kani)]
mod kani_verif;
#[cfg(feature = "ut1")]
pub mod ut1;
pub mod leap_seconds;
use crate::duration::{Duration, Unit};
use crate::efmt::format::Format;
use crate::errors::{DurationError, ParseSnafu};
use crate::leap_seconds::{LatestLeapSeconds, LeapSecondProvider};
use crate::Weekday;
use crate::{
EpochError, MonthName, TimeScale, TimeUnits, BDT_REF_EPOCH, ET_EPOCH_S, GPST_REF_EPOCH,
GST_REF_EPOCH, MJD_J1900, MJD_OFFSET, NANOSECONDS_PER_DAY, QZSST_REF_EPOCH, UNIX_REF_EPOCH,
};
use core::cmp::Eq;
use core::str::FromStr;
pub use gregorian::is_gregorian_valid;
use snafu::ResultExt;
#[cfg(not(kani))]
use crate::ParsingError;
#[cfg(kani)]
use kani::assert;
#[cfg(feature = "python")]
mod python;
#[cfg(feature = "python")]
use pyo3::prelude::*;
#[cfg(not(kani))]
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(not(feature = "std"))]
#[allow(unused_imports)] // Import is indeed used.
use num_traits::Float;
pub(crate) const TT_OFFSET_MS: i64 = 32_184;
pub(crate) const ET_OFFSET_US: i64 = 32_184_935;
/// NAIF leap second kernel data for M_0 used to calculate the mean anomaly of the heliocentric orbit of the Earth-Moon barycenter.
pub const NAIF_M0: f64 = 6.239996;
/// NAIF leap second kernel data for M_1 used to calculate the mean anomaly of the heliocentric orbit of the Earth-Moon barycenter.
pub const NAIF_M1: f64 = 1.99096871e-7;
/// NAIF leap second kernel data for EB used to calculate the eccentric anomaly of the heliocentric orbit of the Earth-Moon barycenter.
pub const NAIF_EB: f64 = 1.671e-2;
/// NAIF leap second kernel data used to calculate the difference between ET and TAI.
pub const NAIF_K: f64 = 1.657e-3;
/// Defines a nanosecond-precision Epoch.
///
/// Refer to the appropriate functions for initializing this Epoch from different time scales or representations.
#[derive(Copy, Clone, Default, Eq)]
#[repr(C)]
#[cfg_attr(feature = "python", pyclass)]
#[cfg_attr(feature = "python", pyo3(module = "hifitime"))]
pub struct Epoch {
/// An Epoch is always stored as the duration since the beginning of its time scale
pub duration: Duration,
/// Time scale used during the initialization of this Epoch.
pub time_scale: TimeScale,
}
#[cfg(not(kani))]
#[cfg(feature = "serde")]
impl Serialize for Epoch {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = self.to_string(); // Assuming `Display` is implemented for `Epoch`
serializer.serialize_str(&s)
}
}
#[cfg(not(kani))]
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Epoch {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Epoch::from_str(&s).map_err(serde::de::Error::custom)
}
}
// Defines the methods that should be classmethods in Python, but must be redefined as per https://github.com/PyO3/pyo3/issues/1003#issuecomment-844433346
impl Epoch {
#[must_use]
/// Converts self to another time scale, using the leap second provider for any conversion involving leap seconds
///
/// As per the [Rust naming convention](https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv),
/// this borrows an Epoch and returns an owned Epoch.
pub fn to_time_scale_with_leap_seconds<L: LeapSecondProvider>(
&self,
ts: TimeScale,
provider: &L,
) -> Self {
if ts == self.time_scale {
// Do nothing, just return a copy
*self
} else {
// Now we need to convert from the current time scale into the desired time scale.
// Let's first compute this epoch from its current time scale into TAI.
let prime_epoch_offset = match self.time_scale {
TimeScale::TAI => self.duration,
TimeScale::TT => self.duration - TT_OFFSET_MS.milliseconds(),
TimeScale::ET => {
// Run a Newton Raphston to convert find the correct value of the
let mut seconds_j2000 = self.duration.to_seconds();
for _ in 0..5 {
seconds_j2000 += -NAIF_K
* (NAIF_M0
+ NAIF_M1 * seconds_j2000
+ NAIF_EB * (NAIF_M0 + NAIF_M1 * seconds_j2000).sin())
.sin();
}
// At this point, we have a good estimate of the number of seconds of this epoch.
// Reverse the algorithm:
let delta_et_tai = Self::delta_et_tai(
seconds_j2000 - (TT_OFFSET_MS * Unit::Millisecond).to_seconds(),
);
// Match SPICE by changing the UTC definition.
self.duration - delta_et_tai.seconds() + self.time_scale.prime_epoch_offset()
}
TimeScale::TDB => {
let gamma = Self::inner_g(self.duration.to_seconds());
let delta_tdb_tai = gamma * Unit::Second + TT_OFFSET_MS * Unit::Millisecond;
// Offset back to J1900.
self.duration - delta_tdb_tai + self.time_scale.prime_epoch_offset()
}
TimeScale::UTC => {
// Assume this is TAI
let mut tai_assumption = *self;
tai_assumption.time_scale = TimeScale::TAI;
self.duration
+ tai_assumption
.leap_seconds_with(true, provider)
.unwrap_or(0.0)
.seconds()
}
TimeScale::GPST => self.duration + GPST_REF_EPOCH.to_tai_duration(),
TimeScale::GST => self.duration + GST_REF_EPOCH.to_tai_duration(),
TimeScale::BDT => self.duration + BDT_REF_EPOCH.to_tai_duration(),
TimeScale::QZSST => self.duration + QZSST_REF_EPOCH.to_tai_duration(),
};
// Convert to the desired time scale from the TAI duration
let ts_ref_offset = match ts {
TimeScale::TAI => prime_epoch_offset,
TimeScale::TT => prime_epoch_offset + TT_OFFSET_MS.milliseconds(),
TimeScale::ET => {
// Run a Newton Raphston to convert find the correct value of the ... ?!
let mut seconds = (prime_epoch_offset - ts.prime_epoch_offset()).to_seconds();
for _ in 0..5 {
seconds -= -NAIF_K
* (NAIF_M0
+ NAIF_M1 * seconds
+ NAIF_EB * (NAIF_M0 + NAIF_M1 * seconds).sin())
.sin();
}
// At this point, we have a good estimate of the number of seconds of this epoch.
// Reverse the algorithm:
let delta_et_tai = Self::delta_et_tai(
seconds + (TT_OFFSET_MS * Unit::Millisecond).to_seconds(),
);
// Match SPICE by changing the UTC definition.
prime_epoch_offset + delta_et_tai.seconds() - ts.prime_epoch_offset()
}
TimeScale::TDB => {
// Iterate to convert find the correct value of the
let mut seconds = (prime_epoch_offset - ts.prime_epoch_offset()).to_seconds();
let mut delta = 1e8; // Arbitrary large number, greater than first step of Newton Raphson.
for _ in 0..5 {
let next = seconds - Self::inner_g(seconds);
let new_delta = (next - seconds).abs();
if (new_delta - delta).abs() < 1e-9 {
break;
}
seconds = next; // Loop
delta = new_delta;
}
// At this point, we have a good estimate of the number of seconds of this epoch.
// Reverse the algorithm:
let gamma =
Self::inner_g(seconds + (TT_OFFSET_MS * Unit::Millisecond).to_seconds());
let delta_tdb_tai = gamma.seconds() + TT_OFFSET_MS.milliseconds();
prime_epoch_offset + delta_tdb_tai - ts.prime_epoch_offset()
}
TimeScale::UTC => {
let original_offset_s = prime_epoch_offset.to_seconds();
let mut corrected_offset = original_offset_s * Unit::Second;
for leap_second in provider.entries().iter().rev() {
let maybe_corrected_offset_s = original_offset_s - leap_second.delta_at;
if original_offset_s >= leap_second.timestamp_tai_s {
corrected_offset = maybe_corrected_offset_s * Unit::Second;
break;
}
}
corrected_offset
// // Assume it's TAI for the sake of calculation
// let epoch = Self {
// duration: prime_epoch_offset,
// time_scale: TimeScale::TAI,
// };
// // TAI = UTC + leap_seconds <=> UTC = TAI - leap_seconds
// prime_epoch_offset
// - epoch
// .leap_seconds_with(true, provider)
// .unwrap_or(0.0)
// .seconds()
}
TimeScale::GPST => prime_epoch_offset - GPST_REF_EPOCH.to_tai_duration(),
TimeScale::GST => prime_epoch_offset - GST_REF_EPOCH.to_tai_duration(),
TimeScale::BDT => prime_epoch_offset - BDT_REF_EPOCH.to_tai_duration(),
TimeScale::QZSST => prime_epoch_offset - QZSST_REF_EPOCH.to_tai_duration(),
};
Self {
duration: ts_ref_offset,
time_scale: ts,
}
}
}
#[must_use]
/// Converts self to another time scale
///
/// Note that this is a shortcut to to_time_scale_with_leap_seconds with the LatestLeapSeconds.
/// As per the [Rust naming convention](https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv),
/// this borrows an Epoch and returns an owned Epoch.
pub fn to_time_scale(&self, ts: TimeScale) -> Self {
self.to_time_scale_with_leap_seconds(ts, &LatestLeapSeconds::default())
}
#[must_use]
/// Creates a new Epoch from a Duration as the time difference between this epoch and TAI reference epoch.
pub const fn from_tai_duration(duration: Duration) -> Self {
Self {
duration,
time_scale: TimeScale::TAI,
}
}
/// Get the accumulated number of leap seconds up to this Epoch from the provided LeapSecondProvider.
/// Returns None if the epoch is before 1960, year at which UTC was defined.
///
/// # Why does this function return an `Option` when the other returns a value
/// This is to match the `iauDat` function of SOFA (src/dat.c). That function will return a warning and give up if the start date is before 1960.
pub fn leap_seconds_with<L: LeapSecondProvider>(
&self,
iers_only: bool,
provider: &L,
) -> Option<f64> {
for leap_second in provider.entries().iter().rev() {
if self.to_tai_duration().to_seconds() >= leap_second.timestamp_tai_s
&& (!iers_only || leap_second.announced_by_iers)
{
return Some(leap_second.delta_at);
}
}
None
}
/// Creates an epoch from given duration expressed in given timescale, i.e. since the given time scale's reference epoch.
///
/// For example, if the duration is 1 day and the time scale is Ephemeris Time, then this will create an epoch of 2000-01-02 at midnight ET. If the duration is 1 day and the time scale is TAI, this will create an epoch of 1900-01-02 at noon, because the TAI reference epoch in Hifitime is chosen to be the J1900 epoch.
/// In case of ET, TDB Timescales, a duration since J2000 is expected.
#[must_use]
pub const fn from_duration(duration: Duration, ts: TimeScale) -> Self {
Self {
duration,
time_scale: ts,
}
}
pub fn to_duration_since_j1900(&self) -> Duration {
self.to_time_scale(TimeScale::TAI).duration
}
#[must_use]
/// Creates a new Epoch from its centuries and nanosecond since the TAI reference epoch.
pub fn from_tai_parts(centuries: i16, nanoseconds: u64) -> Self {
Self::from_tai_duration(Duration::from_parts(centuries, nanoseconds))
}
#[must_use]
/// Initialize an Epoch from the provided TAI seconds since 1900 January 01 at midnight
pub fn from_tai_seconds(seconds: f64) -> Self {
assert!(
seconds.is_finite(),
"Attempted to initialize Epoch with non finite number"
);
Self::from_tai_duration(seconds * Unit::Second)
}
#[must_use]
/// Initialize an Epoch from the provided TAI days since 1900 January 01 at midnight
pub fn from_tai_days(days: f64) -> Self {
assert!(
days.is_finite(),
"Attempted to initialize Epoch with non finite number"
);
Self::from_tai_duration(days * Unit::Day)
}
#[must_use]
/// Initialize an Epoch from the provided UTC seconds since 1900 January 01 at midnight
pub fn from_utc_duration(duration: Duration) -> Self {
Self::from_duration(duration, TimeScale::UTC)
}
#[must_use]
/// Initialize an Epoch from the provided UTC seconds since 1900 January 01 at midnight
pub fn from_utc_seconds(seconds: f64) -> Self {
Self::from_utc_duration(seconds * Unit::Second)
}
#[must_use]
/// Initialize an Epoch from the provided UTC days since 1900 January 01 at midnight
pub fn from_utc_days(days: f64) -> Self {
Self::from_utc_duration(days * Unit::Day)
}
#[must_use]
/// Initialize an Epoch from the provided duration since 1980 January 6 at midnight
pub fn from_gpst_duration(duration: Duration) -> Self {
Self::from_duration(duration, TimeScale::GPST)
}
#[must_use]
/// Initialize an Epoch from the provided duration since 1980 January 6 at midnight
pub fn from_qzsst_duration(duration: Duration) -> Self {
Self::from_duration(duration, TimeScale::QZSST)
}
#[must_use]
/// Initialize an Epoch from the provided duration since August 21st 1999 midnight
pub fn from_gst_duration(duration: Duration) -> Self {
Self::from_duration(duration, TimeScale::GST)
}
#[must_use]
/// Initialize an Epoch from the provided duration since January 1st midnight
pub fn from_bdt_duration(duration: Duration) -> Self {
Self::from_duration(duration, TimeScale::BDT)
}
#[must_use]
pub fn from_mjd_tai(days: f64) -> Self {
assert!(
days.is_finite(),
"Attempted to initialize Epoch with non finite number"
);
Self::from_tai_duration((days - MJD_J1900) * Unit::Day)
}
fn from_mjd_in_time_scale(days: f64, time_scale: TimeScale) -> Self {
// always refer to TAI/mjd
let mut e = Self::from_mjd_tai(days);
if time_scale.uses_leap_seconds() {
e.duration += e.leap_seconds(true).unwrap_or(0.0) * Unit::Second;
}
e.time_scale = time_scale;
e
}
#[must_use]
pub fn from_mjd_utc(days: f64) -> Self {
Self::from_mjd_in_time_scale(days, TimeScale::UTC)
}
#[must_use]
pub fn from_mjd_gpst(days: f64) -> Self {
Self::from_mjd_in_time_scale(days, TimeScale::GPST)
}
#[must_use]
pub fn from_mjd_qzsst(days: f64) -> Self {
Self::from_mjd_in_time_scale(days, TimeScale::QZSST)
}
#[must_use]
pub fn from_mjd_gst(days: f64) -> Self {
Self::from_mjd_in_time_scale(days, TimeScale::GST)
}
#[must_use]
pub fn from_mjd_bdt(days: f64) -> Self {
Self::from_mjd_in_time_scale(days, TimeScale::BDT)
}
#[must_use]
pub fn from_jde_tai(days: f64) -> Self {
assert!(
days.is_finite(),
"Attempted to initialize Epoch with non finite number"
);
Self::from_tai_duration((days - MJD_J1900 - MJD_OFFSET) * Unit::Day)
}
fn from_jde_in_time_scale(days: f64, time_scale: TimeScale) -> Self {
// always refer to TAI/jde
let mut e = Self::from_jde_tai(days);
if time_scale.uses_leap_seconds() {
e.duration += e.leap_seconds(true).unwrap_or(0.0) * Unit::Second;
}
e.time_scale = time_scale;
e
}
#[must_use]
pub fn from_jde_utc(days: f64) -> Self {
Self::from_jde_in_time_scale(days, TimeScale::UTC)
}
#[must_use]
pub fn from_jde_gpst(days: f64) -> Self {
Self::from_jde_in_time_scale(days, TimeScale::GPST)
}
#[must_use]
pub fn from_jde_qzsst(days: f64) -> Self {
Self::from_jde_in_time_scale(days, TimeScale::QZSST)
}
#[must_use]
pub fn from_jde_gst(days: f64) -> Self {
Self::from_jde_in_time_scale(days, TimeScale::GST)
}
#[must_use]
pub fn from_jde_bdt(days: f64) -> Self {
Self::from_jde_in_time_scale(days, TimeScale::BDT)
}
#[must_use]
/// Initialize an Epoch from the provided TT seconds (approximated to 32.184s delta from TAI)
pub fn from_tt_seconds(seconds: f64) -> Self {
assert!(
seconds.is_finite(),
"Attempted to initialize Epoch with non finite number"
);
Self::from_tt_duration(seconds * Unit::Second)
}
#[must_use]
/// Initialize an Epoch from the provided TT seconds (approximated to 32.184s delta from TAI)
pub fn from_tt_duration(duration: Duration) -> Self {
Self::from_duration(duration, TimeScale::TT)
}
#[must_use]
/// Initialize an Epoch from the Ephemeris Time seconds past 2000 JAN 01 (J2000 reference)
pub fn from_et_seconds(seconds_since_j2000: f64) -> Epoch {
Self::from_et_duration(seconds_since_j2000 * Unit::Second)
}
/// Initializes an Epoch from the duration between J2000 and the current epoch as per NAIF SPICE.
///
/// # Limitation
/// This method uses a Newton Raphson iteration to find the appropriate TAI duration. This method is only accuracy to a few nanoseconds.
/// Hence, when calling `as_et_duration()` and re-initializing it with `from_et_duration` you may have a few nanoseconds of difference (expect less than 10 ns).
///
/// # Warning
/// The et2utc function of NAIF SPICE will assume that there are 9 leap seconds before 01 JAN 1972,
/// as this date introduces 10 leap seconds. At the time of writing, this does _not_ seem to be in
/// line with IERS and the documentation in the leap seconds list.
///
/// In order to match SPICE, the as_et_duration() function will manually get rid of that difference.
#[must_use]
pub fn from_et_duration(duration_since_j2000: Duration) -> Self {
Self::from_duration(duration_since_j2000, TimeScale::ET)
}
#[must_use]
/// Initialize an Epoch from Dynamic Barycentric Time (TDB) seconds past 2000 JAN 01 midnight (difference than SPICE)
/// NOTE: This uses the ESA algorithm, which is a notch more complicated than the SPICE algorithm, but more precise.
/// In fact, SPICE algorithm is precise +/- 30 microseconds for a century whereas ESA algorithm should be exactly correct.
pub fn from_tdb_seconds(seconds_j2000: f64) -> Epoch {
assert!(
seconds_j2000.is_finite(),
"Attempted to initialize Epoch with non finite number"
);
Self::from_tdb_duration(seconds_j2000 * Unit::Second)
}
#[must_use]
/// Initialize from Dynamic Barycentric Time (TDB) (same as SPICE ephemeris time) whose epoch is 2000 JAN 01 noon TAI.
pub fn from_tdb_duration(duration_since_j2000: Duration) -> Epoch {
Self::from_duration(duration_since_j2000, TimeScale::TDB)
}
#[must_use]
/// Initialize from the JDE days
pub fn from_jde_et(days: f64) -> Self {
assert!(
days.is_finite(),
"Attempted to initialize Epoch with non finite number"
);
Self::from_jde_tdb(days)
}
#[must_use]
/// Initialize from Dynamic Barycentric Time (TDB) (same as SPICE ephemeris time) in JD days
pub fn from_jde_tdb(days: f64) -> Self {
assert!(
days.is_finite(),
"Attempted to initialize Epoch with non finite number"
);
Self::from_jde_tai(days) - Unit::Microsecond * ET_OFFSET_US
}
#[must_use]
/// Initialize an Epoch from the number of seconds since the GPS Time Epoch,
/// defined as UTC midnight of January 5th to 6th 1980 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS#GPS_Time_.28GPST.29>).
pub fn from_gpst_seconds(seconds: f64) -> Self {
Self::from_duration(seconds * Unit::Second, TimeScale::GPST)
}
#[must_use]
/// Initialize an Epoch from the number of days since the GPS Time Epoch,
/// defined as UTC midnight of January 5th to 6th 1980 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS#GPS_Time_.28GPST.29>).
pub fn from_gpst_days(days: f64) -> Self {
Self::from_duration(days * Unit::Day, TimeScale::GPST)
}
#[must_use]
/// Initialize an Epoch from the number of nanoseconds since the GPS Time Epoch,
/// defined as UTC midnight of January 5th to 6th 1980 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS#GPS_Time_.28GPST.29>).
/// This may be useful for time keeping devices that use GPS as a time source.
pub fn from_gpst_nanoseconds(nanoseconds: u64) -> Self {
Self::from_duration(nanoseconds as f64 * Unit::Nanosecond, TimeScale::GPST)
}
#[must_use]
/// Initialize an Epoch from the number of seconds since the QZSS Time Epoch,
/// defined as UTC midnight of January 5th to 6th 1980 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS#GPS_Time_.28GPST.29>).
pub fn from_qzsst_seconds(seconds: f64) -> Self {
Self::from_duration(seconds * Unit::Second, TimeScale::QZSST)
}
#[must_use]
/// Initialize an Epoch from the number of days since the QZSS Time Epoch,
/// defined as UTC midnight of January 5th to 6th 1980 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS#GPS_Time_.28GPST.29>).
pub fn from_qzsst_days(days: f64) -> Self {
Self::from_duration(days * Unit::Day, TimeScale::QZSST)
}
#[must_use]
/// Initialize an Epoch from the number of nanoseconds since the QZSS Time Epoch,
/// defined as UTC midnight of January 5th to 6th 1980 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS#GPS_Time_.28GPST.29>).
/// This may be useful for time keeping devices that use QZSS as a time source.
pub fn from_qzsst_nanoseconds(nanoseconds: u64) -> Self {
Self::from_duration(
Duration {
centuries: 0,
nanoseconds,
},
TimeScale::QZSST,
)
}
#[must_use]
/// Initialize an Epoch from the number of seconds since the GST Time Epoch,
/// starting August 21st 1999 midnight (UTC)
/// (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS>).
pub fn from_gst_seconds(seconds: f64) -> Self {
Self::from_duration(seconds * Unit::Second, TimeScale::GST)
}
#[must_use]
/// Initialize an Epoch from the number of days since the GST Time Epoch,
/// starting August 21st 1999 midnight (UTC)
/// (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS>)
pub fn from_gst_days(days: f64) -> Self {
Self::from_duration(days * Unit::Day, TimeScale::GST)
}
#[must_use]
/// Initialize an Epoch from the number of nanoseconds since the GPS Time Epoch,
/// starting August 21st 1999 midnight (UTC)
/// (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS>)
pub fn from_gst_nanoseconds(nanoseconds: u64) -> Self {
Self::from_duration(
Duration {
centuries: 0,
nanoseconds,
},
TimeScale::GST,
)
}
#[must_use]
/// Initialize an Epoch from the number of seconds since the BDT Time Epoch,
/// starting on January 1st 2006 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS>)
pub fn from_bdt_seconds(seconds: f64) -> Self {
Self::from_duration(seconds * Unit::Second, TimeScale::BDT)
}
#[must_use]
/// Initialize an Epoch from the number of days since the BDT Time Epoch,
/// starting on January 1st 2006 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS>)
pub fn from_bdt_days(days: f64) -> Self {
Self::from_duration(days * Unit::Day, TimeScale::BDT)
}
#[must_use]
/// Initialize an Epoch from the number of nanoseconds since the BDT Time Epoch,
/// starting on January 1st 2006 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS>).
/// This may be useful for time keeping devices that use BDT as a time source.
pub fn from_bdt_nanoseconds(nanoseconds: u64) -> Self {
Self::from_duration(
Duration {
centuries: 0,
nanoseconds,
},
TimeScale::BDT,
)
}
#[must_use]
/// Initialize an Epoch from the provided duration since UTC midnight 1970 January 01.
pub fn from_unix_duration(duration: Duration) -> Self {
Self::from_utc_duration(UNIX_REF_EPOCH.to_utc_duration() + duration)
}
#[must_use]
/// Initialize an Epoch from the provided UNIX second timestamp since UTC midnight 1970 January 01.
pub fn from_unix_seconds(seconds: f64) -> Self {
Self::from_utc_duration(UNIX_REF_EPOCH.to_utc_duration() + seconds * Unit::Second)
}
#[must_use]
/// Initialize an Epoch from the provided UNIX millisecond timestamp since UTC midnight 1970 January 01.
pub fn from_unix_milliseconds(millisecond: f64) -> Self {
Self::from_utc_duration(UNIX_REF_EPOCH.to_utc_duration() + millisecond * Unit::Millisecond)
}
/// Initializes an Epoch from the provided Format.
pub fn from_str_with_format(s_in: &str, format: Format) -> Result<Self, EpochError> {
format.parse(s_in)
}
/// Initializes an Epoch from the Format as a string.
pub fn from_format_str(s_in: &str, format_str: &str) -> Result<Self, EpochError> {
Format::from_str(format_str)
.with_context(|_| ParseSnafu {
details: "when using format string",
})?
.parse(s_in)
}
fn delta_et_tai(seconds: f64) -> f64 {
// Calculate M, the mean anomaly.4
let m = NAIF_M0 + seconds * NAIF_M1;
// Calculate eccentric anomaly
let e = m + NAIF_EB * m.sin();
(TT_OFFSET_MS * Unit::Millisecond).to_seconds() + NAIF_K * e.sin()
}
fn inner_g(seconds: f64) -> f64 {
use core::f64::consts::TAU;
let g = TAU / 360.0 * 357.528 + 1.990_910_018_065_731e-7 * seconds;
// Return gamma
1.658e-3 * (g + 1.67e-2 * g.sin()).sin()
}
/// Builds an Epoch from given `week`: elapsed weeks counter into the desired Time scale, and the amount of nanoseconds within that week.
/// For example, this is how GPS vehicles describe a GPST epoch.
///
/// Note that this constructor relies on 128 bit integer math and may be slow on embedded devices.
#[must_use]
pub fn from_time_of_week(week: u32, nanoseconds: u64, time_scale: TimeScale) -> Self {
let mut nanos = i128::from(nanoseconds);
nanos += i128::from(week) * Weekday::DAYS_PER_WEEK_I128 * i128::from(NANOSECONDS_PER_DAY);
let duration = Duration::from_total_nanoseconds(nanos);
Self::from_duration(duration, time_scale)
}
#[must_use]
/// Builds a UTC Epoch from given `week`: elapsed weeks counter and "ns" amount of nanoseconds since closest Sunday Midnight.
pub fn from_time_of_week_utc(week: u32, nanoseconds: u64) -> Self {
Self::from_time_of_week(week, nanoseconds, TimeScale::UTC)
}
#[must_use]
/// Builds an Epoch from the provided year, days in the year, and a time scale.
///
/// # Limitations
/// In the TDB or ET time scales, there may be an error of up to 750 nanoseconds when initializing an Epoch this way.
/// This is because we first initialize the epoch in Gregorian scale and then apply the TDB/ET offset, but that offset actually depends on the precise time.
///
/// # Day couting behavior
///
/// The day counter starts at 01, in other words, 01 January is day 1 of the counter, as per the GPS specificiations.
///
pub fn from_day_of_year(year: i32, days: f64, time_scale: TimeScale) -> Self {
let start_of_year = Self::from_gregorian(year, 1, 1, 0, 0, 0, 0, time_scale);
start_of_year + (days - 1.0) * Unit::Day
}
}
#[cfg_attr(feature = "python", pymethods)]
impl Epoch {
#[must_use]
/// Get the accumulated number of leap seconds up to this Epoch accounting only for the IERS leap seconds.
pub fn leap_seconds_iers(&self) -> i32 {
match self.leap_seconds(true) {
Some(v) => v as i32,
None => 0,
}
}
/// Get the accumulated number of leap seconds up to this Epoch accounting only for the IERS leap seconds and the SOFA scaling from 1960 to 1972, depending on flag.
/// Returns None if the epoch is before 1960, year at which UTC was defined.
///
/// # Why does this function return an `Option` when the other returns a value
/// This is to match the `iauDat` function of SOFA (src/dat.c). That function will return a warning and give up if the start date is before 1960.
pub fn leap_seconds(&self, iers_only: bool) -> Option<f64> {
self.leap_seconds_with(iers_only, &LatestLeapSeconds::default())
}
#[cfg(feature = "std")]
#[must_use]
/// The standard ISO format of this epoch (six digits of subseconds) in the _current_ time scale, refer to <https://docs.rs/hifitime/latest/hifitime/efmt/format/struct.Format.html> for format options.
pub fn to_isoformat(&self) -> String {
use crate::efmt::consts::ISO8601_STD;
use crate::efmt::Formatter;
format!("{}", Formatter::new(*self, ISO8601_STD))[..26].to_string()
}
#[must_use]
/// Returns this epoch with respect to the provided time scale.
/// This is needed to correctly perform duration conversions in dynamical time scales (e.g. TDB).
pub fn to_duration_in_time_scale(&self, ts: TimeScale) -> Duration {
self.to_time_scale(ts).duration
}
/// Attempts to return the number of nanoseconds since the reference epoch of the provided time scale.
/// This will return an overflow error if more than one century has past since the reference epoch in the provided time scale.
/// If this is _not_ an issue, you should use `epoch.to_duration_in_time_scale().to_parts()` to retrieve both the centuries and the nanoseconds
/// in that century.
#[allow(clippy::wrong_self_convention)]
fn to_nanoseconds_in_time_scale(&self, time_scale: TimeScale) -> Result<u64, EpochError> {
let (centuries, nanoseconds) = self.to_duration_in_time_scale(time_scale).to_parts();
if centuries != 0 {
Err(EpochError::Duration {
source: DurationError::Overflow,
})
} else {
Ok(nanoseconds)
}
}
#[must_use]
/// Returns the number of TAI seconds since J1900
pub fn to_tai_seconds(&self) -> f64 {
self.to_tai_duration().to_seconds()
}
#[must_use]
/// Returns this time in a Duration past J1900 counted in TAI
pub fn to_tai_duration(&self) -> Duration {
self.to_time_scale(TimeScale::TAI).duration
}
#[must_use]
/// Returns the epoch as a floating point value in the provided unit
pub fn to_tai(&self, unit: Unit) -> f64 {
self.to_tai_duration().to_unit(unit)
}
#[must_use]
/// Returns the TAI parts of this duration
pub fn to_tai_parts(&self) -> (i16, u64) {
self.to_tai_duration().to_parts()
}
#[must_use]
/// Returns the number of days since J1900 in TAI
pub fn to_tai_days(&self) -> f64 {
self.to_tai(Unit::Day)
}
#[must_use]
/// Returns the number of UTC seconds since the TAI epoch
pub fn to_utc_seconds(&self) -> f64 {
self.to_utc(Unit::Second)
}
#[must_use]
/// Returns this time in a Duration past J1900 counted in UTC
pub fn to_utc_duration(&self) -> Duration {
self.to_time_scale(TimeScale::UTC).duration
}
#[must_use]
/// Returns the number of UTC seconds since the TAI epoch
pub fn to_utc(&self, unit: Unit) -> f64 {
self.to_utc_duration().to_unit(unit)
}
#[must_use]
/// Returns the number of UTC days since the TAI epoch
pub fn to_utc_days(&self) -> f64 {
self.to_utc(Unit::Day)
}
#[must_use]
/// `as_mjd_days` creates an Epoch from the provided Modified Julian Date in days as explained
/// [here](http://tycho.usno.navy.mil/mjd.html). MJD epoch is Modified Julian Day at 17 November 1858 at midnight.
pub fn to_mjd_tai_days(&self) -> f64 {
self.to_mjd_tai(Unit::Day)
}
#[must_use]
/// Returns the Modified Julian Date in seconds TAI.
pub fn to_mjd_tai_seconds(&self) -> f64 {
self.to_mjd_tai(Unit::Second)
}
#[must_use]
/// Returns this epoch as a duration in the requested units in MJD TAI
pub fn to_mjd_tai(&self, unit: Unit) -> f64 {
(self.to_tai_duration() + Unit::Day * MJD_J1900).to_unit(unit)
}
#[must_use]
/// Returns the Modified Julian Date in days UTC.
pub fn to_mjd_utc_days(&self) -> f64 {
self.to_mjd_utc(Unit::Day)
}
#[must_use]
/// Returns the Modified Julian Date in the provided unit in UTC.
pub fn to_mjd_utc(&self, unit: Unit) -> f64 {
(self.to_utc_duration() + Unit::Day * MJD_J1900).to_unit(unit)
}
#[must_use]
/// Returns the Modified Julian Date in seconds UTC.
pub fn to_mjd_utc_seconds(&self) -> f64 {
self.to_mjd_utc(Unit::Second)
}
#[must_use]
/// Returns the Julian days from epoch 01 Jan -4713, 12:00 (noon)
/// as explained in "Fundamentals of astrodynamics and applications", Vallado et al.
/// 4th edition, page 182, and on [Wikipedia](https://en.wikipedia.org/wiki/Julian_day).
pub fn to_jde_tai_days(&self) -> f64 {
self.to_jde_tai(Unit::Day)
}
#[must_use]
/// Returns the Julian Days from epoch 01 Jan -4713 12:00 (noon) in desired Duration::Unit
pub fn to_jde_tai(&self, unit: Unit) -> f64 {
self.to_jde_tai_duration().to_unit(unit)
}
#[must_use]
/// Returns the Julian Days from epoch 01 Jan -4713 12:00 (noon) as a Duration
pub fn to_jde_tai_duration(&self) -> Duration {
self.to_tai_duration() + Unit::Day * MJD_J1900 + Unit::Day * MJD_OFFSET
}
#[must_use]
/// Returns the Julian seconds in TAI.
pub fn to_jde_tai_seconds(&self) -> f64 {
self.to_jde_tai(Unit::Second)
}
#[must_use]
/// Returns the Julian days in UTC.
pub fn to_jde_utc_days(&self) -> f64 {
self.to_jde_utc_duration().to_unit(Unit::Day)
}
#[must_use]
/// Returns the Julian days in UTC as a `Duration`
pub fn to_jde_utc_duration(&self) -> Duration {
self.to_utc_duration() + Unit::Day * (MJD_J1900 + MJD_OFFSET)
}
#[must_use]
/// Returns the Julian Days in UTC seconds.
pub fn to_jde_utc_seconds(&self) -> f64 {
self.to_jde_utc_duration().to_seconds()
}
#[must_use]
/// Returns seconds past TAI epoch in Terrestrial Time (TT) (previously called Terrestrial Dynamical Time (TDT))
pub fn to_tt_seconds(&self) -> f64 {
self.to_tt_duration().to_seconds()
}
#[must_use]
/// Returns `Duration` past TAI epoch in Terrestrial Time (TT).
pub fn to_tt_duration(&self) -> Duration {
self.to_time_scale(TimeScale::TT).duration
}
#[must_use]
/// Returns days past TAI epoch in Terrestrial Time (TT) (previously called Terrestrial Dynamical Time (TDT))
pub fn to_tt_days(&self) -> f64 {
self.to_tt_duration().to_unit(Unit::Day)
}
#[must_use]
/// Returns the centuries passed J2000 TT
pub fn to_tt_centuries_j2k(&self) -> f64 {
(self.to_tt_duration() - Unit::Second * ET_EPOCH_S).to_unit(Unit::Century)
}
#[must_use]
/// Returns the duration past J2000 TT
pub fn to_tt_since_j2k(&self) -> Duration {
self.to_tt_duration() - Unit::Second * ET_EPOCH_S
}
#[must_use]
/// Returns days past Julian epoch in Terrestrial Time (TT) (previously called Terrestrial Dynamical Time (TDT))
pub fn to_jde_tt_days(&self) -> f64 {
self.to_jde_tt_duration().to_unit(Unit::Day)
}
#[must_use]
pub fn to_jde_tt_duration(&self) -> Duration {
self.to_tt_duration() + Unit::Day * (MJD_J1900 + MJD_OFFSET)
}
#[must_use]
/// Returns days past Modified Julian epoch in Terrestrial Time (TT) (previously called Terrestrial Dynamical Time (TDT))
pub fn to_mjd_tt_days(&self) -> f64 {
self.to_mjd_tt_duration().to_unit(Unit::Day)
}
#[must_use]
pub fn to_mjd_tt_duration(&self) -> Duration {
self.to_tt_duration() + Unit::Day * MJD_J1900
}
#[must_use]
/// Returns seconds past GPS Time Epoch, defined as UTC midnight of January 5th to 6th 1980 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS#GPS_Time_.28GPST.29>).
pub fn to_gpst_seconds(&self) -> f64 {
self.to_gpst_duration().to_seconds()
}
#[must_use]
/// Returns `Duration` past GPS time Epoch.
pub fn to_gpst_duration(&self) -> Duration {
self.to_time_scale(TimeScale::GPST).duration
}
/// Returns nanoseconds past GPS Time Epoch, defined as UTC midnight of January 5th to 6th 1980 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS#GPS_Time_.28GPST.29>).
/// NOTE: This function will return an error if the centuries past GPST time are not zero.
pub fn to_gpst_nanoseconds(&self) -> Result<u64, EpochError> {
self.to_nanoseconds_in_time_scale(TimeScale::GPST)
}
#[must_use]
/// Returns days past GPS Time Epoch, defined as UTC midnight of January 5th to 6th 1980 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS#GPS_Time_.28GPST.29>).
pub fn to_gpst_days(&self) -> f64 {
self.to_gpst_duration().to_unit(Unit::Day)
}
#[must_use]
/// Returns seconds past QZSS Time Epoch, defined as UTC midnight of January 5th to 6th 1980 (cf. <https://gssc.esa.int/navipedia/index.php/Time_References_in_GNSS#GPS_Time_.28GPST.29>).
pub fn to_qzsst_seconds(&self) -> f64 {
self.to_qzsst_duration().to_seconds()