SpiceyPy

8.1.0 · active · verified Fri Apr 17

SpiceyPy is a Python wrapper for NASA's NAIF CSPICE Toolkit, providing tools for computing ephemeris, attitude, event finding, and geometry for spacecraft and celestial bodies. It enables Python users to leverage the powerful CSPICE library. The library is actively maintained with frequent releases, currently at version 8.1.0, and often includes performance enhancements and new features.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates loading a leap second kernel (LSK) using `spice.furnsh()`, converting a UTC time string to Ephemeris Time (ET) with `spice.str2et()`, and then calculating the position of Earth relative to the Sun using `spice.spkpos()`. It's crucial to download and correctly point to actual SPICE kernel files (LSK, PCK, SPK, FK, IK, CK) from the NAIF website for real applications. The example includes a placeholder for a kernel path.

import spiceypy as spice
import os

# A simple kernel file for demonstration
# In a real application, you would download these from NAIF
# For local testing, ensure naif0012.tls is in the script's directory
# or specify its full path.
kernel_path = os.path.join(os.path.dirname(__file__), 'naif0012.tls')
if not os.path.exists(kernel_path):
    # This is a dummy for demonstration. You would fetch a real kernel.
    print(f"Warning: '{kernel_path}' not found. Please download from NAIF if this isn't a test.")
    # Example: You'd typically download like this (replace with actual URL and process)
    # import urllib.request
    # url = 'https://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/naif0012.tls'
    # urllib.request.urlretrieve(url, kernel_path)

# Load a leap second kernel (LSK) to define Ephemeris Time (ET)
try:
    spice.furnsh(kernel_path)
except spice.exceptions.SpiceyPyError as e:
    print(f"Failed to load kernel: {e}. Skipping calculations.")
    exit()

# Convert a UTC string to Ephemeris Time (ET)
utc_time = '2023-01-01 T00:00:00'
et = spice.str2et(utc_time)
print(f"UTC: {utc_time} -> ET: {et}")

# Get position of Earth relative to the Sun
# Observer: SUN, Target: EARTH, Reference Frame: J2000, Aberration Correction: NONE
pos, lt = spice.spkpos('EARTH', et, 'J2000', 'NONE', 'SUN')
print(f"Position of Earth relative to Sun (km): {pos}")

# Unload all kernels
spice.unload(kernel_path)
# Alternatively, spice.kclear() clears all loaded kernels

view raw JSON →