hifitime 4.3.0

Ultra-precise date and time handling in Rust for scientific applications with leap second support
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
/*
* Hifitime
* Copyright (C) 2017-onward Christopher Rabotin <christopher.rabotin@gmail.com> et al. (cf. https://github.com/nyx-space/hifitime/graphs/contributors)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Documentation: https://nyxspace.com/
*/

use super::{Duration, Epoch};

use core::fmt;

#[cfg(not(feature = "std"))]
#[allow(unused_imports)] // Import is indeed used.
use num_traits::Float;

#[cfg(feature = "python")]
use pyo3::prelude::*;

/*

NOTE: This is taken from itertools: https://docs.rs/itertools-num/0.1.3/src/itertools_num/linspace.rs.html#78-93 .

*/

/// An iterator of a sequence of evenly spaced Epochs.
///
/// (Python documentation hints)
/// :type start: Epoch
/// :type end: Epoch
/// :type step: Duration
/// :type inclusive: bool
#[cfg_attr(kani, derive(kani::Arbitrary))]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "python", pyclass)]
#[cfg_attr(feature = "python", pyo3(module = "hifitime"))]
pub struct TimeSeries {
    start: Epoch,
    duration: Duration,
    step: Duration,
    cur: i64,
    incl: bool,
}

impl TimeSeries {
    /// Return an iterator of evenly spaced Epochs, **inclusive** on start and **exclusive** on end.
    /// ```
    /// use hifitime::{Epoch, Unit, TimeSeries};
    /// let start = Epoch::from_gregorian_utc_at_midnight(2017, 1, 14);
    /// let end = Epoch::from_gregorian_utc_at_noon(2017, 1, 14);
    /// let step = Unit::Hour * 2;
    /// let time_series = TimeSeries::exclusive(start, end, step);
    /// let mut cnt = 0;
    /// for epoch in time_series {
    ///     println!("{}", epoch);
    ///     cnt += 1
    /// }
    /// assert_eq!(cnt, 6)
    /// ```
    #[inline]
    pub fn exclusive(start: Epoch, end: Epoch, step: Duration) -> TimeSeries {
        // Start one step prior to start because next() just moves forward
        Self {
            start,
            duration: end - start,
            step,
            cur: 0,
            incl: false,
        }
    }

    /// Returns first [Epoch] of this [TimeSeries], without consuming
    /// the iterator.
    #[inline]
    pub fn first_epoch(&self) -> Epoch {
        self.start
    }

    /// Returns last [Epoch] of this [TimeSeries], without consuming
    /// the iterator.
    #[inline]
    pub fn last_epoch(&self) -> Epoch {
        let mut epoch = self.start + self.duration;
        if !self.incl {
            // remove one step
            epoch -= self.step;
        }
        epoch
    }

    /// Return an iterator of evenly spaced Epochs, inclusive on start **and** on end.
    /// ```
    /// use hifitime::{Epoch, Unit, TimeSeries};
    /// let start = Epoch::from_gregorian_utc_at_midnight(2017, 1, 14);
    /// let end = Epoch::from_gregorian_utc_at_noon(2017, 1, 14);
    /// let step = Unit::Hour * 2;
    /// let time_series = TimeSeries::inclusive(start, end, step);
    /// let mut cnt = 0;
    /// for epoch in time_series {
    ///     println!("{}", epoch);
    ///     cnt += 1
    /// }
    /// assert_eq!(cnt, 7)
    /// ```
    #[inline]
    pub fn inclusive(start: Epoch, end: Epoch, step: Duration) -> TimeSeries {
        // Start one step prior to start because next() just moves forward
        Self {
            start,
            duration: end - start,
            step,
            cur: 0,
            incl: true,
        }
    }
}

impl fmt::Display for TimeSeries {
    // Prints this duration with automatic selection of the units, i.e. everything that isn't zero is ignored
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "TimeSeries [{} : {} : {}]",
            self.start,
            if self.incl {
                self.start + self.duration
            } else {
                self.start + self.duration - self.step
            },
            self.step
        )
    }
}

impl fmt::LowerHex for TimeSeries {
    /// Prints the Epoch in TAI
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "TimeSeries [{:x} : {:x} : {}]",
            self.start,
            if self.incl {
                self.start + self.duration
            } else {
                self.start + self.duration - self.step
            },
            self.step
        )
    }
}

