forked from IMAP-Science-Operations-Center/imap_processing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime.py
More file actions
469 lines (377 loc) · 14.3 KB
/
time.py
File metadata and controls
469 lines (377 loc) · 14.3 KB
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
"""Time conversion functions that rely on SPICEYPY."""
import typing
from collections.abc import Collection, Iterable
from datetime import datetime
import numpy as np
import numpy.typing as npt
import spiceypy
from imap_processing.spice import IMAP_SC_ID
TICK_DURATION = 2e-5 # 20 microseconds as defined in imap_sclk_0000.tsc
# Hard code the J2000 epoch. This allows for CDF epoch to be converted without
# use of SPICE though it should be noted that this results in a 5-second error
# due to the occurrence of 5 leap-seconds since the J2000 epoch.
# TODO: Implement a function for converting CDF epoch to UTC correctly.
# see github ticket #1208
# The UTC string was generated by:
# >>> spiceypy.et2utc(spiceypy.unitim(0, "TT", "ET"), "ISOC", 9)
TTJ2000_EPOCH = np.datetime64("2000-01-01T11:58:55.816", "ns")
@typing.no_type_check
def _vectorize(pyfunc: typing.Callable, **vectorize_kwargs) -> typing.Callable:
"""
Convert 0-D arrays from numpy.vectorize to scalars.
For details on numpy.vectorize, see
https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html
Parameters
----------
pyfunc : callable
A python function or method.
**vectorize_kwargs :
Keyword arguments to pass to numpy.vectorize.
Returns
-------
out : callable
A vectorized function.
"""
vectorized_func = np.vectorize(pyfunc, **vectorize_kwargs)
def wrapper(*args, **kwargs): # numpydoc ignore=GL08
# Calling the vectorized function with [()] will convert 0-D arrays
# to scalars
return vectorized_func(*args, **kwargs)[()]
return wrapper
def met_to_sclkticks(met: npt.ArrayLike) -> npt.NDArray[float]:
"""
Convert Mission Elapsed Time (MET) to floating point spacecraft clock ticks.
Parameters
----------
met : float, numpy.ndarray
Number of seconds since epoch according to the spacecraft clock.
Returns
-------
numpy.ndarray[float]
The mission elapsed time converted to nanoseconds since the J2000 epoch.
"""
return np.asarray(met, dtype=float) / TICK_DURATION
def met_to_ttj2000ns(
met: npt.ArrayLike,
) -> npt.NDArray[np.int64]:
"""
Convert mission elapsed time (MET) to terrestrial time nanoseconds since J2000.
Parameters
----------
met : float, numpy.ndarray
Number of seconds since epoch according to the spacecraft clock.
Returns
-------
numpy.ndarray[numpy.int64]
The mission elapsed time converted to nanoseconds since the J2000 epoch
in the terrestrial time (TT) timescale.
Notes
-----
There are two options when using SPICE to convert from SCLK time (MET) to
J2000. The conversion can be done on SCLK strings as input or using double
precision continuous spacecraft clock "ticks". The latter is more accurate
as it will correctly convert fractional clock ticks to nanoseconds. Since
some IMAP instruments contain clocks with higher precision than 1 SCLK
"tick" which is defined to be 20 microseconds, according to the sclk kernel,
it is preferable to use the higher accuracy method.
"""
sclk_ticks = met_to_sclkticks(met)
return np.asarray(sct_to_ttj2000s(sclk_ticks) * 1e9, dtype=np.int64)
@typing.no_type_check
def ttj2000ns_to_et(tt_ns: npt.ArrayLike) -> npt.NDArray[float]:
"""
Convert TT J2000 epoch nanoseconds to TDB J2000 epoch seconds.
The common CDF coordinate `epoch` stores terrestrial time (TT) J2000
nanoseconds. SPICE requires Barycentric Dynamical Time (TDB, aka ET) J2000
floating point seconds for most geometry related functions. This is a common
function to do that conversion.
Parameters
----------
tt_ns : float, numpy.ndarray
Number of nanoseconds since the J2000 epoch in the TT timescale.
Returns
-------
numpy.ndarray[float]
Number of seconds since the J2000 epoch in the TDB timescale.
"""
tt_seconds = np.asarray(tt_ns, dtype=np.float64) / 1e9
vectorized_unitim = _vectorize(
spiceypy.unitim, otypes=[float], excluded=["insys", "outsys"]
)
return vectorized_unitim(tt_seconds, "TT", "ET")
@typing.no_type_check
def et_to_ttj2000ns(et: npt.ArrayLike) -> npt.NDArray[float]:
"""
Convert TDB J2000 epoch seconds to TT J2000 epoch nanoseconds.
Opposite of `ttj2000ns_to_et`.
Parameters
----------
et : float, numpy.ndarray
Number of seconds since the J2000 epoch in the TDB timescale.
Returns
-------
numpy.ndarray[float]
Number of nanoseconds since the J2000 epoch in the TT timescale.
"""
vectorized_unitim = _vectorize(
spiceypy.unitim, otypes=[float], excluded=["insys", "outsys"]
)
tt_s = vectorized_unitim(et, "ET", "TT")
tt_ns = np.asarray(tt_s, dtype=np.float64) * 1e9
return tt_ns
@typing.no_type_check
def met_to_utc(met: npt.ArrayLike, precision: int = 9) -> npt.NDArray[str]:
"""
Convert mission elapsed time (MET) to UTC.
Parameters
----------
met : float, numpy.ndarray
Number of seconds since epoch according to the spacecraft clock.
precision : int
The number of digits of precision to which fractional seconds
are to be computed.
Returns
-------
numpy.ndarray[str]
The mission elapsed time converted to UTC string. The UTC string(s)
returned will be of the form '1987-04-12T16:31:12.814' with the
fractional seconds precision as specified by the precision keyword.
"""
sclk_ticks = met_to_sclkticks(met)
et = sct_to_et(sclk_ticks)
return spiceypy.et2utc(et, "ISOC", prec=precision)
def met_to_datetime64(
met: npt.ArrayLike,
) -> np.datetime64 | npt.NDArray[np.datetime64]:
"""
Convert mission elapsed time (MET) to datetime.datetime.
Parameters
----------
met : float, numpy.ndarray
Number of seconds since epoch according to the spacecraft clock.
Returns
-------
numpy.ndarray[str]
The mission elapsed time converted to UTC string.
"""
return np.array(met_to_utc(met), dtype=np.datetime64)[()]
def et_to_datetime64(
et: npt.ArrayLike,
) -> np.datetime64 | npt.NDArray[np.datetime64]:
"""
Convert ET to numpy datetime64.
Parameters
----------
et : float, numpy.ndarray
Number of seconds since the J2000 epoch in the TDB timescale.
Returns
-------
numpy.ndarray[str]
The mission elapsed time converted to numpy.datetime64.
"""
return np.array(et_to_utc(et), dtype=np.datetime64)[()]
@typing.no_type_check
def et_to_met(
et: float | Collection[float],
) -> float | np.ndarray:
"""
Convert ephemeris time to mission elapsed time (MET).
This function converts ET to spacecraft clock ticks and then to MET seconds.
This is the inverse of the MET to ET conversion process.
Parameters
----------
et : Union[float, Collection[float]]
Input ephemeris time value(s) to be converted to MET.
Returns
-------
met: np.ndarray
Mission elapsed time in seconds.
"""
vectorized_sce2c = _vectorize(spiceypy.sce2c, otypes=[float], excluded=[0])
sclk_ticks = vectorized_sce2c(IMAP_SC_ID, et)
met = np.asarray(sclk_ticks, dtype=float) * TICK_DURATION
return met
def ttj2000ns_to_met(
tt_ns: npt.ArrayLike,
) -> npt.NDArray[float]:
"""
Convert terrestrial time nanoseconds since J2000 to mission elapsed time (MET).
This is the inverse of met_to_ttj2000ns. The conversion process is:
TTJ2000ns -> ET -> MET
Parameters
----------
tt_ns : float, numpy.ndarray
Number of nanoseconds since the J2000 epoch in the TT timescale.
Returns
-------
numpy.ndarray[float]
The mission elapsed time in seconds.
"""
et = ttj2000ns_to_et(tt_ns)
met = et_to_met(et)
return met
@typing.no_type_check
def sct_to_et(
sclk_ticks: float | Collection[float],
) -> float | np.ndarray:
"""
Convert encoded spacecraft clock "ticks" to ephemeris time.
Decorated wrapper for spiceypy.sct2e that vectorizes the function in addition
to wrapping with the @ensure_spice automatic kernel furnishing functionality.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sct2e_c.html
Parameters
----------
sclk_ticks : Union[float, Collection[float]]
Input sclk ticks value(s) to be converted to ephemeris time.
Returns
-------
ephemeris_time: np.ndarray
Ephemeris time, seconds past J2000.
"""
vectorized_sct2e = _vectorize(spiceypy.sct2e, otypes=[float], excluded=[0])
return vectorized_sct2e(IMAP_SC_ID, sclk_ticks)
@typing.no_type_check
def sct_to_ttj2000s(
sclk_ticks: float | Iterable[float],
) -> float | np.ndarray:
"""
Convert encoded spacecraft clock "ticks" to terrestrial time (TT).
Decorated wrapper for chained spiceypy functions `unitim(sct2e(), "ET", "TT")`
that vectorizes the functions in addition to wrapping with the @ensure_spice
automatic kernel furnishing functionality.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sct2e_c.html
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/unitim_c.html
Parameters
----------
sclk_ticks : Union[float, Iterable[float]]
Input sclk ticks value(s) to be converted to ephemeris time.
Returns
-------
terrestrial_time: np.ndarray[float]
Terrestrial time, seconds past J2000.
"""
def conversion(sclk_ticks): # numpydoc ignore=GL08
return spiceypy.unitim(spiceypy.sct2e(IMAP_SC_ID, sclk_ticks), "ET", "TT")
vectorized_func = _vectorize(conversion, otypes=[float])
return vectorized_func(sclk_ticks)
@typing.no_type_check
def str_to_et(
time_str: str | Iterable[str],
) -> float | np.ndarray:
"""
Convert string to ephemeris time.
Decorated wrapper for spiceypy.str2et that vectorizes the function in addition
to wrapping with the @ensure_spice automatic kernel furnishing functionality.
https://spiceypy.readthedocs.io/en/main/documentation.html#spiceypy.spiceypy.str2et
Parameters
----------
time_str : str or Iterable[str]
Input string(s) to be converted to ephemeris time.
Returns
-------
ephemeris_time: np.ndarray
Ephemeris time, seconds past J2000.
"""
vectorized_str2et = _vectorize(spiceypy.str2et, otypes=[float])
return vectorized_str2et(time_str)
@typing.no_type_check
def et_to_utc(
et: float | Iterable[float],
format_str: str = "ISOC",
precision: int = 3,
utclen: int = 24,
) -> str | np.ndarray:
"""
Convert ephemeris time to UTC.
Decorated wrapper for spiceypy.et2utc that vectorizes the function in addition
to wrapping with the @ensure_spice automatic kernel furnishing functionality.
https://spiceypy.readthedocs.io/en/main/documentation.html#spiceypy.spiceypy.et2utc
Parameters
----------
et : float or Iterable[float]
Input ephemeris time(s) to be converted to UTC.
format_str : str
Format of the output time string. Default is "ISOC". All options:
"C" Calendar format, UTC.
"D" Day-of-Year format, UTC.
"J" Julian Date format, UTC.
"ISOC" ISO Calendar format, UTC.
"ISOD" ISO Day-of-Year format, UTC.
precision : int
Digits of precision in fractional seconds or days. Default is 3.
utclen : int
The length of the output string. Default is 24 (to accommodate the
"YYYY-MM-DDT00:00:00.000" format + 1). From the NAIF docs: if the output string
is expected to have `x` characters, utclen` must be x + 1.
Returns
-------
utc_time : str or np.ndarray
UTC time(s).
"""
return spiceypy.et2utc(et, format_str, precision, utclen)
def epoch_to_doy(epoch: np.ndarray) -> npt.NDArray:
"""
Convert epoch times to day of year (1-365/366).
Parameters
----------
epoch : xarray.DataArray
Time, number of nanoseconds since J2000 with leap seconds included.
Returns
-------
day_of_year : numpy.ndarray
Day of year (1-365/366) for each epoch value.
"""
et = ttj2000ns_to_et(epoch.data)
# Get UTC time strings in ISO calendar format
time_strings = et_to_utc(et, "ISOC")
# Extract DOY from datetime
return np.array(
[datetime.fromisoformat(date).timetuple().tm_yday for date in time_strings]
)
def epoch_to_fractional_doy(epoch: int | Iterable[int]) -> float | np.ndarray:
"""
Convert epoch in TTJ2000ns to floating point day-of-year.
Uses SPICE's timout function to directly extract day of year and # codespell:ignore
time components, avoiding intermediate datetime parsing.
Parameters
----------
epoch : int or Iterable[int]
Epoch in TTJ2000ns format (nanoseconds since J2000). Can be a single
integer or an iterable of integers.
Returns
-------
doy : float or numpy.ndarray
Floating point day of year (1.0 = Jan 1 00:00:00). Returns a scalar
when `epoch` is a single integer, or a NumPy array when `epoch` is an
iterable.
References
----------
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/timout_c.html
"""
# Convert to ephemeris time (ET/TDB)
et = ttj2000ns_to_et(epoch)
def single_et_to_fractional_doy(et: float) -> float: # numpydoc ignore=GL08
# Use SPICE timout to extract DOY and time components # codespell:ignore
# Format: "DOY.####" with ::UTC modifier for UTC-based output
# The ::UTC modifier converts ET to UTC but doesn't appear in output
return float(spiceypy.timout(et, "DOY.#### ::UTC", 30)) # codespell:ignore
vectorized_et_to_frac_doy = _vectorize(single_et_to_fractional_doy, otypes=[float])
return vectorized_et_to_frac_doy(et)
def str_yyyymmdd_to_ttj2000ns(date_str: str) -> np.int64:
"""
Convert a YYYYMMDD date string to TTJ2000 nanoseconds.
Parameters
----------
date_str : str
The date string in YYYYMMDD format.
Returns
-------
int
The corresponding time in TTJ2000 nanoseconds.
"""
if len(date_str) != 8:
raise ValueError(
f"Date {date_str} must be 8 characters long in yyyymmdd format."
)
date_string = datetime.strptime(date_str, "%Y%m%d").strftime("%Y-%m-%dT00:00:00")
return np.int64(et_to_ttj2000ns(str_to_et(date_string)))