"""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)))