impl fmt::UpperHex for TimeSeries {
    /// Prints the Epoch in TT
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "TimeSeries [{:X} : {:X} : {}]",
            self.start,
            if self.incl {
                self.start + self.duration
            } else {
                self.start + self.duration - self.step
            },
            self.step
        )
    }
}

impl fmt::LowerExp for TimeSeries {
    /// Prints the Epoch in TDB
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "TimeSeries [{:e} : {:e} : {}]",
            self.start,
            if self.incl {
                self.start + self.duration
            } else {
                self.start + self.duration - self.step
            },
            self.step
        )
    }
}

impl fmt::UpperExp for TimeSeries {
    /// Prints the Epoch in ET
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "TimeSeries [{:E} : {:E} : {}]",
            self.start,
            if self.incl {
                self.start + self.duration
            } else {
                self.start + self.duration - self.step
            },
            self.step
        )
    }
}

impl fmt::Pointer for TimeSeries {
    /// Prints the Epoch in UNIX
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "TimeSeries [{:p} : {:p} : {}]",
            self.start,
            if self.incl {
                self.start + self.duration
            } else {
                self.start + self.duration - self.step
            },
            self.step
        )
    }
}

impl fmt::Octal for TimeSeries {
    /// Prints the Epoch in GPS
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "TimeSeries [{:o} : {:o} : {}]",
            self.start,
            if self.incl {
                self.start + self.duration
            } else {
                self.start + self.duration - self.step
            },
            self.step
        )
    }
}

#[cfg(feature = "python")]
#[pymethods]
impl TimeSeries {
    #[new]
    /// Return an iterator of evenly spaced Epochs
    /// If inclusive is set to true, this iterator is inclusive on start **and** on end.
    /// If inclusive is set to false, only the start epoch is included in the iteration.
    fn new_py(start: Epoch, end: Epoch, step: Duration, inclusive: bool) -> Self {
        if inclusive {
            Self::inclusive(start, end, step)
        } else {
            Self::exclusive(start, end, step)
        }
    }

    fn __getnewargs__(&self) -> Result<(Epoch, Epoch, Duration, bool), PyErr> {
        Ok((self.start, self.start + self.duration, self.step, self.incl))
    }

    fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
        slf
    }

    fn __next__(mut slf: PyRefMut<'_, Self>) -> Option<Epoch> {
        slf.next()
    }

    fn __str__(&self) -> String {
        format!("{self}")
    }

    fn __repr__(&self) -> String {
        format!("{self:?} @ {self:p}")
    }

    #[cfg(feature = "python")]
    fn __eq__(&self, other: Self) -> bool {
        *self == other
    }
}

impl Iterator for TimeSeries {
    type Item = Epoch;

    #[inline]
    fn next(&mut self) -> Option<Epoch> {
        let next_offset = self.cur * self.step;
        if (!self.incl && next_offset >= self.duration)
            || (self.incl && next_offset > self.duration)
        {
            None
        } else {
            self.cur += 1;
            Some(self.start + next_offset)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.len(), Some(self.len() + 1))
    }
}

impl DoubleEndedIterator for TimeSeries {
    #[inline]
    fn next_back(&mut self) -> Option<Epoch> {
        // Offset from the end of the iterator
        self.cur += 1;
        let offset = self.cur * self.step;
        // if offset < -self.duration - self.step {
        if (!self.incl && offset > self.duration)
            || (self.incl && offset > self.duration + self.step)
        {
            None
        } else {
            Some(self.start + self.duration - offset)
        }
    }
}

