Skip to main content

Quick Spice Manager

PyPI PyPI - Python Version PyPI - License Coookiecutter - Wolt


Documentation: https://luca-penasa.github.io/quick-spice-manager

Source Code: https://github.com/luca-penasa/quick-spice-manager

PyPI: https://pypi.org/project/quick-spice-manager/


quick-spice-manager provides a straightforward way to download, cache, and load ESA SPICE kernels. The core of the library is an FTP-based download engine that fetches kernels directly from the ESA public FTP server (spiftp.esac.esa.int) with parallel transfers and progress reporting. QuickSpiceManager handles metakernel resolution, local caching, pool management, and environment-based overrides — so you can get a loaded kernel set with minimal boilerplate. Optional integration with planetary-coverage is available as an extras install.

Supported missions include JUICE, SOLAR-ORBITER, BEPICOLOMBO, MARS-EXPRESS, ROSETTA, and many more.

Installation

pip install quick-spice-manager

Note: The SpiceManager name is a deprecated alias for QuickSpiceManager and will be removed in a future release. Use QuickSpiceManager in new code.

Migrating from 0.1.x

0.1.x 0.2.0
SpiceManager QuickSpiceManager
sm.tour_config to get a TourConfig sm.get_tour_config()
sm.tour_config only to load kernels sm.load_kernels(); pass exclusive=False to keep what was loaded before

tour_config loads through planetary_coverage.TourConfig, which adds to the SPICE pool. load_kernels() defaults to exclusive=True and clears the pool first, so code that loads two metakernels one after the other keeps only the last one unless it passes exclusive=False.

Command line

Installing the package also installs qsm:

qsm missions                        # supported missions and aliases
qsm list -s juice --filter plan     # metakernels on the ESA FTP server
qsm download plan -s juice          # download the metakernel and its kernels
qsm resolve plan -s juice           # same, then print a furnshable metakernel path
qsm info plan -s juice              # what's cached, without using the network
qsm reduce plan -w 2032-12-18 2033-01-09 -o test_kernels --drop 'dsk/*'
                                    # a copy holding only that time window
qsm cache list                      # size and location of each cached mission
qsm cache clear juice               # delete a mission's cached kernels

MK is a shortcut (plan), a name (juice_plan), or the path to a local .tm file, and defaults to plan. --spacecraft defaults to JUICE. download and resolve also take --version to pin an SKD version, --kernels-dir, and --offline to never use the network.

qsm resolve prints only the path, and all progress and warnings go to stderr, so it can be used in scripts. It writes a copy of the metakernel with PATH_VALUES pointing at your local kernels, in the mission's cache, or wherever -o FILE says. It stays there until you clear the cache. Both download and resolve exit with an error if any referenced kernel is missing.

Use -v or -vv before the command for more logging (qsm -v download plan). The environment variables apply here too, and replace what's given on the command line; qsm prints a note when they're set.

Usage

Basic usage

from quick_spice_manager import QuickSpiceManager

# Downloads kernels automatically from the ESA FTP server and loads them.
# Kernels are cached in the platform user-cache directory and reused on
# subsequent calls — no re-download unless the cache is cleared.
sm = QuickSpiceManager(spacecraft="JUICE", mk="plan")
sm.load_kernels()

# ... use spiceypy directly ...

sm.unload_kernels()

Getting a furnshable metakernel path

resolved_mk triggers FTP download and PATH_VALUES rewriting without loading anything into the SPICE pool, giving you a ready-to-use metakernel path:

sm = QuickSpiceManager(spacecraft="JUICE", mk="plan")

import spiceypy
spiceypy.furnsh(str(sm.resolved_mk))  # pool management is yours

The result is cached — repeated access to sm.resolved_mk does not re-download or recreate the temp file.

Context manager

The preferred approach — kernels are loaded on entry and the original kernel pool is automatically restored on exit:

with QuickSpiceManager(spacecraft="JUICE", mk="plan") as sm:
    # kernels are loaded here; original pool is restored on exit
    ...

By default exclusive=True, which clears the entire SPICE pool before loading so that only the kernels from the chosen metakernel are active. Set exclusive=False to keep any previously loaded kernels alongside the new ones:

with QuickSpiceManager(spacecraft="JUICE", mk="plan", exclusive=False) as sm:
    ...

