SPICE
This module is a thread-safe reader and writer of SPICE kernels. It loads SPICE kernel files directly into memory.
Note
This does not use cSPICE, or any original SPICE library code.
cSPICE is difficult to use in a thread safe manner which is limiting when performing orbit calculations on millions of objects.
Data files which are automatically downloaded:
DE440 - A SPICE file containing the planets within a few hundred years.
BSP files are also automatically downloaded for the 5 largest asteroids, which are used for numerical integrations when the correct flags are set.
PCK Files which enable coordinate transformations between Earths surface and the common inertial frames.
- class kete.spice.FovDefinition(shape, frame, boresight, bounds)
The field of view definition of an instrument, in its own frame.
- boresight
Boresight vector, as the kernel gives it.
- bounds
The boundary vectors. There is one for a circle, two for an ellipse, and the corners, in order, for a rectangle or a polygon.
- count(value, /)
Return number of occurrences of value.
- frame
Name of the frame of the vectors.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- shape
The shape, “CIRCLE”, “ELLIPSE”, “RECTANGLE” or “POLYGON”.
- class kete.spice.SpkBuilder(internal_desc='', comment='')
Builder for creating multi-segment SPK binary kernel files.
Add segments of different types one at a time, then write the completed file to disk. Use this class to create new SPK files from Python.
- Parameters:
internal_desc (str, optional) – Short internal description in the DAF header, at most 60 characters. Default is an empty string.
comment (str, optional) – Free-text comment block in the DAF file. Default is an empty string.
Examples
builder = kete.spice.SpkBuilder() builder.add_tle_segment("iss_tles.txt", 399, 1) builder.write("iss.bsp")
- add_tle_segment(tle_file, center_id, frame_id, pad_days=0.5)
Add Type 10 (TLE) segments from a TLE text file.
The method combines all TLE entries with the same NORAD catalog number into one SPK segment. The NAIF ID of each object is
-norad_id.- Parameters:
tle_file (str) – Path to a text file of TLEs, in 2-line or 3-line format.
center_id (int) – NAIF ID of the central body, for example 399 for Earth.
frame_id (int) – NAIF frame ID stored in each segment. kete evaluates Type 10 states in the J2000 equatorial frame, which is frame ID 1.
pad_days (float, optional) – Days of coverage added before the first and after the last element set of each segment. In the padding, the nearest element set is propagated. An object with one element set covers only this padding. Must be non-negative. Default is 0.5.
- Raises:
OSError – If the TLE file cannot be read.
ValueError – If the text holds no valid TLE, or if
pad_daysis negative or NaN.
- n_segments
Number of segments currently held by this builder.
- write(filename)
Write the completed SPK file to filename.
The file must not already exist.
- Parameters:
filename – Destination path for the
.bspfile.- Raises:
FileExistsError – If the output file already exists.
- class kete.spice.SpkInfo(name, jd_start, jd_end, center, frame, spk_type)
Information contained within a Spice Kernel.
- center
Reference Center NAIF ID.
- count(value, /)
Return number of occurrences of value.
- frame
Frame of reference.
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- jd_end
JD date of the end of the spice segment.
- jd_start
JD date of the start of the spice segment.
- name
Name of the object.
- spk_type
SPK Segment Type ID.
- kete.spice.approx_earth_pos_to_ecliptic(jd, geodetic_lat, geodetic_lon, height, name=None)
Compute the approximate state of a location on Earth in the Ecliptic frame.
kete.spice.earth_pos_to_ecliptic()should be preferred for all modern dates. This function is only an approximation.This should be used when the desired date is outside the Earth orientation PCK kernels, which begin in 1962.
The Earth’s orientation includes precession, the largest nutation terms, and the Earth’s rotation, which also sets the velocity. Polar motion is not included. From 1972 the rotation uses UTC in place of UT1, which differ by less than a second. Before 1972 it uses a model of Delta T, the difference between TT and UT1, which is poorly known before 1600.
- Parameters:
jd – Julian time (TDB) of the desired state.
geodetic_lat – Latitude on Earth’s surface in degrees.
geodetic_lon – Latitude on Earth’s surface in degrees.
height – Height of the observer above the surface of the Earth in km.
name – Optional name of the position on Earth.
- kete.spice.daf_convert_big_to_little_endian(input_filename, output_filename)
Convert a big-endian DAF/SPK file to a little-endian copy.
Some old SPK files from NAIF, for example Spitzer, are big-endian. kete reads these files and converts them in memory on each load. This function byte-swaps all numeric values of the input file. It writes the little-endian copy to
output_filenameonce.- Parameters:
input_filename (str) – Path to the big-endian DAF/SPK file.
output_filename (str) – Path to write the converted little-endian file.
- Raises:
ValueError – If the input file cannot be read, is not a valid big-endian DAF file, or if the output file cannot be written.
- kete.spice.earth_pos_to_ecliptic(jd, geodetic_lat, geodetic_lon, height_above_surface, name=None, center='Sun')
Given a position in the frame of the Earth at a specific time, convert that to Sun centered ecliptic state.
This uses the WGS84 model of Earth’s shape to compute state. This uses Geodetic latitude and longitude, not geocentric.
The frame conversion is done using a PCK file from the NAIF/JPL website. This is the combined PCK file containing lower accuracy historical data, high accuracy modern data, and the current predictions going forward.
- Parameters:
jd (float | Time) – Julian time (TDB) of the desired state.
geodetic_lat (float) – Latitude on Earth’s surface in degrees.
geodetic_lon (float) – Latitude on Earth’s surface in degrees.
height_above_surface (float) – Height of the observer above the surface of the Earth in km.
name (str | None) – Optional name of the position on Earth.
center (str | int) – The new center point, this defaults to being heliocentric.
- Returns:
Returns the equatorial state of the target in AU and AU/days.
- Return type:
- kete.spice.get_state(id, jd, center=Ellipsis, frame=Ellipsis)
Calculates the
Stateof the target object at the specified time jd.This defaults to the ecliptic heliocentric state, though other centers may be chosen.
- Parameters:
target – The names of the target object, this can include any object name listed in
loaded_objects()jd – Julian time (TDB) of the desired record.
center – The center point, this defaults to being heliocentric.
frame – Coordinate frame of the state, defaults to ecliptic.
- Returns:
Returns the ecliptic state of the target in AU and AU/days.
- Return type:
- Raises:
ValueError – If the desired time is outside of the range of the source binary file.
- kete.spice.instrument_equatorial_to_frame(instrument_id, jd, vec)
Convert a vector from the equatorial frame to an instrument frame.
The frame resolves through its chain of reference frames, such as a camera on a spacecraft. Where loaded CK kernels overlap, the kernel loaded last takes precedence. Pointing is not extrapolated. A time inside a gap between the intervals of a kernel has no pointing, unless another loaded kernel covers that time.
- Parameters:
instrument_id (int or str) – SPICE frame ID or frame name of the instrument frame. A frame that no loaded frames kernel defines is a CK frame with that ID.
jd (
Timeor float) – Time of the request. A float is a Julian date in the TDB scale.vec (
Vectoror list of float) – Vector to convert. A list is taken to be in the equatorial frame. AVectoris converted from its own frame.
- Returns:
Time of the frame, and the 3 components of the vector in the instrument frame. The time is the time of the CK pointing for a CK frame, and
jdotherwise.- Return type:
tuple of (
Time, list of float)- Raises:
ValueError – If the frame or a frame in its chain of reference frames is unknown, or of an unsupported class. Also if a CK frame in the chain has no pointing at
jd, or its spacecraft clock is not loaded.
- kete.spice.instrument_fov(instrument, jd)
The field of view of an instrument at a time, from the loaded kernels.
The instrument kernel gives the field of view in the frame of the instrument. The frame is resolved through its chain of reference frames to the equatorial frame. The observer is the spacecraft of the instrument, from the loaded SPK files. It is the spacecraft of the CK frame the instrument frame is fixed to. That is
CK_<id>_SPKif it is set, else the CK ID divided by 1000 for a CK ID of -1000 or less. Without such a CK frame, it is the instrument ID divided by 1000. The pointing has no light time or aberration correction.- Parameters:
instrument (int or str) – NAIF ID or name of the instrument, such as
-226111or"ROS_OSIRIS_NAC".jd (
Timeor float) – Time of the field of view. A float is a Julian date in the TDB scale.
- Returns:
The field of view.
- Return type:
- Raises:
ValueError – If the instrument or its field of view is not defined, or the field of view is an ellipse. Also if a frame in the chain has no data at
jd, if these rules give no spacecraft ID, or if the SPK files have no state of the spacecraft atjd.
- kete.spice.instrument_fov_definition(instrument)
The field of view definition of an instrument, in its own frame.
The definition comes from the loaded instrument kernels. An
ANGLESdefinition gives the boundary vectors from its reference vector and its angles.- Parameters:
instrument (int | str) – NAIF ID or name of the instrument, such as
-226111or"ROS_OSIRIS_NAC".- Returns:
The shape, frame name, boresight, and boundary vectors.
- Return type:
- Raises:
ValueError – If the instrument or its field of view is not defined, or the definition is malformed.
- kete.spice.instrument_frame_to_equatorial(instrument_id, jd, vec)
Convert a vector in an instrument frame to the equatorial frame.
The frame resolves through its chain of reference frames, such as a camera on a spacecraft. Where loaded CK kernels overlap, the kernel loaded last takes precedence. Pointing is not extrapolated. A time inside a gap between the intervals of a kernel has no pointing, unless another loaded kernel covers that time.
- Parameters:
instrument_id (int or str) – SPICE frame ID or frame name of the instrument frame. A frame that no loaded frames kernel defines is a CK frame with that ID.
jd (
Timeor float) – Time of the request. A float is a Julian date in the TDB scale.vec (list of float) – Vector in the instrument frame, with 3 components.
- Returns:
Time of the frame, and the vector in the equatorial frame. The time is the time of the CK pointing for a CK frame, and
jdotherwise.- Return type:
- Raises:
ValueError – If the frame or a frame in its chain of reference frames is unknown, or of an unsupported class. Also if a CK frame in the chain has no pointing at
jd, or its spacecraft clock is not loaded.
- kete.spice.kernel_fetch_from_url(url, force_download=False)
Download the target url into the cache folder of spice kernels.
- Parameters:
force_download (bool)
- kete.spice.kernel_header_comments(filename)
Return the comments contained within the header of the provided DAF file, this includes SPK and PCK files.
This does not load the contents of the file into memory, it only prints the header contents.
- Parameters:
filename (str) – Path to a DAF file.
- kete.spice.kernel_ls()
List all files contained within the kernels cache folder.
- kete.spice.kernel_reload(filenames=None, include_cache=False, include_planets=True)
Reset all loaded kernels, then load the specified kernels into memory.
The reset clears the SPK, PCK, CK, and all text kernels. The function identifies the type of each file from its header, not its extension. It supports binary SPK, PCK, and CK files, and text SCLK, frames (FK), PCK, instrument (IK), and meta-kernels. Other kernel types raise a ValueError, and then none of
filenamesload. A file of a supported type that fails to load prints a message and is skipped.A meta-kernel lists files in
KERNELS_TO_LOAD, which load right after it. In a listed name, a$and a symbol fromPATH_SYMBOLSis replaced by the matching entry ofPATH_VALUES. An entry that ends in+continues into the next entry. Relative paths are relative to the working directory, not to the meta-kernel. A listed file of an unsupported type, such as a leap seconds kernel or a DSK, prints a message and is skipped.Where kernels overlap in time for the same object, the kernel loaded last is used. The load order is the cache, then the default planetary kernels, then
filenamesin the order given. Thus the files infilenamestake precedence over all other kernels. The default planetary kernels take precedence over the cache. For an object in both, the cache supplies data only outside the time range of the default planetary kernels.- Parameters:
filenames (list of str, optional) – Paths of the files to load. The list can mix SPK, PCK, CK, SCLK, frames, text PCK, instrument, and meta-kernel files. Default is
None, which loads no additional files.include_cache (bool, optional) – If
True, also load the SPK kernels in the kete cache folder. Default isFalse.include_planets (bool, optional) – If
True(default), also load the default planetary kernels. These are the de440s planetary ephemeris, the WISE, Spitzer, and SPHEREx spacecraft kernels, the 5 largest main-belt asteroids, and the core PCK files. The function tries to download any missing file.
- Raises:
ValueError – If a file in
filenames, or a file a meta-kernel lists, cannot be read; if a file infilenamesdoes not have the header of a supported kernel type; or if a meta-kernel lists another meta-kernel.
- kete.spice.kernel_variable(name)
The value of a variable of the loaded text kernels.
- Parameters:
name (str) – Name of the variable, such as
"INS-226111_PIXEL_SIZE". The name is matched exactly.- Returns:
The numbers or strings of the variable, or None if no loaded text kernel defines it. A date is a string that starts with
@.- Return type:
list of float, list of str, or None
- kete.spice.loaded_object_info(desig)
Return the available SPK information for the target object.
- Parameters:
desig (int | str) – Name or integer id value of the object.
- Return type:
list[SpkInfo]
- kete.spice.loaded_objects()
Return a list of all NAIF objects currently loaded in the SPICE shared memory singleton.
- kete.spice.moon_illumination_frac(jd, observer='399')
Compute the fraction of the moon which is illuminated at the specified time.
This is a simple approximation using basic spherical geometry, and defaults to having the observer located at the geocenter of the Earth.
>>> float(kete.spice.moon_illumination_frac(Time.from_ymd(2024, 2, 24))) 0.9964936480162188
- kete.spice.mpc_code_to_ecliptic(obs_code, jd, center='Sun', full_name=False)
Load an MPC Observatory code as an ecliptic state.
This only works for ground based observatories.
- Parameters:
obs_code (str) – MPC observatory code or name of observatory.
jd (float | Time) – Julian time (TDB) of the desired state.
center (str | int) – The new center point, this defaults to being heliocentric.
full_name – Should the final state include the full name of the observatory or just its code.
- Returns:
Returns the equatorial state of the observatory in AU and AU/days.
- Return type:
- kete.spice.name_lookup(name)
Given the provided partial name or integer, find the full name contained within the loaded SPICE kernels.
>>> kete.spice.name_lookup("jupi") ('jupiter barycenter', 5)
>>> kete.spice.name_lookup(10) ('sun', 10)
If there are multiple names, but an exact match, the exact match is returned. In the case of
Earth, there is alsoEarth Barycenter, but asking for Earth will return the exact match. Puttingeartwill raise an exception as there are 2 partial matches.>>> kete.spice.name_lookup("Earth") ('earth', 399)
>>> kete.spice.name_lookup("Earth b") ('earth barycenter', 3)
- Parameters:
name – Name, partial name, or integer id value of the object.
- Returns:
Two elements in the tuple, the full name and the integer id value.
- Return type:
tuple
- kete.spice.repack_spk(input_filename, output_filename, object_ids=None, center_id=None, threshold_km=0.5, degree=None, output_type=2)
Repack an SPK file into a compact output file.
The function fits the positions of each object in the Equatorial J2000 frame. It writes the result to
output_filename. The coverage of each object is the coverage of its segments in the input file.The function loads the input file into the SPK singleton, where it stays after the call. The fit reads the loaded kernels, which provide the center-body chains. The input file loads last, so where another kernel also covers an object, the fit uses the input file.
- Parameters:
input_filename (str) – Path to the source
.bspfile to repack.output_filename (str) – Destination path for the output
.bspfile. The file must not exist.object_ids (list of int, optional) – NAIF IDs to repack. If
None(default), the function repacks all objects in the input file.center_id (int, optional) – NAIF ID of the center body of the output. If
None(default), each object uses the center of its first segment in the input file. An object that is not in the input file uses 10 (Sun).threshold_km (float, optional) – Maximum position error of the output, in km. Default is 0.5.
degree (int, optional) – Polynomial degree. For Type 2, 1 to 27, and
Nonegives 15. For Type 13, an odd number from 1 to 27, andNonegives 7. Default isNone.output_type (int, optional) – SPK segment type: 2 (Chebyshev) or 13 (Hermite). Default is 2.
- Returns:
One tuple of (object_id, n_segments, n_records_total, threshold_km) for each repacked object.
- Return type:
list[tuple[int, int, int, float]]
- Raises:
FileExistsError – If the output file already exists.
ValueError – If no objects are found, if
output_typeis not 2 or 13, or if the repack fails for any object.OSError – If the input file cannot be loaded, or if the output file cannot be written.
- kete.spice.state_to_earth_pos(state)
Convert a [State] to the Earth’s surface lat/lon/height on the WGS84 reference.
This requires the earth_000101_*.pck file to be loaded which contains the instantaneous earth frame information. The one provided by kete has dates from around 2000 to early 2024, along with predicts into the future. New files may be downloaded from the NAIF website for additional precision or years of epoch.
- Parameters:
state (State) – Convert the given state to latitude, longitude, and height in km on the WGS84 reference.