impl ExactSizeIterator for TimeSeries
where
    TimeSeries: Iterator,
{
    fn len(&self) -> usize {
        let approx = (self.duration.to_seconds() / self.step.to_seconds()).abs();
        if self.incl {
            if approx.ceil() >= usize::MAX as f64 {
                usize::MAX
            } else {
                approx.ceil() as usize
            }
        } else if approx.floor() >= usize::MAX as f64 {
            usize::MAX
        } else {
            approx.floor() as usize
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{Epoch, TimeSeries, Unit};

    #[test]
    fn test_exclusive_timeseries() {
        let start = Epoch::from_gregorian_utc_at_midnight(2017, 1, 14);
        let end = Epoch::from_gregorian_utc_at_noon(2017, 1, 14);
        let step = Unit::Hour * 2;

        let mut count = 0;
        let time_series = TimeSeries::exclusive(start, end, step);

        assert_eq!(time_series.first_epoch(), start, "invalid first epoch");
        assert_eq!(time_series.last_epoch(), end - step, "invalid last epoch");

        for epoch in time_series {
            if count == 0 {
                assert_eq!(
                    epoch, start,
                    "Starting epoch of exclusive time series is wrong"
                );
            } else if count == 5 {
                assert_ne!(epoch, end, "Ending epoch of exclusive time series is wrong");
            }
            #[cfg(feature = "std")]
            println!("tests::exclusive_timeseries::{epoch}");
            count += 1;
        }

        assert_eq!(count, 6, "Should have five items in this iterator");
    }

    #[test]
    fn test_inclusive_timeseries() {
        let start = Epoch::from_gregorian_utc_at_midnight(2017, 1, 14);
        let end = Epoch::from_gregorian_utc_at_noon(2017, 1, 14);
        let step = Unit::Hour * 2;

        let mut count = 0;
        let time_series = TimeSeries::inclusive(start, end, step);

        assert_eq!(time_series.first_epoch(), start, "invalid first epoch");
        assert_eq!(time_series.last_epoch(), end, "invalid last epoch");

        for epoch in time_series {
            if count == 0 {
                assert_eq!(
                    epoch, start,
                    "Starting epoch of inclusive time series is wrong"
                );
            } else if count == 6 {
                assert_eq!(epoch, end, "Ending epoch of inclusive time series is wrong");
            }
            #[cfg(feature = "std")]
            println!("tests::inclusive_timeseries::{epoch}");
            count += 1;
        }

        assert_eq!(count, 7, "Should have six items in this iterator");
    }

    #[test]
    fn gh131_regression() {
        let start = Epoch::from_gregorian_utc(2022, 7, 14, 2, 56, 11, 228271007);
        let step = 0.5 * Unit::Microsecond;
        let steps = 1_000_000_000;
        let end = start + steps * step; // This is 500 ms later
        let times = TimeSeries::exclusive(start, end, step);
        // For an _exclusive_ time series, we skip the last item, so it's steps minus one
        assert_eq!(times.len(), steps as usize - 1);
        assert_eq!(times.len(), times.size_hint().0);

        // For an _inclusive_ time series, we skip the last item, so it's the steps count
        let times = TimeSeries::inclusive(start, end, step);
        assert_eq!(times.len(), steps as usize);
        assert_eq!(times.len(), times.size_hint().0);
    }

    #[test]
    fn ts_over_leap_second() {
        let start = Epoch::from_gregorian_utc(2016, 12, 31, 23, 59, 59, 0);
        let end = start + Unit::Second * 5;
        let step = Unit::Second * 1;

        let times = TimeSeries::exclusive(start, end, step);
        let expect_end = start + Unit::Second * 4;
        let mut cnt = 0;
        let mut cur_epoch = start;

        assert_eq!(times.first_epoch(), start, "invalid first epoch");
        assert_eq!(times.last_epoch(), end - step, "invalid last epoch");

        for epoch in times {
            cnt += 1;
            cur_epoch = epoch;
        }

        assert_eq!(cnt, 5); // Five because the first item is always inclusive
        assert_eq!(cur_epoch, expect_end, "incorrect last item in iterator");
    }

    #[test]
    fn ts_backward() {
        let start = Epoch::from_gregorian_utc(2015, 1, 1, 12, 0, 0, 0);
        let end = start + Unit::Second * 5;
        let step = Unit::Second * 1;
        let times = TimeSeries::exclusive(start, end, step);
        let mut cnt = 0;
        let mut cur_epoch = start;

        assert_eq!(times.first_epoch(), start, "invalid first epoch");
        assert_eq!(times.last_epoch(), end - step, "invalid last epoch");

        for epoch in times.rev() {
            cnt += 1;
            cur_epoch = epoch;
            let expect = start + Unit::Second * (5 - cnt);
            assert_eq!(expect, epoch, "incorrect item in iterator");
        }

        assert_eq!(cnt, 5); // Five because the first item is always inclusive
        assert_eq!(cur_epoch, start, "incorrect last item in iterator");
    }
}