Listing available metakernels

sm = QuickSpiceManager(spacecraft="JUICE")
print(sm.metakernels)  # e.g. ['juice_plan', 'juice_plan_v462_20260223_001', ...]

Pinning a specific SKD version

By default version="latest" fetches the current unversioned metakernel and re-downloads it on each fresh resolution so you always get the latest kernel list. To pin a reproducible snapshot, pass the exact version tag from the FTP server:

sm = QuickSpiceManager(spacecraft="JUICE", mk="plan", version="v462_20260223_001")
sm.load_kernels()

The version tag is the suffix that appears in the versioned filenames listed by sm.metakernels (e.g. juice_plan_v462_20260223_001 → tag is v462_20260223_001). Pinned versions are looked up in kernels/mk/ first, then in kernels/mk/former_versions/. A FileNotFoundError is raised if the tag is not found, rather than silently falling back to a different version.

Adding extra kernels

Kernels furnished via add_kernel() are registered as intentional — is_dirty stays False and the pool can be snapshotted including them:

sm = QuickSpiceManager(spacecraft="JUICE", mk="plan")
sm.load_kernels()

sm.add_kernel("/path/to/extra.bc")                          # single file
sm.add_kernel(["/path/to/a.tls", "/path/to/b.bsp"])        # multiple files

Saving the current pool state

Write the live SPICE pool to a portable metakernel file that can be re-furnished later to reproduce the exact same set of loaded kernels, in the same order:

sm.snapshot_pool("/tmp/pool_snapshot.tm")

The pool belongs to the process, not to a manager, so the same function is available without one, whoever loaded the kernels (a manager, spiceypy.furnsh, another library):

from quick_spice_manager import snapshot_pool

snapshot_pool("/tmp/pool_snapshot.tm")

Kernels under one directory share a single $KERNELS path symbol; kernels spread over unrelated trees get one symbol per directory. Strings longer than SPICE's 80-character limit are split with + continuation. When the pool's metakernel is known, its SKD_VERSION / MK_IDENTIFIER are copied into the snapshot, and the kernels loaded on top of it are listed in its comments.

Reduced kernel sets (test data)

reduce_kernels writes a copy of a metakernel and its kernels that holds only the data inside some time windows, for example test data small enough to commit to a repository:

from quick_spice_manager import reduce_kernels

result = reduce_kernels(
    "5_1_150lb_23_1_a3",
    windows=[("2032-12-18", "2033-01-09"), ("2032-09-01", "2032-10-01")],
    out_dir="tests/data/spice",
    drop=["dsk/*"],               # kernels the workload does not need
)
print(result.summary())           # what happened to each kernel, and the sizes
QuickSpiceManager(mk=result.metakernel).load_kernels()

The data inside the windows is copied, not resampled, so the reduced set gives the same answers there:

kernel written
SPK, every type the records covering each window (spksub)
CK type 3 the pointing records covering each window, with their interpolation intervals
binary PCK type 2 the Chebyshev records covering each window (equal to rounding)
anything else copied whole: text kernels, DSKs, CKs of other types (spiceypy cannot write type 6), a CK whose SCLK is not defined

