SpiceManager#
- class SpiceManager#
Bases:
objectUnified interface to NASA SPICE via SpiceyPy.
Provides static utility methods for loading/unloading SPICE kernels, querying body states and positions, converting between time systems, resolving body and frame identifiers, and computing geometric quantities (light time, ground-station visibility, etc.).
All methods that return physical quantities wrap their output in
ArrayWUnitsorArrayWFrameto carry units and frames explicitly.- Attributes:
- kernel_folder
Methods
YDS2et(year, doy, sec)Method to convert a year, DOY, seconds into ephemeris times.
cal2et(cal)Convert a calendar UTC string to ephemeris time.
check_kernel_status_in_pool(kernel_filename)Check if a Spice kernel is loaded in the kernel pool.
ckbrief(ck_file[, tol, disp])Extracts ID and interval information from a given C-kernel.
Unload all SPICE kernels from the kernel pool.
Drop every cached parameters sidecar.
def_new_body(name, spiceId)Define a new celestial body in the SPICE kernel.
et2YDS(et_list)Method to convert a list of ephemeris times into (year, DOY, seconds) format.
et2cal(et)Convert ephemeris time to a calendar UTC string.
et2jd(et[, form, prec, utclen])Convert ephemeris time to a Julian Date string (JDUTC).
et2sclk(scId, et[, lenout])Convert ephemeris time to a spacecraft clock string.
et2utc(et[, form, prec, utclen])Convert ephemeris time to a UTC string.
frame_id_to_frame_name(frame_id)Return the SPICE frame name for a given integer frame ID.
frame_name_to_frame_id(frame_name)Return the SPICE integer frame ID for a given frame name.
generate_metakernel(directory[, output_file])List all files in a directory and write them into a SPICE metakernel.
get_STMs(trgt_bdy, epoch_time, ...[, ...])Retrieve or interpolate the State Transition Matrix (STM) at a given epoch.
get_attitude(trgt_bdy, epoch_time, ...[, ...])Get the attitude of a target body at a specified epoch time.
get_elevation_angle(target, et[, station, ...])Compute the elevation angle of a target body as seen from a DSN ground station using SPICE.
get_frame_w_spice_id(id_number)Return the frame code and name associated with a NAIF body ID.
get_id_from_string(name_string)Return the NAIF integer ID for a body given its SPICE name.
get_intervals(spkFile, objID)Return the coverage interval of a body in an SPK file as JD strings.
get_lighttime(trgt_bdy, epoch_time, ...[, ...])Calculate the light time between a target and an origin at a given epoch time.
get_name_from_id(spice_id)Return the SPICE body name for a given NAIF integer ID.
Determine the visibility windows between an observer and a target within a specified time range.
get_parameters(trgt_bdy, epoch_time, ...[, ...])Retrieve and interpolate estimated parameters from a companion JSON file.
get_pos(trgt_bdy, epoch_time, ...[, ab_correct])Get the position of a target body relative to an observer body at a given epoch.
get_pos_values(trgt_bdy, epoch_time, ...[, ...])Raw-array variant of
get_pos()for hot inner loops.get_propagator_settings(trgt_bdy, ...[, ...])Retrieves the propagator settings for a given target, reference frame, and origin from JSON files.
get_sep_angle(target, et[, station, abcorr])Compute the Sun–Earth–Probe (SEP) angle of a target body as seen from a DSN ground station.
get_state(trgt_bdy, epoch_time, ...[, ...])Retrieve the state (position and velocity) of a target body relative to an origin body at a specified epoch time.
get_state_antenna(trgt_bdy, epoch_time, ...)Retrieve the state (position and velocity) of the antenna on a target spacecraft relative to an origin body at a specified epoch time.
get_state_precise(trgt_bdy, epoch_time_high, ...)Retrieve the state of a target body at a two-part epoch
epoch_time_high + epoch_time_low.get_vel(trgt_bdy, epoch_time, ...[, ab_correct])Calculates the velocity of a target body relative to an observer body at a specified epoch time and reference frame.
get_xfrm(frame_from, frame_to, epoch)Computes the direction cosine matrix (DCM) to transform coordinates from one reference frame to another at a given epoch.
id2name(id)Convert given SPICE ID to the name of the associated body.
increase_kernel_priority(kernel_filename)This function increases the priority of kernel to the top of the pool for kernels of the same type by unloading then loading it.
jd2et(jd)Convert a Julian Date (JDTDB) to ephemeris time.
List every body found across all loaded SPK kernels.
list_all_ck_ids(ck_file)Return all NAIF IDs present in a C-kernel file.
List all SPICE reference frames currently detectable in the pool.
load_kernel(kernel_filenames)Load SPICE kernels into the SPICE system.
load_kernel_from_mkfile(furnshKernelFilename)Load a SPICE kernel from a given MK file.
matrix_times_vector(matrix, vector)Multiply a \(3 \times 3\) matrix by a 3-vector via SPICE.
name_to_ID(name)Converts a given name to its corresponding ID in the kernel pool.
Print the source and type of every currently loaded SPICE kernel.
sce2c(sc, et)Convert ephemeris time to encoded spacecraft clock ticks.
sclk2et(scId, sclk)Convert a spacecraft clock string to ephemeris time.
sidecar_files([location, kind])List the sidecar files a lookup would read, in the order it reads them.
spk_files_for_body(spice_id[, epochs])List the loaded SPK files that provide ephemeris for a body.
str2et(s)Convert a time string to ephemeris time (TDB seconds past J2000).
unload_kernel_from_pool(kernel_filename)Unload a kernel from the pool.
utc2et(utc)Convert a UTC time string to ephemeris time (TDB seconds past J2000).
utc2tdb(utc)Convert a UTC time string to TDB seconds past J2000.
write_ck_type3(ck_path, inst_id, ref_frame, ...)Write a CK type 3 segment (discrete pointing) to a new CK file.
write_spk_metadata_json(SPK_name, body, ...)Write ONLY the JSON sidecars associated with an SPK (parameters/STMs/settings/mass profile).
write_spk_segment_type13(SPK_name, ...[, ...])Write a segment of type 13 to an SPK file.
Notes
SpiceManageris a pure-static class; it holds no instance state. Configuration is done through class-level attributes:kernel_list— list of currently loaded kernel paths.kernel_folder— default folder scanned for scenario kernels.poly_interp_deg— polynomial degree for state interpolation.
References
[1]Annex et al., (2020). SpiceyPy: a Pythonic Wrapper for the SPICE Toolkit. Journal of Open Source Software, 5(46), 2050. https://doi.org/10.21105/joss.02050
[2]Acton, C.H.; “Ancillary Data Services of NASA’s Navigation and Ancillary Information Facility;” Planetary and Space Science, Vol. 44, No. 1, pp. 65–70, 1996. DOI 10.1016/0032-0633(95)00107-7
[3]Acton, C.; Bachman, N.; Semenov, B.; Wright, E.; “A look toward the future in the handling of space science mission geometry;” Planetary and Space Science (2017). DOI 10.1016/j.pss.2017.02.013
- classmethod ckbrief(ck_file: str, tol: int = 0, disp: bool = False) list[dict]#
Extracts ID and interval information from a given C-kernel.
- Parameters:
- ck_filestr
The path to the C-kernel file to be examined.
- dispbool, optional
Flag to include a formatted print-out of the brief. Defaults to
False.
- Returns:
- brieflist of dict
A list containing information about each frame in the C-kernel. Each element of the list is a dict containing the following keys:
'ID': the NAIF integer code of the frame.'SCLK_INTERVAL': the interval or intervals for which the frame is defined in the C-kernel, represented as encoded SCLK ticks by floats.'TDB_INTERVAL': the interval or intervals for which the frame is defined in the C-kernel, represented as ephemeris time (TDB) EpochArray objects.
- classmethod clear_kernels()#
Unload all SPICE kernels from the kernel pool.
Calls
spice.kclear()to flush every kernel currently held in memory.- Returns:
- None
- classmethod get_STMs(trgt_bdy: str | Body, epoch_time: float, reference_frame: str | Frame, obsvr_bdy: str | Body, folder_path_override: str = None, sidecar_path=None) ndarray#
Retrieve or interpolate the State Transition Matrix (STM) at a given epoch.
Reads the candidates
sidecar_files()resolves from sidecar_path — an SPK, a file, a folder, or several of them — and takes the first whosebody_ID,origin_ID, andreference_framematch the supplied arguments. If epoch_time equals a stored epoch the corresponding STM is returned directly. Otherwise element-wise linear interpolation is performed between the two bracketing epochs.A sequence sidecar stores one STM block per leg, each on that leg’s own grid. The STM is then taken from the first leg whose span holds epoch_time, so an epoch on the boundary between two legs reads the end of the earlier one.
- Parameters:
- trgt_bdystr or Body
Target body whose STMs are requested.
- epoch_timefloat
TDB epoch (seconds past J2000) at which to retrieve/interpolate the STM.
- reference_framestr or Frame
Reference frame recorded in the STM JSON file.
- obsvr_bdystr or Body
Observer (origin) body recorded in the STM JSON file.
- folder_path_overridestr, optional
Deprecated alias for sidecar_path, kept working for callers that pass a folder. Defaults to
None.- sidecar_pathstr or os.PathLike or iterable, optional
Where to look for the sidecar: an SPK, a file, a folder, or an iterable of those — see
sidecar_files(). Defaults toNone.
- Returns:
- STMnumpy.ndarray
Shape
(n, n)State Transition Matrix evaluated at epoch_time,nbeing the size of the state it was propagated with.
- Raises:
- SidecarNotFoundError
If no matching STM sidecar is found in any location searched.
- ValueError
If epoch_time lies outside the stored time span, or outside every leg’s span for a sequence sidecar.
- classmethod get_attitude(trgt_bdy: str | Body, epoch_time: float | EpochArray, reference_frame: str | Frame, tol: int, frame_id: int = None)#
Get the attitude of a target body at a specified epoch time.
- Parameters:
- trgt_bdystr or Body
The target body for which the attitude is to be determined. Can be an instance of Body or a string representing the body’s name.
- epoch_timefloat or EpochArray
The epoch time at which the attitude is to be determined. Can be an instance of EpochArray or a float representing the time.
- reference_framestr or Frame
The reference frame in which the attitude is to be determined. Can be a string or an instance of Frame.
- tolint
Time tolerance for the C-kernel lookup, in spacecraft clock ticks.
- frame_idint, optional
The frame of the target body. If not given, frame ID is assumed to be the body’s ID multiplied by 1000. Defaults to
None.
- Returns:
- cmatnp.ndarray
(3, 3) rotation matrix from
reference_frameto the body frame, as returned byspice.ckgpav.- avnp.ndarray
(3,) angular velocity of the body frame relative to
reference_frame, in rad/s, expressed inreference_frame.- clkoutfloat
Spacecraft clock time, in ticks, of the returned pointing.
- classmethod get_elevation_angle(target: str, et, station: str = 'DSS-14', abcorr: str = 'LT+S') float#
Compute the elevation angle of a target body as seen from a DSN ground station using SPICE.
This method uses the SPICE toolkit to calculate the elevation angle of a target relative to a Deep Space Network (DSN) ground station. The calculation is performed in the station’s local topocentric frame (e.g.,
DSS-14_TOPO), where the convention is X = East, Y = North, and Z = Up.- Parameters:
- targetstr
The name or NAIF ID of the target body. Examples:
"MRO"or"-74".- etfloat
Ephemeris time at which to compute the elevation angle.
- stationstr
The DSN ground station name or NAIF ID used as the observer. Must match the identifiers defined in the loaded SPICE kernels. Defaults to
"DSS-14".- abcorrstr, optional
Aberration correction to apply when computing the geometry. Examples: -
"NONE": No corrections. -"LT": Light-time correction only. -"LT+S": Light-time + stellar aberration correction (default).
- Returns:
- elevation_angleArrayWUnits
The elevation angle of the target relative to the local horizon at the specified DSN station, expressed in radians (or the units defined by
cls._spc_angle_units). Positive values indicate the target is above the horizon, while negative values indicate it is below.
Notes
The station’s topocentric frame (e.g.,
DSS-14_TOPO) must be defined in the loaded SPICE kernels.The axis convention for topocentric frames is assumed to be: X = East, Y = North, Z = Up.
To obtain azimuth as well, use
atan2(East, North)in the same frame.Requires SPICE kernels for:
DSN station locations and frames.
Target body ephemerides.
Leapseconds (LSK).
- classmethod get_lighttime(trgt_bdy: str | Body, epoch_time: float | EpochArray, reference_frame: str | Frame, obsvr_bdy: str | Body, aberration_correction: str = 'None')#
Calculate the light time between a target and an origin at a given epoch time.
- Parameters:
- trgt_bdystr or Body
The target body or its name as a string.
- epoch_timeEpochArray or float
The epoch time at which to calculate the light time.
- reference_framestr or Frame
The reference frame or its name as a string.
- originstr or Body
The origin body or its name as a string.
- aberration_correctionstr, optional
The aberration correction to apply. Defaults to
None.
- Returns:
- light_timeArrayWUnits
The light time as an array with units.
- classmethod get_parameters(trgt_bdy: str | Body, epoch_time: float | EpochArray, reference_frame: str | Frame, obsvr_bdy: str | Body, folder_path_override: str = None, per_parameter: bool = False, sidecar_path=None)#
Retrieve and interpolate estimated parameters from a companion JSON file.
Reads the candidates
sidecar_files()resolves from sidecar_path — an SPK, a file, a folder, or several of them — and takes the first whosebody_ID,origin_ID, andreference_framematch the supplied arguments, at the top level or in any leg. If the file contains a multi-leg sequence, the leg whoseepochsTDBinterval contains epoch_time is selected. Within each leg (or in the flat, non-sequence case) the stored parameter time series is fitted with a polynomial of degreecls.poly_interp_par_degand evaluated at epoch_time.- Parameters:
- trgt_bdystr or Body
Target body whose parameters are requested.
- epoch_timefloat or EpochArray
TDB epoch (seconds past J2000) at which to evaluate the parameters.
- reference_framestr or Frame
Reference frame recorded in the JSON file.
- obsvr_bdystr or Body
Observer (origin) body recorded in the JSON file.
- folder_path_overridestr, optional
Deprecated alias for sidecar_path, kept working for callers that pass a folder. Defaults to
None.- per_parameterbool, optional
Return a
{name: ArrayWUnits}mapping instead of the stacked vector. Defaults toFalse.- sidecar_pathstr or os.PathLike or iterable, optional
Where to look for the sidecar: an SPK, a file, a folder, or an iterable of those — see
sidecar_files(). WhenNone(default),cls.kernel_folderis used if set; otherwise falls back to<cwd>/data/kernels/scenario.
- Returns:
- parametersArrayWUnits or dict of str to ArrayWUnits
By default an
ArrayWUnitsholding the stacked parameter vector, always — the return type does not vary with the contents of the file.Its units are the shared units when every parameter of the body agrees, which is the usual case. A body’s parameters need not agree, though: solving for a delta-v (km/s) alongside a maneuver-epoch correction (sec) is ordinary. No single unit then describes the stack, so it is reported dimensionless rather than mislabelled with whichever unit came first, and
per_parameteris the way to recover what each column actually is.With
per_parameter=True, a{name: ArrayWUnits}mapping instead, each entry carrying its own units.
- Raises:
- SpiceManager.SidecarNotFoundError
If no matching sidecar is found; the message lists every location searched.
- ValueError
If the sidecar is malformed (e.g. a leg’s
parametersentry), or if epoch_time does not fall within any leg’s time span.
- Warns:
- RuntimeWarning
If more than one matching sidecar is found; the most recently modified file is used.
- classmethod get_pos(trgt_bdy: str | Body, epoch_time: float | EpochArray, reference_frame: str | Frame, obsvr_bdy: str | Body, ab_correct: str = 'None')#
Get the position of a target body relative to an observer body at a given epoch. This method computes the position vector of a target body as observed from an observer body at a specified epoch time, in a given reference frame.
- Parameters:
- trgt_bdystr | Body
The target body whose position is to be computed. Can be specified as a string (body name) or a Body object.
- epoch_timefloat | EpochArray
The epoch time(s) at which to compute the position. Can be a single float value or an EpochArray for multiple time points.
- reference_framestr | Frame
The reference frame in which to express the position vector. Can be specified as a string (frame name) or a Frame object.
- obsvr_bdystr | Body
The observer body from which the target position is measured. Can be specified as a string (body name) or a Body object.
- ab_correctstr, optional
Aberration correction specification. Defaults to “None”. Common values include “NONE”, “LT”, “LT+S”, “CN”, “CN+S”, “XLT”, “XLT+S”, “XCN”, “XCN+S”.
- Returns:
- The position vector(s) of the target body relative to the observer body.
- The exact return type depends on the implementation of _get_pos_core.
Notes
This method is a wrapper around _get_pos_core and delegates the actual computation to that core method.
- classmethod get_pos_values(trgt_bdy, epoch_time, reference_frame, obsvr_bdy, ab_correct='None')#
Raw-array variant of
get_pos()for hot inner loops.Returns the position as a plain numpy array in kilometers, skipping the
ArrayWUnitswrap/unwrap thatget_pos()performs. Numerically identical toget_pos(...).values; use this where the caller only needs the values (e.g. force-model acceleration during propagation).- Parameters:
- trgt_bdy, obsvr_bdystr or Body
Target and observer bodies.
- epoch_timefloat
TDB epoch (seconds past J2000).
- reference_framestr or Frame
Output reference frame.
- ab_correctstr, optional
Aberration correction. Defaults to
"None".
- Returns:
- numpy.ndarray
(3,)position vector in km.
- classmethod get_propagator_settings(trgt_bdy: str | Body, reference_frame: str | Frame, obsvr_bdy: str | Body, folder_path_override: str = None, sidecar_path=None)#
Retrieves the propagator settings for a given target, reference frame, and origin from JSON files.
Reads the candidates
sidecar_files()resolves from sidecar_path — an SPK, a file, a folder, or several of them — and takes the first whosebody_ID,origin_ID, andreference_framematch the supplied arguments.- Parameters:
- trgt_bdystr or Body
The target body or its name.
- reference_framestr or Frame
The reference frame or its name.
- obsvr_bdystr or Body
The origin body or its name.
- folder_path_overridestr, optional
Deprecated alias for sidecar_path, kept working for callers that pass a folder. Defaults to
None.- sidecar_pathstr or os.PathLike or iterable, optional
Where to look for the sidecar: an SPK, a file, a folder, or an iterable of those — see
sidecar_files(). Defaults toNone.
- Returns:
- dict
The propagator settings data from the corresponding JSON file.
- Raises:
- SidecarNotFoundError
If no matching settings sidecar is found in any location searched.
- classmethod get_sep_angle(target: str, et, station: str = 'DSS-14', abcorr: str = 'LT+S') float#
Compute the Sun–Earth–Probe (SEP) angle of a target body as seen from a DSN ground station.
The SEP angle is defined as the angle at the observer (DSN station) between the vector pointing to the Sun and the vector pointing to the spacecraft (target). This is the standard “solar elongation angle” used in mission operations to assess geometry for radiometric tracking and solar corona effects.
- Parameters:
- targetstr
The name or NAIF ID of the target body. Examples:
"OSIRIS-REX"or"-64".- etfloat
Ephemeris Time (seconds past J2000 TDB) at which to compute the SEP angle.
- stationstr, optional
DSN ground station name or NAIF ID used as the observer. Must match the identifiers defined in the loaded SPICE kernels. Default is
"DSS-14".- abcorrstr, optional
Aberration correction to apply when computing the geometry. Examples: -
"NONE": No corrections. -"LT": Light-time correction only. -"LT+S": Light-time + stellar aberration correction (default).
- Returns:
- sep_angleArrayWUnits
The SEP angle in radians (or converted via
cls._spc_angle_units). Larger angles correspond to better tracking geometry (target farther from the Sun as seen from Earth).
Notes
- Requires SPICE kernels for:
DSN station locations (SPK + topocentric frame definitions).
Target body ephemerides (SPK).
Solar system ephemerides (SPK).
Leapseconds (LSK).
This angle is distinct from elevation angle (target above station horizon). SEP measures angular separation from the Sun, not from the horizon.
Often used to set operational limits during solar conjunctions.
Examples
et = scb.SpiceManager.utc2et("2017-09-22T16:52:00") # OSIRIS-REx EGA sep = MyClass.get_sep_angle("OSIRIS-REX", et, station="DSS-14") print(sep.to("deg"))
- classmethod get_state(trgt_bdy: str | Body, epoch_time: float | EpochArray, reference_frame: str | Frame, obsvr_bdy: str | Body, aberration_correction: str = 'None')#
Retrieve the state (position and velocity) of a target body relative to an origin body at a specified epoch time.
- Parameters:
- trgt_bdystr or Body
The target body for which the state is to be retrieved. Can be a string name or a Body object.
- epoch_timefloat or EpochArray
The epoch time at which the state is to be retrieved. Can be an EpochArray object or a float representing the time.
- reference_framestr or Frame
The reference frame in which the state is to be retrieved. Can be a Frame object or a string name.
- obsvr_bdystr or Body
The observing body relative to which the state is to be retrieved. Can be a string name or a Body object.
- aberration_correctionstr, optional
The aberration correction to be applied. Defaults to
None.
- Returns:
- stateArrayWUnits
An array containing the state (position and velocity) of the target body with associated units.
- classmethod get_state_antenna(trgt_bdy: Body, epoch_time: float, reference_frame: Frame, obsvr_bdy: Body, antenna_offset: ndarray, offset_reference_frame: Frame, ab_correct: str = 'None')#
Retrieve the state (position and velocity) of the antenna on a target spacecraft relative to an origin body at a specified epoch time.
- Parameters:
- trgt_bdystr
The target body for which the position is to be determined. Can be a string or a Body object.
- epoch_timefloat
The epoch time at which the position is to be determined. Can be a float or an EpochArray object.
- reference_frameFrame
The reference frame in which the position is to be determined. Can be a string or a Frame object.
- obsvr_bdystr
The observing body from which the position is to be measured. Can be a string or a Body object.
- antenna_offset: np.ndarray
The antenna-CoM offset vector, expressed in the “spacecraft_body_frame” reference frame.
- offset_reference_frame: Frame
The spaceraft body-fixed reference frame. The origin of this frame is used to account for the antenna offset vector.
- ab_correctstr, optional
Aberration correction to be applied. Defaults to
None.
- Returns:
- statenp.ndarra()
The State of the antenna relative to the origin body, expressed in units of km and km/sec
- classmethod get_state_precise(trgt_bdy: str | Body, epoch_time_high: float | EpochArray, reference_frame: str | Frame, obsvr_bdy: str | Body, aberration_correction: str = 'None', epoch_time_low: float | None = None)#
Retrieve the state of a target body at a two-part epoch
epoch_time_high + epoch_time_low.SPICE is evaluated once at the nearest representable epoch, and the position is then moved along the velocity by the part of the epoch that a single float cannot hold. The neglected second-order term is
|a| d^2 / 2, with|d|at most half an ULP of the epoch (~60 ns near J2000 + 26 yr), i.e. below 1e-14 km for any solar-system acceleration.- Parameters:
- trgt_bdystr or Body
The target body for which the state is to be retrieved. Can be a string name or a Body object.
- epoch_time_highfloat or EpochArray
High part of the epoch, in TDB seconds past J2000. Can be an EpochArray object or a float.
- reference_framestr or Frame
The reference frame in which the state is to be retrieved. Can be a Frame object or a string name.
- obsvr_bdystr or Body
The observing body relative to which the state is to be retrieved. Can be a string name or a Body object.
- aberration_correctionstr, optional
The aberration correction to be applied. Defaults to
None.- epoch_time_lowfloat, optional
Low part of the epoch [s], typically from
EpochArray._add_duration().Noneis treated as0.0, which reproducesget_state().
- Returns:
- stateArrayWUnits
An array containing the state (position and velocity) of the target body with associated units.
- classmethod get_vel(trgt_bdy: str | Body, epoch_time: float | EpochArray, reference_frame: str | Frame, obsvr_bdy: str | Body, ab_correct: str = 'None')#
Calculates the velocity of a target body relative to an observer body at a specified epoch time and reference frame.
- Parameters:
- trgt_bdystr | Body
The target body for which the velocity is to be computed. Can be a string identifier or a Body object.
- epoch_timefloat | EpochArray
The epoch time(s) at which to compute the velocity. Can be a single float or an array of epochs.
- reference_framestr | Frame
The reference frame in which the velocity is expressed. Can be a string or a Frame object.
- obsvr_bdystr | Body
The observer body relative to which the velocity is computed. Can be a string identifier or a Body object.
- ab_correctstr, optional
Aberration correction flag. Defaults to “None”.
- Returns:
- Velocity or array-like
The computed velocity of the target body relative to the observer in the specified reference frame.
- classmethod get_xfrm(frame_from: str, frame_to: str, epoch)#
Computes the direction cosine matrix (DCM) to transform coordinates from one reference frame to another at a given epoch.
- Parameters:
- frame_fromstr
The name of the source reference frame.
- frame_tostr
The name of the target reference frame.
- epoch
The epoch at which the transformation is computed. The type depends on the implementation (e.g., float, datetime).
- Returns:
- numpy.ndarray
The direction cosine matrix (DCM) representing the transformation from frame_from to frame_to at the specified epoch.
- classmethod print_kernels()#
Print the source and type of every currently loaded SPICE kernel.
Iterates over all kernels tracked by
spice.ktotaland prints each entry’s file path and kernel type to stdout.- Returns:
- None
- classmethod sidecar_files(location=None, kind: str = 'parameters') list[str]#
List the sidecar files a lookup would read, in the order it reads them.
Sidecars are found by where they are, not by a folder layout this library imposes, so
locationcan be whatever handle the caller happens to hold:an SPK (
.bsp) — the sidecars written beside it are read first (<base>_parameters.jsonand friends), then anything else in the same folder, which covers a run whose sidecars are shared under a different basename;a file — read as-is, whatever it is called;
a folder — the files in it whose names carry this library’s suffix for kind come first, then any other
.json/.pkl, so a folder following someone else’s naming still resolves;an iterable of any of the above — searched in the given order, for payloads split across locations;
None—kernel_folderwhen set, then<cwd>/data/kernels/scenario.
Locations that do not exist are skipped rather than raised on: the callers report every location they consulted when a lookup finds nothing, which is more useful than failing on the first missing one.
- Parameters:
- locationstr or os.PathLike or iterable, optional
Where to look, as described above. Defaults to
None.- kindstr, optional
Which payload is wanted —
'parameters','stms','settings', or'mass_profile'. Only sets which suffixes are preferred. Defaults to'parameters'.
- Returns:
- list of str
Absolute paths of existing candidate files, most specific first, without duplicates.
Examples
SpiceManager.sidecar_files("/runs/case7/traj.bsp") SpiceManager.sidecar_files(["/runs/case7", "/shared/sidecars"])
- classmethod write_ck_type3(ck_path: str, inst_id: int, ref_frame: str, sclk_id: int, et_list: list[float] | ndarray, quats: ndarray | None = None, avvs: ndarray | None = None, dcm_cb=None, segid: str = 'SCB GENERATED CK TYPE 3', make_intervals: str = 'per_sample', load_after: bool = True)#
Write a CK type 3 segment (discrete pointing) to a new CK file.
- Parameters:
- ck_pathstr
Output CK file path (.bc or .ck).
- inst_idint
NAIF instrument/frame ID for the CK segment (the CK “INST” id).
- ref_framestr
Base/reference frame name (usually ‘J2000’).
- sclk_idint
NAIF spacecraft clock ID code used by sce2c().
- et_listarray-like
ET (TDB seconds past J2000) sample times.
- quatsndarray, optional
Quaternions rotating vectors from ref_frame to inst frame. Shape (N,4) or (4,N). If None, must provide dcm_cb.
- avvsndarray, optional
Angular velocities expressed in ref_frame. Shape (N,3) or (3,N). If None, AVFLAG=0 and zeros are written (or FD-estimated if dcm_cb provided and you want).
- dcm_cbcallable, optional
Function et -> (3,3) DCM C_ref_to_inst. If provided and quats is None, quats are built via spice.m2q(C). spice.m2q uses SPICE quaternion convention. :contentReference[oaicite:2]{index=2}
- segidstr
Segment ID (<= 40 chars recommended).
- make_intervals{‘per_sample’,’single’}
‘per_sample’: NINTS=N-1, STARTS=sclkdp[:-1]
‘single’ : NINTS=1, STARTS=[sclkdp[0]]
- load_afterbool
If True, furnsh() the CK after writing.
- Returns:
- ck_pathstr
Path to the written CK file.
Notes
CKW03 requirements include monotonically increasing SCLKDP and descriptor times containing the data range. :contentReference[oaicite:3]{index=3}
- classmethod write_spk_metadata_json(SPK_name: str, body: Body, origin_ID: float, ref_frame: Frame, epochs_TDB: list, degree_poly: int, parameters_JSON: list = None, parameters_units: list = None, STMs_JSON: list = None, STM_units: dict = None, state_definition: list = None, sequence_definition: list = None, leg_data: dict = None, propagator_settings: dict = None, mass_profile: SCBPolynomial = None, stm_format: str = 'json', sidecar_format: str = 'json', sidecar_name: str = None)#
Write ONLY the JSON sidecars associated with an SPK (parameters/STMs/settings/mass profile).
This avoids writing any additional SPK segments (no dummy segments), and avoids SPICE descriptor-time errors.
Notes
epochs_TDB is included so JSON has a time reference; for sequences it can be the concatenated full epochs list or the global seq.total_epochsTDB list.
For sequence_definition != None, epochs_TDB is not directly used for legs epochs; _prepare_sequence_data uses sequence_definition.epochs_vec.
- classmethod write_spk_segment_type13(SPK_name: str, SPK_SEG_ID: str, body: Body, origin_ID: float, ref_frame: Frame, epochs_TDB: list, degree_poly: int, state_SPICE: list, parameters_JSON: list = None, parameters_units: list = None, STMs_JSON: list = None, STM_units: dict = None, state_definition: list = None, sequence_definition: list = None, leg_data: dict = None, propagator_settings: dict = None, mass_profile: SCBPolynomial = None, stm_format: str = 'json', sidecar_format: str = 'json', sidecar_name: str = None)#
Write a segment of type 13 to an SPK file.
Type 13 stores the same
(epoch, position, velocity)records as type 9, in the same number of bytes, but interpolates them with Hermite polynomials that use the sampled velocities as derivative constraints on the position curve. The returned velocity is then the exact derivative of the returned position, and atdegree_poly=3the two-node window makes the interpolant C1-continuous across every node, removing the jumps a shifting type-9 Lagrange window produced at each node crossing.- Parameters:
- SPK_namestr
The name of the SPK file.
- SPK_SEG_IDstr
The segment ID.
- bodyobject
The body object.
- origin_IDint
The ID of the origin.
- ref_frameframe
The reference frame.
- epochs_TDBlist
The array of epochs in TDB format.
- degree_polyint
The degree of the polynomial.
- state_SPICElist
The array of states in SPICE format.
- parameters_JSONlist, optional
The array of parameters in JSON format.
- STMs_JSONlist, optional
The array of state transition matrices in JSON format.
- state_definitionlist, optional
The state definition.
- sequence_definitionobject, optional
The sequence definition.
- leg_datadict, optional
The body, origin, and reference frame data for each leg.
- propagator_settingsdict, optional
The propagator settings.
- mass_profileSCBPolynomial, optional
The mass profile.
- Returns:
- None
- Raises:
- EvenDegreeError
If
degree_polyis even. Type 13 builds each Hermite polynomial from a position and a velocity per node, so its degree is always odd.- TooFewStatesError
If the segment holds fewer than
(degree_poly + 1) // 2states, which is the window SPK type 13 needs to build its interpolating polynomial.
- static YDS2et(year, doy, sec)#
Method to convert a year, DOY, seconds into ephemeris times.
- Parameters:
- yearfloat or list of float
Year
- doyfloat or list of float
Day of the year
- secfloat or list of float
Second of the year
- Returns:
- etlist
List of ephemeris times
- static cal2et(cal: str) float#
Convert a calendar UTC string to ephemeris time.
Alias for
str2et(); accepts any time string format recognised by SPICE.- Parameters:
- calstr
Calendar or ISO time string (e.g.
"2017 SEP 22 16:52:00").
- Returns:
- etfloat
TDB seconds past J2000.
- static check_kernel_status_in_pool(kernel_filename: str) bool#
Check if a Spice kernel is loaded in the kernel pool.
- Parameters:
- kernel_filenamestr
Filename of the kernel to be checked.
- Returns:
- bool
Returns True if the kernel is in the pool and False if not.
- static def_new_body(name, spiceId)#
Define a new celestial body in the SPICE kernel.
- Parameters:
- namestr
The name of the celestial body.
- spiceIdint
The SPICE ID of the celestial body.
- Returns:
- None
- static et2YDS(et_list)#
Method to convert a list of ephemeris times into (year, DOY, seconds) format.
- Parameters:
- et_listfloat or list of float
List of ephemeris times
- Returns:
- (years,doys,secs)Tuple of lists
List of years, day of years, and seconds associated to the input et_list
- static et2cal(et: float | ndarray[tuple[Any, ...], dtype[_ScalarT]])#
Convert ephemeris time to a calendar UTC string.
Accepts scalar floats, 0-D arrays, or N-D arrays and preserves the input shape in the output.
- Parameters:
- etfloat or numpy.ndarray
TDB seconds past J2000. May be scalar or array-valued.
- Returns:
- calstr or numpy.ndarray of str
Calendar UTC string(s) in
"C"(civil) format. A scalar et returns a singlestr; a 1-D array returns a 1-D array of strings; a higher-dimensional array is reshaped back to the original shape.
- static et2jd(et: float, form: str = 'J', prec: int = 27, utclen: int = 27) str#
Convert ephemeris time to a Julian Date string (JDUTC).
- Parameters:
- etfloat
TDB seconds past J2000.
- formstr, optional
Format code; default
"J"produces a Julian Date string.- precint, optional
Digits of precision for fractional days. Default 27.
- utclenint, optional
Length of the output string buffer. Default 27.
- Returns:
- jdstr
Julian Date string. The returned value is always JDUTC.
- static et2sclk(scId: int, et: float, lenout: int = 30) str#
Convert ephemeris time to a spacecraft clock string.
Thin wrapper around
spice.sce2s.- Parameters:
- scIdint
NAIF spacecraft integer ID.
- etfloat
TDB seconds past J2000 to convert.
- lenoutint, optional
Maximum length of the output SCLK string. Default 30.
- Returns:
- sclkstr
Spacecraft clock string corresponding to et.
- static et2utc(et: float, form: str = 'ISOC', prec: int = 27, utclen: int = 27) str#
Convert ephemeris time to a UTC string.
- Parameters:
- etfloat
TDB seconds past J2000.
- formstr, optional
Output format code passed to
spice.et2utc. Common values:"ISOC"(ISO calendar, default),"ISOD"(ISO day-of-year),"C"(calendar),"D"(day-of-year),"J"(Julian date).- precint, optional
Number of digits of precision for fractional seconds. Default 27.
- utclenint, optional
Length of the output string buffer. Default 27.
- Returns:
- utcstr
UTC time string in the requested format.
- static frame_id_to_frame_name(frame_id: int) str#
Return the SPICE frame name for a given integer frame ID.
Results are cached with
functools.lru_cache()for performance.- Parameters:
- frame_idint
SPICE integer frame ID to resolve.
- Returns:
- frame_namestr
SPICE name of the reference frame.
Notes
The frame ID is distinct from the body NAIF ID used in SPK/PCK kernels.
- static frame_name_to_frame_id(frame_name: str) int#
Return the SPICE integer frame ID for a given frame name.
- Parameters:
- frame_namestr
SPICE name of the reference frame (e.g.
"J2000").
- Returns:
- frame_idint
SPICE integer frame ID corresponding to frame_name.
Notes
The frame ID is distinct from the body NAIF ID used in SPK/PCK kernels.
- static generate_metakernel(directory: str, output_file: str = 'output_metakernel.tm')#
List all files in a directory and write them into a SPICE metakernel.
- Parameters:
- directorystr
Path to the directory containing kernels.
- output_filestr
Name of the output metakernel file (default ‘output_metakernel.tm’).
- static get_frame_w_spice_id(id_number: int)#
Return the frame code and name associated with a NAIF body ID.
- Parameters:
- id_numberint
NAIF integer body ID to look up (e.g.
499for Mars).
- Returns:
- resulttuple of (int, str)
(frame_code, frame_name)where frame_code is the integer SPICE frame ID and frame_name is its string identifier.
- Raises:
- ValueError
If id_number has no associated frame in the kernel pool.
- static get_id_from_string(name_string: str) int#
Return the NAIF integer ID for a body given its SPICE name.
- Parameters:
- name_stringstr
SPICE body name (e.g.
"EARTH","MARS","-60000").
- Returns:
- id_numint
NAIF integer ID of the body.
- static get_intervals(spkFile: str, objID: int) list[str]#
Return the coverage interval of a body in an SPK file as JD strings.
Retrieves the first (and typically only) time window for objID from the SPK coverage window and converts the endpoints to Julian Date strings.
- Parameters:
- spkFilestr
Full path to the SPK file. The file must already be accessible on disk (it does not need to be loaded into the kernel pool).
- objIDint
NAIF integer body ID whose coverage is requested.
- Returns:
- intervallist of str
[start_jd, end_jd]where each element is a Julian Date string produced byspice.et2utc.
- static get_name_from_id(spice_id: int) str#
Return the SPICE body name for a given NAIF integer ID.
- Parameters:
- spice_idint
NAIF integer body ID (e.g.
399for Earth).
- Returns:
- namestr
SPICE body name corresponding to spice_id.
- static get_observer_target_visibility_windows(obsvr_bdy: str | Body, trgt_bdy: str | Body, epoch_start: float | EpochArray, epoch_end: float | EpochArray, step_size: float = 300.0, angle_limit: float = 10.0, inframe: str = 'obs', abcorr: str = 'None', crdsys: str = 'LATITUDINAL', coord: str = 'LATITUDE', relate: str = '>', adjust: float = 0.0, num_intervals: int = 1000)#
Determine the visibility windows between an observer and a target within a specified time range.
- Parameters:
- obsvr_bdyUnion[str, scb.Body]
The observer, either as a string name or a scb.Body object.
- trgt_bdyUnion[str, scb.Body]
The target, either as a string name or a scb.Body object.
- epoch_startUnion[float, scb.EpochArray]
The start time of the observation window.
- epoch_endUnion[float, scb.EpochArray]
he end time of the observation window.
- step_sizefloat, optional
The step size in seconds for the search. Default is 300.0.
- angle_limitfloat, optional
The angular limit for visibility in degrees. Default is 10.0.
- inframestr, optional
The reference frame for the observation. Default is “obs”.
- abcorrstr, optional
Aberration correction. Default is “None”.
- crdsysstr, optional
Coordinate system. Default is “LATITUDINAL”.
- coordstr, optional
Coordinate type. Default is “LATITUDE”.
- relatestr, optional
Relational operator for the coordinate comparison. Default is “>”.
- adjustfloat, optional
Adjustment value for the search. Default is 0.0.
- num_intervalsint, optional
Maximum number of intervals for the search. Default is 1000.
- Returns:
- tuple
A tuple containing the number of visibility windows and a list of visibility windows.
- static increase_kernel_priority(kernel_filename: str)#
This function increases the priority of kernel to the top of the pool for kernels of the same type by unloading then loading it.
Note: this is the method recommended by the Spice documentation.
- Parameters:
- kernel_filenamestr
Filename of the
- static jd2et(jd: float) float#
Convert a Julian Date (JDTDB) to ephemeris time.
- Parameters:
- jdfloat
Julian Date in the TDB time scale.
- Returns:
- etfloat
TDB seconds past J2000.
Notes
A leap-second correction (
spice.deltet) is added to account for the drift between JD and ET.
- static list_all_bodies() list[int]#
List every body found across all loaded SPK kernels.
Iterates over each SPK kernel currently loaded in the SPICE kernel pool, and for every kernel prints its filename followed by the NAIF integer ID and resolved name of each body it contains. Bodies whose ID cannot be resolved to a name are printed as
(no name).- Returns:
- all_idslist of int
Sorted, de-duplicated NAIF integer IDs of every body found across the loaded SPK kernels.
- static list_all_ck_ids(ck_file: str) list[int]#
Return all NAIF IDs present in a C-kernel file.
- Parameters:
- ck_filestr
Absolute or relative path to the CK file.
- Returns:
- idslist of int
NAIF integer IDs of every object stored in ck_file.
- static load_kernel(kernel_filenames)#
Load SPICE kernels into the SPICE system.
- Parameters:
- kernel_filenamesstr or list
A single kernel filename or a list of kernel filenames to be loaded.
- Returns:
- None
- static load_kernel_from_mkfile(furnshKernelFilename)#
Load a SPICE kernel from a given MK file.
- Parameters:
- furnshKernelFilenamestr
The filename of the MK file to load.
- Returns:
- None
- static matrix_times_vector(matrix, vector)#
Multiply a \(3 \times 3\) matrix by a 3-vector via SPICE.
Computes \(\mathbf{w} = \mathbf{M}\,\mathbf{v}\) using
spice.mxv(CSPICEmxv_c).- Parameters:
- matrixnumpy.ndarray
Shape
(3, 3)double-precision matrix (e.g. a rotation matrix).- vectornumpy.ndarray
Shape
(3,)double-precision vector.
- Returns:
- resultnumpy.ndarray
Shape
(3,)product \(\mathbf{M}\mathbf{v}\).
- static name_to_ID(name)#
Converts a given name to its corresponding ID in the kernel pool.
- Parameters:
- namestr
The name to be converted.
- Returns:
- int or None
The ID corresponding to the given name, or None if the name is not found in the kernel pool.
- static sce2c(sc: int, et: float) float#
Convert ephemeris time to encoded spacecraft clock ticks.
Thin wrapper around
spice.sce2c.- Parameters:
- scint
NAIF spacecraft integer ID (e.g.
-64for OSIRIS-REx).- etfloat
TDB seconds past J2000 to convert.
- Returns:
- sclk_ticksfloat
Encoded SCLK ticks corresponding to et.
- static sclk2et(scId: int, sclk: str) float#
Convert a spacecraft clock string to ephemeris time.
Thin wrapper around
spice.scs2e.- Parameters:
- scIdint
NAIF spacecraft integer ID (e.g.
-64for OSIRIS-REx).- sclkstr
Spacecraft clock time string as it appears in the SCLK kernel.
- Returns:
- etfloat
TDB seconds past J2000 corresponding to sclk.
- static spk_files_for_body(spice_id, epochs=None) list#
List the loaded SPK files that provide ephemeris for a body.
Useful for recording which trajectory a computation actually used, since a body’s ephemeris is resolved from global kernel-pool state rather than from anything passed in at the call site.
- Parameters:
- spice_idint or str
NAIF ID of the body.
- epochsarray_like, optional
ET epochs, in seconds. When given, only the files that resolve the body at one of these epochs are listed: for each epoch, the last-loaded file whose coverage contains it. Defaults to
None.
- Returns:
- list of str
Paths of the loaded SPKs covering this body, in load order. Without
epochs, SPK precedence (last-loaded-wins) makes the final entry the one that resolves wherever its coverage reaches, but an earlier file still resolves epochs outside it.
- static str2et(s: str) float#
Convert a time string to ephemeris time (TDB seconds past J2000).
Thin wrapper around
spice.str2et. Accepts a wide range of formats (ISO calendar, DOY, JD, etc.).- Parameters:
- sstr
Time string recognised by SPICE (e.g.
"2017-09-22T16:52:00"). Julian-Date strings are treated as JDUTC.
- Returns:
- etfloat
TDB seconds past J2000 corresponding to s.
- static unload_kernel_from_pool(kernel_filename: str)#
Unload a kernel from the pool. If the kernel is not in the pool then no action is taken.
- Parameters:
- kernel_filenamestr
Filename of the Spice kernel being unloaded.
- static utc2et(utc: str) float#
Convert a UTC time string to ephemeris time (TDB seconds past J2000).
Thin wrapper around
spice.utc2et.- Parameters:
- utcstr
UTC time string in a format recognised by SPICE (e.g.
"2017-09-22T16:52:00").
- Returns:
- etfloat
Equivalent ephemeris time in TDB seconds past J2000.
- static utc2tdb(utc: str) float#
Convert a UTC time string to TDB seconds past J2000.
Alias for
utc2et().- Parameters:
- utcstr
UTC time string in a format recognised by SPICE.
- Returns:
- tdbfloat
TDB seconds past J2000.
- list_all_frames() list#
List all SPICE reference frames currently detectable in the pool.
This includes all built in SPICE frames.
- Parameters:
- max_idint, optional
Keep only frames whose NAIF ID is at most this value. Enumerating every loaded frame is slow once a large kernel set is on the pool, so a caller that only needs the low-numbered inertial frames can cap the search. Defaults to no limit.
- Returns:
- frames_listlist of str
Names of all reference frames found.
- kernel_folder = None#
- kernel_list = []#
- poly_interp_deg = 3#
- poly_interp_par_deg = 1#
- exception EvenDegreeError#
Bases:
ValueErrorRaised when an even interpolation degree is given for a type-13 segment, whose Hermite polynomials are built from a position and a velocity per node and so always have odd degree.
- exception STMLayoutError#
Bases:
ValueErrorRaised when the STMs given for a sequence’s STM sidecar line up neither with its legs, one block per leg on that leg’s epoch grid, nor with the global epoch grid, one matrix per epoch.
- exception SidecarNotFoundError#
Bases:
ValueErrorRaised when no sidecar for the requested body, origin, and frame is found in any of the locations searched.
- exception TooFewStatesError#
Bases:
ValueErrorRaised when a segment has fewer states than its interpolation degree needs.