Each window is padded by a day (pad=, in seconds), so interpolation and extrapolation near its edges still work; overlapping windows are merged. A binary kernel without data in any window is left out. The reduced metakernel (out_dir/mk/<name>.tm, PATH_VALUES = ( '..' ), the layout of ESA's) and each reduced kernel's comment area record the source and the windows; the kernels keep their own comments.

For JUICE's juice_crema_5_1_150lb_23_1_a3 (882 MB), a 24-day window without the DSKs is 29 MB, 24.5 MB of which is the type 6 attitude CK, copied whole.

Pool management

print(sm.is_active)   # True if this manager currently owns the SPICE pool
print(sm.is_dirty)    # True if kernels were added/removed since load_kernels()
sm.clean_pool()       # unload extras and re-furnish missing kernels

Inspecting the current configuration

sm.config returns a pandas DataFrame — spacecraft, version, the metakernel's own SKD_VERSION / MK_IDENTIFIER (when it declares them), the resolved metakernel path, and kernels directory — resolved entirely from this manager's own state. Unlike tour_config below, it does not require the planetary-coverage extra and doesn't report target/instrument, since those belong to TourConfig, not this manager:

print(sm.config)

Documenting which kernels were used

kernel_provenance() reports the minimum information needed to reproduce the currently active kernel set — e.g. when generating PDS4 labels for processing performed on downlinked data. Rather than flattening every individual kernel file, it cites the metakernel itself (its real, resolved filename — with the SKD version baked in when pinned) plus only the kernels added on top of it (e.g. via add_kernel()):

info = sm.kernel_provenance()
info["metakernel"]       # '.../juice_plan_v462_20260223_001.tm'
info["spacecraft"]       # 'JUICE'
info["version"]          # 'v462_20260223_001' (or 'latest')
info["resolved_at"]      # ISO-8601 UTC timestamp of when this was resolved --
                          # the closest thing to a version string when
                          # version='latest' was used
info["kernels_dir"]      # directory the metakernel's kernels were loaded from
info["extra_kernels"]    # kernels added beyond the metakernel, e.g. via add_kernel()
info["all_kernels"]      # every kernel currently loaded, flattened

Pass source="pool" to inspect the live SPICE pool directly instead of this manager's own bookkeeping — useful when kernels were furnished by another manager instance or via raw spiceypy calls (works even without ever calling load_kernels() on this instance):

info = sm.kernel_provenance(source="pool")

The pool itself holds a temporary, localized copy of the metakernel; source="pool" reports the real metakernel it was made from, also after the manager that loaded it has been garbage-collected. (The temporary copy is kept on disk while it is in the pool, and deleted by unload_kernels() or at interpreter exit.)

Cache management

print(sm.cache_size)   # human-readable size of the kernel cache
sm.clear_cache()       # delete cached kernels (will re-download on next use)

Using a local metakernel

Pass the path to an existing .tm file to skip FTP resolution. The kernels are the ones the metakernel itself points to: its PATH_VALUES, resolved relative to the metakernel's own folder. For an ESA kernel dataset (e.g. JUICE.zip, whose metakernels use PATH_VALUES = ( '..' )) that is the dataset's kernels/ folder:

sm = QuickSpiceManager(mk="/path/to/JUICE/kernels/mk/juice_crema_5_1_150lb_23_1_a3.tm")
sm.load_kernels()   # loads /path/to/JUICE/kernels/...

Pass kernels_dir (or set SPICE_DIRECTORY) to load the kernels from another folder instead:

sm = QuickSpiceManager(mk="/path/to/my_local.tm", kernels_dir="/path/to/kernels")

A local metakernel that doesn't declare exactly one PATH_VALUES entry falls back to the download cache directory, as metakernels resolved via FTP do.

planetary-coverage integration

QuickSpiceManager itself only handles SPICE kernels — it carries no target/instrument/geometry state of its own. get_tour_config() is a thin, on-demand bridge to planetary_coverage.TourConfig for downstream analysis. Requires the optional planetary-coverage extra:

pip install quick-spice-manager[planetary-coverage]
sm = QuickSpiceManager(spacecraft="JUICE", mk="plan")

# Builds a TourConfig with the given target/instrument.
tc = sm.get_tour_config(target="Jupiter", instrument="JANUS")
print(tc.coverage)

Deprecated: the old tour_config property (no target/instrument control, always target='Jupiter'/instrument='JANUS') still works for backward compatibility, but emits a DeprecationWarning — use get_tour_config() instead.

Environment variable overrides

Two environment variables (readable from a .env file in the working directory) let you override the FTP-based workflow without changing code:

Variable Effect
SPICE_METAKERNEL Path to a local metakernel file. Disables automatic FTP download.
SPICE_DIRECTORY Directory containing the kernel files referenced by the metakernel. Takes precedence over kernels_dir and over the metakernel's own PATH_VALUES.
# .env
SPICE_METAKERNEL=/data/kernels/juice_ops.tm
SPICE_DIRECTORY=/data/kernels

Supported missions

The FTP downloader supports the following ESA missions (case-insensitive, common aliases accepted):

Mission Accepted names
BepiColombo BEPICOLOMBO, MPO, MTM, MMO
Comet Interceptor COMET-INTERCEPTOR
EnVision ENVISION
ExoMars 2016 EXOMARS2016, TGO, EDM
ExoMars RSP EXOMARSRSP
Gaia GAIA
Hera HERA
Huygens HUYGENS, CASP
INTEGRAL INTEGRAL
JUICE JUICE
JWST JWST
Mars Express MARS-EXPRESS, MEX, BEAGLE2
Rosetta ROSETTA
SMART-1 SMART-1
Solar Orbiter SOLAR-ORBITER, SOLO
Venus Express VENUS-EXPRESS, VEX

Logging

Logging is disabled by default. Enable it for debugging:

from quick_spice_manager import log_enable, log_enable_debug

log_enable()        # INFO level
log_enable_debug()  # DEBUG level

Concurrency & multi-process safety

The underlying CSPICE toolkit keeps a single, process-global kernel pool that is not thread-safe. quick-spice-manager handles this with a two-tier model:

  1. In-process (threads): every pool operation (load_kernels, unload_kernels, add_kernel, clean_pool, pool queries) is serialized by a single re-entrant lock. with QuickSpiceManager(...) as sm: holds this lock for the entire block, so the whole load → use → unload lifecycle is one critical section — a second thread's with block (or a direct load_kernels() call) waits until the first one fully exits. Advanced users calling spiceypy directly can join the same critical section via QuickSpiceManager.pool_lock.
  2. Cross-process (the on-disk kernel cache): kernel downloads write to a temp file and atomically rename it into place, so a reader never sees a truncated file, and each destination file is guarded by its own cross-process lock, so two processes racing to fetch the same missing kernel only download it once. clear_cache() is serialized against other clear_cache() calls the same way.
  3. Cross-process (total FTP connection count): per-file locking alone doesn't stop many independent managers or processes from each opening their own batch of parallel FTP connections at once. A small, fixed number of connection "slots" (shared by every QuickSpiceManager instance and OS process for this user, regardless of mission or kernels_dir) bounds the total number of simultaneous connections to ESA's FTP server machine-wide, so a burst of concurrent downloads waits its turn instead of overwhelming the server.
  4. Cross-process (resolving + furnishing): load_kernels() also takes a turn in a small, bounded pool of "furnish slots" scoped per kernels_dir, held across both the resolve/download-check step and the actual furnsh() calls. This keeps a burst of managers/processes cold-starting against the same cache directory from all hammering the same kernel files at once — by the time a manager gets its turn, an earlier holder has usually already finished preparing everything, so its own prepare step is a fast, local no-op. Different missions (different kernels_dir) never wait on each other.

Separate OS processes never need to coordinate over furnsh/unload/pool queries once kernels are loaded — each process owns an independent CSPICE kernel pool, so read-only querying across processes works without any locking. The furnish-slot mechanism above only throttles the loading step itself (a resource/throughput concern, not a correctness one), not anything that happens afterwards. Only the shared cache directory, the FTP connection count, and the furnish/prepare step are genuinely cross-process resources. One accepted limitation: clear_cache() isn't coordinated against concurrently in-flight downloads from other processes, so avoid calling it while other processes may be actively loading kernels from the same cache.

Working offline / when the ESA FTP server is unreachable

A small local cache remembers what each FTP call last returned, so the library degrades gracefully instead of hard-failing when there's no network:

  • Pinned versions never need the network twice. Once a specific version tag (e.g. version="v462_20260223_001") has been fully resolved and downloaded, later calls for the same spacecraft/mk/version skip the FTP server entirely — a pinned version tag never changes once published.
  • version="latest" (the default) tries a live check first — its whole point is to discover newly published kernels, so it never silently serves stale data while online. Only if the ESA FTP server truly can't be reached (DNS failure, timeout, connection refused, etc.) does it fall back to the last fully-verified local resolution, logging a warning that the result may not reflect the newest kernels. Set QSM_LATEST_MAX_AGE to reuse a resolution verified online less than that many seconds ago without asking the server; kernels published in the meantime are picked up at the next check.
  • An unreachable server costs a few seconds, once. Before connecting, a short TCP probe checks that the server answers, and the answer is remembered in the process for 2 minutes: on a network that blocks the server, the first manager waits for the probe and the next ones go straight to the cache. Real FTP connections time out too, instead of waiting for the operating system's connect timeout (about two minutes on Linux).
  • sm.metakernels (the list of available metakernels) gets the same treatment: cached after each successful listing, reused with a warning if the server can't be reached.
  • If nothing usable is cached when the server is unreachable, a clear ConnectionError is raised (naming exactly which referenced kernel files are still missing, if a partial cache exists) instead of a raw socket error several layers down.

This is transparent — no configuration needed — and lives alongside the regular kernel cache (<kernels_dir>/.resolution_cache.json), so clear_cache() clears it too.

These environment variables tune it (read on each call, so setting os.environ in a running notebook works):

Variable Default Effect
QSM_OFFLINE unset 1 never touches the network, everywhere (like download_kernels=False): resolve from the cache, or fail clearly. For air-gapped machines and CI.
QSM_LATEST_MAX_AGE 0 Seconds a "latest" resolution verified online is reused without asking the server. 0 checks on every call.
QSM_FTP_PROBE_TIMEOUT 3 Seconds the reachability probe waits for the server.
QSM_FTP_RETRY_AFTER 120 Seconds the probe's answer is remembered in the process.
QSM_FTP_TIMEOUT 30 Seconds each FTP socket operation may wait (a limit on silence, not on the length of a download).

Development

  • Clone this repository
  • Requirements:
    • uv
    • Python 3.10+
  • Create a virtual environment and install the dependencies
uv sync

Testing

uv run pytest

Documentation

The documentation is automatically generated from the content of the docs directory and from the docstrings of the public signatures of the source code. The documentation is updated and published as a Github Pages page automatically as part each release.

Releasing

Manual release

Releases are done with the command, e.g. incrementing patch:

uv run just bump patch
# also push, of course:
git push origin main --tags

this will update the changelog, commit it, and make a corresponding tag.

as the CI is not yet configured for publish on pypi it can be done by hand:

uv build
uv publish --build path/to/wheel

Automatic release - to be fixed

Trigger the Draft release workflow (press Run workflow). This will update the changelog & version and create a GitHub release which is in Draft state.

Find the draft release from the GitHub releases and publish it. When a release is published, it'll trigger release workflow which creates PyPI release and deploys updated documentation.

Updating with copier

To update the skeleton of the project using copier:

uvx copier update --defaults

Pre-commit

Pre-commit hooks run all the auto-formatting (ruff format), linters (e.g. ruff and mypy), and other quality checks to make sure the changeset is in good shape before a commit/push happens.

You can install the hooks with (runs for each commit):

pre-commit install

Or if you want them to run only for each push:

pre-commit install -t pre-push

Or if you want e.g. want to run all checks manually for all files:

pre-commit run --all-files

This project was generated using a fork of the wolt-python-package-cookiecutter template.

Metadata

Release files for quick-spice-manager 0.2.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for quick-spice-manager 0.2.5
File Size Uploaded Provenance Actions
quick_spice_manager-0.2.5.tar.gz 53.9 kB Without provenance Details for quick_spice_manager-0.2.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for quick-spice-manager 0.2.5
File Interpreter ABI Platform Actions
quick_spice_manager-0.2.5-py3-none-any.whl Python 3 none any Details for quick_spice_manager-0.2.5-py3-none-any.whl

Total release size: 111.8 kB

Release files / quick_spice_manager-0.2.5.tar.gz

Download URL quick_spice_manager-0.2.5.tar.gz
Size 53.9 kB
Tags Source
SHA-256 checksum
How to use checksums
5ac57d9816282a89fee9e2ce2a0c1b2d9b217824733dfbb4949fcb97d6e338e5
BLAKE2b-256 checksum
How to use checksums
b7fa3d89bdea6cf4d0f1fcfe77ed7322562cfc30d985243b9029386127024b2f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.23 {"installer":{"name":"uv","version":"0.12.23","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Manjaro Linux","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / quick_spice_manager-0.2.5-py3-none-any.whl

Download URL quick_spice_manager-0.2.5-py3-none-any.whl
Size 57.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
05672fd66088cb912ecb3c9278d0fa477c65889f725f1416a70597ebf6113d7c
BLAKE2b-256 checksum
How to use checksums
94e7e024b57f64bba52f795c009b72f932b8cc3b572a2b578a8063684c87a2b2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.23 {"installer":{"name":"uv","version":"0.12.23","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Manjaro Linux","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for quick-spice-manager 0.2.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page